我试图在 Java 中解密 C# 加密数据但没有成功。我使用 PKCS7 填充的 128 位密钥和块大小。这是 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"));
}
知道有什么问题吗?
谢谢
更新
对不起,我真笨,我忘了写实际的错误信息。这里是:
线程“主”javax.crypto.BadPaddingException 中的异常:在 javax.crypto.Cipher.doFinal(Cipher.java:1970) 的 org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source) 处的垫块损坏
谢谢