此代码块用于同时拥有密钥和iv集,取自C# Encryption to PHP Decryption
我试图将其更改为使用生成的iv,该iv会添加到结果输出中。加密工作正常(测试解密是通过php完成的,效果很好)但是我无法使用C#加密文本与C#decrypt函数获得相同的结果。任何人都可以指出我忽略的东西吗?
我看到的错误是Bad PKCS7填充。长度x无效,其中x变化。
private static readonly byte[] Key = Convert.FromBase64String("REMOVED");
private const int IvBytes = 32;
public static string Encrypt(string prm_text_to_encrypt)
{
var sToEncrypt = prm_text_to_encrypt;
var rj = new RijndaelManaged()
{
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
KeySize = 256,
BlockSize = 256,
Key = Key,
};
rj.GenerateIV ();
var encryptor = rj.CreateEncryptor();
var msEncrypt = new MemoryStream();
var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
var toEncrypt = Encoding.ASCII.GetBytes(sToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
var encrypted = msEncrypt.ToArray();
return (Convert.ToBase64String(rj.IV.Concat(encrypted).ToArray()));
}
public static string Decrypt(string prm_text_to_decrypt)
{
var sEncryptedString = prm_text_to_decrypt;
var rj = new RijndaelManaged()
{
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
KeySize = 256,
BlockSize = 256,
Key = Key
};
var decryptor = rj.CreateDecryptor();
var tmp = Convert.FromBase64String(sEncryptedString);
var fromEncrypt = new byte[tmp.Length];
byte[] IV = tmp.Take(IvBytes).ToArray();
byte[] sEncrypted = tmp.Skip(IvBytes).ToArray();
rj.IV = IV;
var msDecrypt = new MemoryStream(sEncrypted);
var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return (Encoding.ASCII.GetString(fromEncrypt));
}