加密方式使用 AES 加密,再转成 Base64。
SQL
-- 加密
update your_table set your_column=to_base64(aes_encrypt(your_column, "password"));-- 解密
select aes_decrypt(from_base64(your_column) ,"password") from your_table;
使用原生
public class AESUtils {/*** AES 加密操作** @param data 待加密内容* @param aesKey 加密的Key* @return 返回Base64转码后的加密数据* @throws Exception*/public static String encrpt(String encrptData, String aesKey) throws Exception {Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(aesKey));byte[] encrypted = cipher.doFinal(encrptData.getBytes());return Base64.encode(encrypted);}/*** AES 解密操作** @param decrptData* @param aesKey* @return 返回解密内容* @throws Exception*/public static String decrpt(String decrptData, String aesKey) throws Exception {Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(aesKey));byte[] doFinal = cipher.doFinal(Base64.decode(decrptData));return new String(doFinal);}private static SecretKeySpec getSecretKeySpec(String key) {byte[] keyBytes = Arrays.copyOf(key.getBytes(), 16);return new SecretKeySpec(keyBytes, "AES");}public static void main(String[] args) throws Exception {String aesKey = "1234567890";String encrpt = encrpt("128931739@163.com", aesKey);System.out.println(encrpt);System.out.println(decrpt(encrpt, aesKey)); //解密 加密的数据}
}
使用 Hutool
public class AESUtils {/*** AES 加密操作** @param encodedData 待加密内容* @param aesKey 加密的Key* @return 返回Base64转码后的加密数据* @throws Exception*/public static String encrpt(String encodedData, String aesKey) {return Base64.encode(SecureUtil.aes(getSecretKey(aesKey)).encrypt(encodedData));}/*** AES 解密操作** @param decrptData 待解密内容* @param aesKey 解密的Key* @return 返回解密内容* @throws Exception*/public static String decrpt(String decrptData, String aesKey) {return SecureUtil.aes(getSecretKey(aesKey)).decryptStr(Base64.decode(decrptData));}private static byte[] getSecretKey(String key) {byte[] keyBytes = Arrays.copyOf(key.getBytes(), 16);return SecureUtil.generateKey("AES", keyBytes).getEncoded();}public static void main(String[] args) {String aesKey = "1234567890";String encrpt = encrpt("128931739@163.com", aesKey);System.out.println("-->加密后字符串: " + encrpt);System.out.println("-->解密后字符串: " + decrpt(encrpt, aesKey)); //解密 加密的数据}
}