首先,我知道这个问题可以在这里找到很多-但它们不是我想要的。
我试图在PHP脚本上加密数据,然后稍后在C#应用程序上对其解密
我当前的PHP代码:
$plaintext = 'My secret message 1234';
$password = '3sc3RLrpd17';
$method = 'aes-256-cbc';
$key = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
// IV must be exact 16 chars (128 bit)
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
// av3DYGLkwBsErphcyYp+imUW4QKs19hUnFyyYcXwURU=
$encrypted = base64_encode(openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv));
echo $encrypted;
之后,我想在我的C#应用程序上解密$encrypted
的值...
我目前正在这样做:
public string DecryptString(string cipherText, byte[] key, byte[] iv)
{
// Instantiate a new Aes object to perform string symmetric encryption
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
//encryptor.KeySize = 256;
//encryptor.BlockSize = 128;
//encryptor.Padding = PaddingMode.Zeros;
// Set key and IV
encryptor.Key = key.Take(32).ToArray();
encryptor.IV = iv;
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our Aes object
ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
// Will contain decrypted plaintext
string plainText = String.Empty;
try
{
// Convert the ciphertext string into a byte array
byte[] cipherBytes = Convert.FromBase64String(cipherText);
// Decrypt the input ciphertext string
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
// Complete the decryption process
cryptoStream.FlushFinalBlock();
// Convert the decrypted data from a MemoryStream to a byte array
byte[] plainBytes = memoryStream.ToArray();
// Convert the decrypted byte array to string
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
}
// Return the decrypted data as a string
return plainText;
}
string password = "3sc3RLrpd17";
// hash the password with BCrypt
string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, 12);
// Convert hashed password to array
byte[] key = Encoding.ASCII.GetBytes(hashedPassword);
// Create secret IV
byte[] iv = new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
string decrypted = this.DecryptString(encrypted, key, iv);
但是最后,decrypted
的值不是My secret message 1234
我得到的错误是:Padding is invalid and cannot be removed.
免责声明:我已安装BCrypt软件包。
我认为问题出在iv
。
我已经做了很多修复。
任何帮助将不胜感激。
谢谢!
答案 0 :(得分:1)
尝试在EncryptString 和 DecryptString函数中更改以下代码:
encryptor.Key = key.Take(32).ToArray();
byte[] aesKey = new byte[32];
Array.Copy(key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
PS:您的错误消息表示AES密钥不正确。确保您使用相同的密钥和iv进行加密和解密。