【问题标题】:Decrypt MySQL fields that were encrypted using Java解密使用 Java 加密的 MySQL 字段
【发布时间】:2016-06-01 20:57:11
【问题描述】:

我有一些使用以下 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 中未由 MySQL 加密的 AES 加密字段?

【问题讨论】:

    标签: java mysql encryption cryptography


    【解决方案1】:

    看来我遇到的问题是我忘记了我用来加密 Java 端字符串的 BASE64Encoder。我能够使用以下 MySQL 命令取回正确的数据:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 2013-05-15
      • 1970-01-01
      • 2011-08-30
      • 2017-07-06
      相关资源
      最近更新 更多