.NET中的加密算法总结(上)

发表于:2011-10-10 10:06

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:JK_Rush(cnblogs)    来源:51Testing软件测试网采编

分享:

  现在我们对PBKDF1算法的原理有了初步的了解,接下来我们将通过GetBytes()调用该算法生成密钥。

/// <summary>
/// Uses the PBKDF1 to genernate key, 
/// then use it to encrypt plain text.
/// </summary>
public void PBKDF1()
{
    byte[] salt = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

    // Creates an RC2 object to encrypt with the derived key
    var pdb = new PasswordDeriveBytes("pwd", salt) 
    {IterationCount = 23, HashName = "SHA1"};

    // Gets the key and iv.
    byte[] key = pdb.GetBytes(16);
    byte[] iv = pdb.GetBytes(8);

    var rc2 = new RC2CryptoServiceProvider { Key = key, IV = iv };

    byte[] plaintext = Encoding.UTF8.GetBytes("NeedToEncryptData");

    using (var ms = new MemoryStream())
    {
        // Encrypts data.
        var cs = new CryptoStream(
            ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);

        cs.Write(plaintext, 0, plaintext.Length);
        cs.Close();
        byte[] encrypted = ms.ToArray();
    }

}

  示意例子二:我们使用PBKDF1算法为RC2加密算法生成128 bit的密钥和64 bit的初始化向量,要注意的是PasswordDeriveBytes的GetBytes()方法已经过时了,而它的替代项就是接下来要介绍的Rfc2898DeriveBytes的GetBytes()方法。

  PBKDF2

  GetBytes:由于Rfc2898DeriveBytes的GetBytes()方法实现了PBKDF2算法,而且它也替代了PBKDF1过时的GetBytes()方法,所以我们推荐使用Rfc2898DeriveBytes的GetBytes()方法。

/// <summary>
/// Uses the PBKDF2 to genernate key, 
/// then use it to encrypt plain text.
/// </summary>
public void PBKDF2()
{
    byte[] salt = new byte[] { 23, 21, 32, 33, 46, 59, 60, 74 };
    var rfc = new Rfc2898DeriveBytes("pwd", salt, 23);

    // generate key and iv.
    byte[] key = rfc.GetBytes(16);
    byte[] iv = rfc.GetBytes(8);

    // Creates an RC2 object to encrypt with the derived key
    var rc2 = new RC2CryptoServiceProvider { Key = key, IV = iv };

    // Encrypts the data.
    byte[] plaintext = Encoding.UTF8.GetBytes("NeedToEncryptData");
    using (var ms = new MemoryStream())
    {
        var cs = new CryptoStream(
            ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);

        cs.Write(plaintext, 0, plaintext.Length);
        cs.Close();
        byte[] encrypted = ms.ToArray();
    }
}

44/4<1234
价值129的会员专享直播免费赠送,添加微信领取听课名额哦~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海漕溪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号