简单的异或加密,用于前后端数据传输加密
1、加密String
/**
* 加密 String 类型
*
* @param content
* @param secretKey
* @return
*/
public static String encryptByDES(String content, String secretKey) {
byte[] data = null;
try {
if (Objects.isNull(secretKey)){
return content;
}
data = content.getBytes("UTF-8");
byte[] key = secretKey.getBytes("UTF-8");
for (int i = 0; i < data.length; i++) {
data[i] ^= key[i % key.length];
}
} catch (Exception e) {
}
return new String(data);
}
2、解密-加密String
/**
* 解密-加密的String
*
* @param content
* @param secretKey
* @return
*/
public static String decryptByDES(String content, String secretKey) {
char[] data = new char[content.length()];
try {
if (Objects.isNull(secretKey)){
return content;
}
content.getChars(0, content.length(), data, 0);
char[] key = new char[secretKey.length()];
secretKey.getChars(0, secretKey.length(), key, 0);
for (int i = 0; i < data.length; i++) {
data[i] ^= key[i % key.length];
}
} catch (Exception e) {
}
return new String(data);
}
3、测试
public static void main(String[] args) {
String str = "123456";
String secretKey = "hello word !";
String result = encryptByDES(str, secretKey);
System.out.println("加密结果:" + result);
result = decryptByDES(result, secretKey);
System.out.println("解密结果:" + result);
}
注:密钥,后端可以使用登录后生成的token进行加密,前端使用token解密