简体   繁体   English

解密使用Java加密的MySQL字段

[英]Decrypt MySQL fields that were encrypted using Java

I have some String fields that are being encrypted/encrypted using the following Java methods: 我有一些使用以下Java方法加密/加密的String字段:

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);
    }
}  

The methods are working as desired for both encrypting and decryption by calling the respective method. 通过调用相应的方法,这些方法可以按要求工作,以进行加密和解密。 I am persisting the encrypted Strings to a MySQL database. 我将加密的字符串保留到MySQL数据库中。 I would like to occasionally decrypt the Strings while in the MySQL command line. 我想偶尔在MySQL命令行中解密字符串。 I've been trying to use 我一直在尝试使用

SELECT AES_DECRPYT(encrypted_field, MySuperSecretKey), FROM table;

However, this is returning a null results for all the fields in that column. 但是,这将为该列中的所有字段返回null结果。 Am I able to decrypt AES encrypted fields in MySQL that weren't encrypted by MySQL? 我可以解密MySQL中未加密的AES加密字段吗?

It appears the issue I was having was that I was forgetting about the BASE64Encoder that I was using to encrypt the Strings on the Java side. 看来我遇到的问题是我忘记了我用来在Java端加密字符串的BASE64Encoder I was able to get the correct data back with the following MySQL command: 我可以使用以下MySQL命令获取正确的数据:

SELECT AES_DECRYPT(FROM_BASE64(encrypted_field), 'MySuperSecretKey') FROM table;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM