c# – Convert.ToBase64String / Convert.FromBase64String和Enc
发布时间:2020-12-15 04:25:43 所属栏目:百科 来源:网络整理
导读:我目前正在学习.NET中的对称加密技术.我写了一个演示如下: private byte[] key = Encoding.ASCII.GetBytes("abcdefgh"); private byte[] IV = Encoding.ASCII.GetBytes("hgfedcba"); private byte[] encrypted; public Form1() { InitializeComponent(); }
我目前正在学习.NET中的对称加密技术.我写了一个演示如下:
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,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)具有比加密更多的字节 那么使用Convert.From / ToBase64String和Encoding.UTF8.GetBytes / GetString有什么区别呢? 解决方法
UTF-8是一个字符编码.它将Unicode码点(字符)编码成字节.
Base64是二进制到文本编码.它将字节编码为文本. 在这种情况下你需要后者. Encoding.UTF8.GetString解码一个UTF-8编码的字节数组,如果存在无效的字节序列(这很有可能是像密文一样给它随机字节),那么它是有损的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |