我想編寫代碼來解密一個字符串。試圖解密一個字符串使用AES管理
我在python中獲得了一個等價物,我試圖創建它。 NET
的Python:
//Initialization vector is just a string of 16 null bytes
iv = '\x00' * 16
//Create new AES object using the key and init vector
aes = AES.new(key, AES.MODE_CBC, iv)
//Decrypt password and remove padding
result = aes.decrypt(myString).rstrip('\x0b\x08\x07')
return result
這裏是我的嘗試:
byte[] iv = new byte[16];
byte[] rawPlaintext = Convert.FromBase64String("MyBase64String");
byte[] key = // Read from common source
using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.None;
aes.KeySize = 128; // in bits
aes.Key = new byte[128/8]; // 16 bytes for 128 bit encryption
aes.IV = new byte[128/8]; // AES needs a 16-byte IV
// Should set Key and IV here. Good approach: derive them from
// a password via Cryptography.Rfc2898DeriveBytes
byte[] cipherText = key;
byte[] plainText = iv;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
}
cipherText = ms.ToArray();
}
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherText, 0, cipherText.Length);
}
plainText = ms.ToArray();
}
string s = System.Text.Encoding.Unicode.GetString(plainText);
Console.WriteLine(s);
}
它不會似乎工作的結果是符號的字符串。
可能的問題:
- 我看到CBC被設置的模式。我不確定相應的設置在哪裏。我試圖玩PaddingMode。
- 我的iv字節[]能導致這個問題嗎?缺省爲空還是0?
編輯: - 從我正在閱讀的AesManaged在CBC模式下使用AES,因此應該是非問題。
這將幫助,如果你提供樣品的輸入和預期的輸出示例。 – NineBerry