我想解密Java中的C#加密數據,但沒有成功。我正在使用128位密鑰&塊大小與PKCS7填充。下面是C#代碼:AES加密C#解密Java?
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"));
}
任何想法可能是錯誤的?
感謝
UPDATE
對不起,怎麼啞了我的,我忘了寫實際的錯誤信息。這裏,它是:在線程 「主」 javax.crypto.BadPaddingException
例外:墊塊 在的javax在 org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(未知 源)損壞.crypto.Cipher.doFinal(Cipher.java:1970)
感謝
什麼實際上不起作用?拋出異常還是數據被破壞? – Fildor 2013-04-25 14:56:31
@Fildor,thansk爲我指點,我更新了我的帖子:) – Davita 2013-04-25 22:08:55
這已經解決了Davida?對不起,如果我沒有更直接的答案... – 2013-05-05 09:23:15