Csharp/C#教程:C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例分享

思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。

 代码:

publicstaticstringEncrypt(stringplainText,stringAESKey) { RijndaelManagedrijndaelCipher=newRijndaelManaged(); byte[]inputByteArray=Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 rijndaelCipher.Key=Convert.FromBase64String(AESKey);//加解密双方约定好密钥:AESKey rijndaelCipher.GenerateIV(); byte[]keyIv=rijndaelCipher.IV; byte[]cipherBytes=null; using(MemoryStreamms=newMemoryStream()) { using(CryptoStreamcs=newCryptoStream(ms,rijndaelCipher.CreateEncryptor(),CryptoStreamMode.Write)) { cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); cipherBytes=ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); } } varallEncrypt=newbyte[keyIv.Length+cipherBytes.Length]; Buffer.BlockCopy(keyIv,0,allEncrypt,0,keyIv.Length); Buffer.BlockCopy(cipherBytes,0,allEncrypt,keyIv.Length*sizeof(byte),cipherBytes.Length); returnConvert.ToBase64String(allEncrypt); } publicstaticstringDecrypt(stringshowText,stringAESKey) { stringresult=string.Empty; try { byte[]cipherText=Convert.FromBase64String(showText); intlength=cipherText.Length; SymmetricAlgorithmrijndaelCipher=Rijndael.Create(); rijndaelCipher.Key=Convert.FromBase64String(AESKey);//加解密双方约定好的密钥 byte[]iv=newbyte[16]; Buffer.BlockCopy(cipherText,0,iv,0,16); rijndaelCipher.IV=iv; byte[]decryptBytes=newbyte[length-16]; byte[]passwdText=newbyte[length-16]; Buffer.BlockCopy(cipherText,16,passwdText,0,length-16); using(MemoryStreamms=newMemoryStream(passwdText)) { using(CryptoStreamcs=newCryptoStream(ms,rijndaelCipher.CreateDecryptor(),CryptoStreamMode.Read)) { cs.Read(decryptBytes,0,decryptBytes.Length); cs.Close(); ms.Close(); } } result=Encoding.UTF8.GetString(decryptBytes).Replace("","");///将字符串后尾的''去掉 } catch{} returnresult; }

调用:

stringjiaMi=MyAESTools.Encrypt(textBox1.Text,"abcdefgh12345678abcdefgh12345678"); stringjieMi=MyAESTools.Decrypt(textBox3.Text,"abcdefgh12345678abcdefgh12345678");

您可能感兴趣的文章:C#对称加密与非对称加密实例C#实现简单的RSA非对称加密算法示例C#中对称加密算法的踩坑日常记录

标签: 加密

详解C++的String类的字符串分割实现

C++实现银行排队系统

上述就是C#学习教程:C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/906652.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐