Java,解码AES-256时出错

时间:2014-03-15 17:47:05

标签: java android cryptography aes

我在解密时收到错误:(javax.crypto.BadPaddingException:错误:06065064:数字信封例程:EVP_DecryptFinal_ex:bad decrypt)

我的代码加密/解密:

private static byte[] password = null; //  this.password = editText.getBytes();
static final byte[] ivBytes = {'6','g','6','o','d','a','0','u','4','n','w','i','6','9','i','j'};

public static byte[] encrypt(String text) throws Exception {
    byte[] clear = text.getBytes("UTF-8");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(password);
    kgen.init(256, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] key = skey.getEncoded();

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}

public static String decrypt(byte[] encrypted) throws Exception {
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(password);
    kgen.init(256, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] key = skey.getEncoded();

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
    String decrypted = new String(cipher.doFinal(encrypted));
    return decrypted;
}

我怀疑bug generateKey。

3 个答案:

答案 0 :(得分:2)

你做错了两件事:

  • 使用密钥为PRNG播种密钥从密码生成密钥是个坏主意。请改用基于密码的加密。 Java有一个PKCS#5的实现,它将从密码生成一个密钥。

  • 您需要为每次加密使用新的强随机IV:

    • 加密时,请勿在cipher.init()中指定IV。将为您生成一个新的。
    • encrypt()需要将IV(cipher.getIV())和密文序列化为字节数组。
    • decrypt():将IV与密文分开,从中构建一个IvParameterSpec,并按照您目前的方式输入cipher.init()。

答案 1 :(得分:0)

您的问题是,当您解密时,您生成一个新的密钥而不是从密码中获取它。查看this blog post以了解如何实施基于密码的加密。有加密和解密功能的例子。

答案 2 :(得分:-1)

替换以下行:

<div class="col-md-1" style="text-align: right">
    @Html.Label("Public", new { @class = "control-label" })
    @Html.CheckBox("PublicNote", new { @class = "chk=style", @checked = "checked" })
</div>

以下行:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");