我有一些使用以下Java方法加密/加密的字符串字段:
public class Encryptor {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue =
new byte[] { 'M', 'y', 'S', 'u', 'p', 'e', 'r', 'S',
'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = cipher.doFinal(valueToEnc.getBytes());
return new BASE64Encoder().encode(encValue);
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
byte[] decValue = cipher.doFinal(decodedValue);
return new String(decValue);
}
private static Key generateKey() throws Exception {
return new SecretKeySpec(keyValue, ALGORITHM);
}
}
通过调用相应的方法,这些方法可以根据需要进行加密和解密。我将加密的字符串持久化到MySQL数据库。我想在MySQL命令行中偶尔解密字符串。我一直在尝试使用
SELECT AES_DECRPYT(encrypted_field, MySuperSecretKey), FROM table;
但是,这会为该列中的所有字段返回null
个结果。我能解密MySQL中未加密的AES加密字段吗?
答案 0 :(得分:0)
我遇到的问题似乎是忘记了我用来加密Java端字符串的BASE64Encoder
。我能够使用以下MySQL命令获取正确的数据:
SELECT AES_DECRYPT(FROM_BASE64(encrypted_field), 'MySuperSecretKey') FROM table;