.NET中的加密和Android中的解密会引发BadPaddingException:pad块损坏
作者:互联网
我做了很多研究但是找不到我的问题的答案.我在.NET中进行AES加密(Rijndael块大小为128位),在Android(AES)中使用相同的密码进行解密,盐和密码.四他们之间.
C#加密代码段:
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Padding = PaddingMode.PKCS7;
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
Android Decryption代码段:
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithSHA1And128BitAES-CBC-BC").generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv.getBytes()));
byte[] decrypted = cipher.doFinal(encrypted);
cipher.doFinal调用抛出异常.
“05-02 18:17:38.239:W / System.err(25547):javax.crypto.BadPaddingException:pad block corrupted”
我确实在.NET和Android中将填充设置为“PKCS7Padding”,加密块大小为128位.
但是,在Android和Android中进行加密在Android中解密工作正常.与.NET中的加密和.NET中的Decrypt相同也可以.
样品测试:
String PlainText = "hello world";
String EncryptedDotNetblob = "JyijoGEALMI25Zej7d+fMg==";
String EncryptedAndroidblob = "1HhuTQaLRJEK4zxI9FAO6A==";
正如你所看到的,blob也是不同的.
谁知道这里有什么问题?
解决方法:
您导出的键是不同的,这就是您收到错误的原因(将它们记录为十六进制字符串以进行检查). PasswordDeriveBytes使用修改版本的PBKDF1,另一方面,SecretKeyFactory.getInstance(“PBEWithSHA1And128BitAES-CBC-BC”)为您提供了一个密钥工厂,它可以根据PKCS#12的规定派生密钥.这些是不同的算法,并产生不同的密钥.使用.NET中的Rfc2898DeriveBytes和具有相同参数的SecretKeyFactory .getInstance(“PBKDF2WithHmacSHA1”)来获取相同的密钥.
标签:android,net,aes,rijndaelmanaged 来源: https://codeday.me/bug/20190709/1415509.html