异或:a.同为0,异为1;
b.一个数,两次异或之后,是原数本身 - 加密 解密
a(97) - 01100001
3 - 00000011
a与3的异或 01100010 一次异或后的结果
3 - 00000011
再次与3异或 01100001
"xxxx" - 异或一次 --》 加密
//异或实现加密与解密: 传入String("abc") --> String("xyz")
public static String xor(String input){ //"abc" --> {'a','b','c'} --> {'x','y','z'} -->"xyz"
char[] chs = input.toCharArray();
for(int i=0;i<chs.length;i++){
//对每一位字符进行加密:与任意一个数字进行异或(^) a->x char<int
chs[i]=(char) (chs[i]^3000);
}
return new String(chs);//{'x','y','z'} -->"xyz"
}
Base64
加密:
任何类型byte[] --> 字符串形式String
解密:
字符串形式String --> 任何类型byte[]
public static String base64Encode(byte[] input){
String result=null;
try {
Class cla=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method method =cla.getMethod("encode", byte[].class);
result = (String) method.invoke(null, input);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
//Base64解密
public static byte[] base64Decode(String input){
byte[] result =null;
try {
Class cla=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method method = cla.getMethod("decode", String.class);
result = (byte[]) method.invoke(null, input);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
MD5/SH256:字节串 --> 十六进制串
不可逆(只能加密,不能解密)
"a" -- "5145ab15165"
//MD5加密
public static String md5Encode(byte[] input){//byte[]("abc") --> String("121515")
return DigestUtils.md5Hex(input);//byte[] -->String
};
//SH256加密
public static String sha256Encode(byte[] input){
return DigestUtils.sha256Hex(input);
}
Base64直接依赖于JDK
MD5/SHA依赖于三方JAR:commons-codec.jar
Base64/异或:可逆(加密、解密)
MD5/SHA:不可逆
视频学习地址:https://ke.qq.com/course/list/DT