AES加密C#解密Java?

时间:2013-04-25 14:51:01

标签: c# java encryption aes rijndael

我正在尝试用Java解密C#加密数据但没有成功。我使用128位密钥和块大小与PKCS7填充。这是C#代码:

    public byte[] Encrypt(byte[] data, byte[] key)
    {
        using (var ms = new MemoryStream())
        {
            using (var aes = RijndaelManaged.Create())
            {
                aes.Key = key;
                aes.IV = key;
                var stream = new CryptoStream(ms, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write);
                stream.Write(data, 0, data.Length);
                stream.FlushFinalBlock();
                return ms.ToArray();
            }
        }
    }

这是java代码:

private static Key generateKey() throws Exception {

    Key key = new SecretKeySpec(Files.readAllBytes(Paths.get("D:/Temp/cr.key")), "AES");

    return key;
}

public static byte[] decrypt(byte[] encryptedData) throws Exception {
    Key key = generateKey();

    Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

    IvParameterSpec ivSpec = new IvParameterSpec(key.getEncoded());
    c.init(Cipher.DECRYPT_MODE, key, ivSpec);

    System.out.println(c.getBlockSize());


    c.update(encryptedData);
    byte[] decValue = c.doFinal();
    return decValue;
}

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] bb = decrypt(Files.readAllBytes(Paths.get("d:\\Temp\\cr~\\OEBPS\\Chapter001.html")));
           //decompressFile(bb, new File("D:\\Temp\\enc.html"));
}

知道可能出现什么问题吗?

感谢

更新


抱歉,我多么愚蠢,我忘了写实际的错误信息。这是:

  

线程“main”中的异常javax.crypto.BadPaddingException:pad块   腐败了   org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(未知   来源)在javax.crypto.Cipher.doFinal(Cipher.java:1970)

由于

1 个答案:

答案 0 :(得分:1)

您忘记了Cipher.update(byte[]): byte[]只要处理完整个密文块就会返回数据。

注意:显然不是这个问题的答案,因为异常指向另一个错误。但是上面代码中的一个错误就不足了。