我目前正在学习.NET中的Symmetric Cryptography。我写了一个演示如下:
private byte[] key = Encoding.ASCII.GetBytes("abcdefgh");
private byte[] IV = Encoding.ASCII.GetBytes("hgfedcba");
private byte[] encrypted;
public Form1()
{
InitializeComponent();
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
this.textBox2.Text = this.Encrypt(this.textBox1.Text);
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
this.textBox3.Text = this.Decrypt(this.textBox2.Text);
}
private string Encrypt(string plainText)
{
try
{
using (DESCryptoServiceProvider crypto = new DESCryptoServiceProvider())
{
crypto.Key = this.key;
crypto.IV = this.IV;
ICryptoTransform transform = crypto.CreateEncryptor(crypto.Key, crypto.IV);
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cryptoStream))
{
writer.Write(plainText);
}
encrypted = stream.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
catch (Exception)
{
throw;
}
}
private string Decrypt(string cipherText)
{
try
{
string plainText = string.Empty;
using (DESCryptoServiceProvider crypto = new DESCryptoServiceProvider())
{
crypto.Key = this.key;
crypto.IV = this.IV;
ICryptoTransform transform = crypto.CreateDecryptor(crypto.Key, crypto.IV);
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(cipherText)))
{
using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cryptoStream))
{
plainText = reader.ReadToEnd();
}
}
}
}
return plainText;
}
catch (Exception)
{
throw;
}
}
一切都按预期工作。但如果我更换
return Convert.ToBase64String(encrypted);
并且
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(cipherText)))
要
return Encoding.UTF8.GetString(encrypted);
并且
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(cipherText)))
我在CryptoStream System.NotSupportedException
收到错误。诊断代码后,我发现Encoding.UTF8.GetBytes(cipherText)
的字节数多于encrypted
那么使用Convert.From/ToBase64String
和Encoding.UTF8.GetBytes/GetString)
之间的区别是什么?