C#对称加密与非对称加密实例
本文实例讲述了C#对称加密与非对称加密的原理与实现方法,分享给大家供大家参考。具体分析如下:
一、对称加密(SymmetricCryptography)
对称加密是最快速、最简单的一种加密方式,加密(encryption)与解密(decryption)用的是同样的密钥(secretkey)。对称加密有很多种算法,由于它效率很高,所以被广泛使用在很多加密协议的核心当中。
对称加密通常使用的是相对较小的密钥,一般小于256bit。因为密钥越大,加密越强,但加密与解密的过程越慢。如果你只用1bit来做这个密钥,那黑客们可以先试着用0来解密,不行的话就再用1解;但如果你的密钥有1MB大,黑客们可能永远也无法破解,但加密和解密的过程要花费很长的时间。密钥的大小既要照顾到安全性,也要照顾到效率,是一个trade-off。
2000年10月2日,美国国家标准与技术研究所(NIST--AmericanNationalInstituteofStandardsandTechnology)选择了Rijndael算法作为新的高级加密标准(AES--AdvancedEncryptionStandard)。.NET中包含了Rijndael算法,类名叫RijndaelManaged,下面举个例子。
加密过程:
privatestringmyData="hello"; privatestringmyPassword="OpenSesame"; privatebyte[]cipherText; privatebyte[]salt={0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x5,0x4,0x3,0x2,0x1,0x0};
privatevoidmnuSymmetricEncryption_Click(objectsender,RoutedEventArgse) { varkey=newRfc2898DeriveBytes(myPassword,salt); //Encryptthedata. varalgorithm=newRijndaelManaged(); algorithm.Key=key.GetBytes(16); algorithm.IV=key.GetBytes(16); varsourceBytes=newSystem.Text.UnicodeEncoding().GetBytes(myData); using(varsourceStream=newMemoryStream(sourceBytes)) using(vardestinationStream=newMemoryStream()) using(varcrypto=newCryptoStream(sourceStream,algorithm.CreateEncryptor(),CryptoStreamMode.Read)) { moveBytes(crypto,destinationStream); cipherText=destinationStream.ToArray(); } MessageBox.Show(String.Format("Data:{0}{1}EncryptedandEncoded:{2}",myData,Environment.NewLine,Convert.ToBase64String(cipherText))); } privatevoidmoveBytes(Streamsource,Streamdest) { byte[]bytes=newbyte[2048]; varcount=source.Read(bytes,0,bytes.Length); while(0!=count) { dest.Write(bytes,0,count); count=source.Read(bytes,0,bytes.Length); } }