C#对称加密与非对称加密实例

2019-12-26 12:20:36王旭
易采站长站为您分析C#对称加密与非对称加密实例,详细分析了对称加密与非对称加密的原理与具体实现方法,具有一定的实用价值,需要的朋友可以参考下    

本文实例讲述了C#对称加密与非对称加密的原理与实现方法,。具体分析如下:

一、对称加密(Symmetric Cryptography)

对称加密是最快速、最简单的一种加密方式,加密(encryption)与解密(decryption)用的是同样的密钥(secret key)。对称加密有很多种算法,由于它效率很高,所以被广泛使用在很多加密协议的核心当中。

对称加密通常使用的是相对较小的密钥,一般小于256 bit。因为密钥越大,加密越强,但加密与解密的过程越慢。如果你只用1 bit来做这个密钥,那黑客们可以先试着用0来解密,不行的话就再用1解;但如果你的密钥有1 MB大,黑客们可能永远也无法破解,但加密和解密的过程要花费很长的时间。密钥的大小既要照顾到安全性,也要照顾到效率,是一个trade-off。

2000年10月2日,美国国家标准与技术研究所(NIST--American National Institute of Standards and Technology)选择了Rijndael算法作为新的高级加密标准(AES--Advanced Encryption Standard)。.NET中包含了Rijndael算法,类名叫RijndaelManaged,下面举个例子。

加密过程:

 

复制代码 private string myData = "hello";
private string myPassword = "OpenSesame";
private byte[] cipherText;
private byte[] salt = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0 };
   

 

private void mnuSymmetricEncryption_Click(object sender, RoutedEventArgs e)
{
    var key = new Rfc2898DeriveBytes(myPassword, salt);
    // Encrypt the data.
    var algorithm = new RijndaelManaged();
    algorithm.Key = key.GetBytes(16);
    algorithm.IV = key.GetBytes(16);
    var sourceBytes = new System.Text.UnicodeEncoding().GetBytes(myData);
    using (var sourceStream = new MemoryStream(sourceBytes))
    using (var destinationStream = new MemoryStream())
    using (var crypto = new CryptoStream(sourceStream, algorithm.CreateEncryptor(), CryptoStreamMode.Read))
    {
 moveBytes(crypto, destinationStream);