0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点# java通过mysql的加解密函数实现敏感字段存储

 java通过mysql的加解密函数实现敏感字段存储

1.AES加解密工具类:

public class AESUtils {

public static String encrypt(String password, String strKey) {
try {
SecretKey key = generateMySQLAESKey(strKey,"ASCII");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = password.getBytes("UTF-8");
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(Hex.encodeHex(ciphertextBytes));

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

public static String decrypt(String content, String aesKey){
try {
SecretKey key = generateMySQLAESKey(aesKey,"ASCII");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] cleartext = Hex.decodeHex(content.toCharArray());
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(ciphertextBytes, "UTF-8");

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (DecoderException e) {
e.printStackTrace();
}
return null;
}


public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) {
try {
final byte[] finalKey = new byte[16];
int i = 0;
for(byte b : key.getBytes(encoding))
finalKey[i++%16] ^= b;
return new SecretKeySpec(finalKey, "AES");
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

public static String getAesKey(){
StringBuilder sb = new StringBuilder();
Random random = new Random();
for(int i = 0; i < 16; i++){
sb.append(random.nextInt(10));
}
return sb.toString();
}

public static void main(String[] args){
String abc = "1";
String aeskey = "3532263592381276";
String a1= encrypt(abc, aeskey);
System.out.println("加密后:" + a1);
System.out.println("解密后:" +decrypt(a1, aeskey));
}


}

运行main方法结果:

加密后:62b778a8ccaa40cce4c9e4e42c693665
解密后:1

2.mysql的sql加解密:

生成16随机盐:3532263592381276

select  concat((SELECT CEILING(RAND()*9000000000000000+1000000000000000)),'');

加密:62B778A8CCAA40CCE4C9E4E42C693665

SELECT (HEX(AES_ENCRYPT(1,"3532263592381276")))

解密:1

SELECT AES_DECRYPT(UNHEX("62B778A8CCAA40CCE4C9E4E42C693665"),"3532263592381276")

3.实现效果:

java工具类加解密和mysql的加解密效果是一样的。


举报

相关推荐

0 条评论