cI编写了用于加密和解密byte []的代码。当我将填充模式设置为PKCS7时,我得到无效的填充错误。虽然,当我将填充模式更改为零时,加密和解密工作正常。以下是代码,如果有人可以看看,看看他们是否可以指出问题:
public static byte[] encryptBytes(byte[] plainText, string keyPath)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
byte[] cipherText = new byte[plainText.Length];
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
byte[] tempKey, tempIV;
int keySize = ((int)(new FileInfo(keyPath).Length)) - 16;
readKeyIV(keyPath, keySize, out tempKey, out tempIV);
rijAlg.Padding = PaddingMode.Zeros;
rijAlg.Mode = CipherMode.CBC;
rijAlg.KeySize = keySize * 8;
rijAlg.BlockSize = rijAlg.KeySize;
rijAlg.Key = tempKey;
rijAlg.IV = tempIV;
ICryptoTransform encryptor = rijAlg.CreateEncryptor();
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
//Write all data to the stream
csEncrypt.Write(plainText, 0, plainText.Length);
}
cipherText = msEncrypt.ToArray();
}
return cipherText;
}
}
/// <summary>
/// takes a byte array of cipher text and a key then returns the decrypted byte array
/// </summary>
/// <param name="cipher"></param>
/// <param name="keyPath"></param>
public static byte[] decryptBytes(byte[] cipher, string keyPath)
{
if (cipher == null || cipher.Length <= 0)
throw new ArgumentNullException("plainText");
byte[] plainText = new byte[cipher.Length];
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
byte[] tempKey, tempIV;
int keySize = ((int)(new FileInfo(keyPath).Length)) - 16;
readKeyIV(keyPath, keySize, out tempKey, out tempIV);
rijAlg.Padding = PaddingMode.Zeros;
rijAlg.KeySize = keySize * 8;
rijAlg.BlockSize = rijAlg.KeySize;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Key = tempKey;
rijAlg.IV = tempIV;
ICryptoTransform decryptor = rijAlg.CreateDecryptor();
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Write))
{
//Write all data to the stream
csEncrypt.Write(cipher, 0, cipher.Length);
}
plainText = msEncrypt.ToArray();
}
return plainText;
}
}
从磁盘上的文件读取密钥和IV,并在调用函数之前生成。我做了大量的研究,发现了一些我在发布这个问题之前尝试过的解决方案,但它们并不适用于我。
有谁能告诉我我做错了什么以及为什么错了。
编辑:解密数据时会出现问题。我测试它的方法是读取一个文件并将其内容传递给encryptBytes函数,以加密形式将其写入磁盘,将其读回并将其提供给decryptBytes函数,然后以解密形式将结果存储在磁盘上。正如我所说的,如果我使用Zeros填充,一切都很好,但是一旦我将其更改为PKCS7,它就会给我错误。 感谢