我有一个PHP应用程序,使用openSSL将带有Base64编码的AES-256-CBC加密字符串发送到.NET应用程序。我启动了decrypt方法,但是当我尝试实际解密数据时总是出错。错误指出“填充无效且无法删除”。我在这里做错了什么?
PHP函数生成的加密Base64值为: p07cNwcvcYLxvYHCUsmZqKYr40IXXYjEHr7r + JdgXiJT5 / wpDSDmr48JLOXyNEL7
关键是: M2AZULUALPHA
盐是: TripBuilder2017x
PHP函数是:
function encrypt($text) {
$key = "M2AZULUALPHA";
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$padding = $block - (strlen($text) % $block);
$text .= str_repeat(chr($padding), $padding);
$crypttext = openssl_encrypt($text,'aes-256-cbc', $key, OPENSSL_RAW_DATA, 'TripBuilder2017x');
return base64_encode($crypttext);
}
.NET解密功能:
private string Decrypt(string cipherText)
{
string EncryptionKey = "M2AZULUALPHA";
byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017x");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, saltArray);
encryptor.Mode = CipherMode.CBC;
encryptor.BlockSize = 128;
encryptor.KeySize = 256;
encryptor.Padding = PaddingMode.PKCS7;
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
更新我使用在线openSSL解密工具,输入了我的IV,Key和base64文本。它生成了正确的字符串,但在字符串中有一些奇怪的块。
更新2 这是更新的PHP代码。我还将密钥大小增加到16个字节。我仍然收到同样的错误。
$key = "M2AZULUALPHAECHO";
$salt = "TripBuilder2017x";
$mode = "aes-256-cbc";
$text = "BrassMonkey";
function encrypt($text,$key,$salt,$mode) {
return base64_encode(encryptplain($text,$key,$salt,$mode));
}
function encryptplain($text,$key,$salt,$mode) {
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $block - (strlen($text) % $block);
$text .= str_repeat(chr($padding), $padding);
$crypttext = openssl_encrypt($text, $mode, $key, 1, $salt);
return ($crypttext);
}
更新3:我的.NET代码
private string Decrypt(string cipherText)
{
string EncryptionKey = "M2AZULUALPHAECHO";
byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017x");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
encryptor.Mode = CipherMode.CBC;
encryptor.BlockSize = 128;
encryptor.KeySize = 256;
encryptor.Padding = PaddingMode.PKCS7;
encryptor.Key = Encoding.ASCII.GetBytes(EncryptionKey);
encryptor.IV = saltArray;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
答案 0 :(得分:2)
我可以看到几个直接的问题:
其他评论: