关闭

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

发表于:2011-10-10 10:21

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

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

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

  示意例子三:我们发现PBKDF2()方法和之前的PBKDF1()方法没有什么区别,就是无需指定加密密钥的哈希算法。

  前面通过三种方法来动态的生成加密密钥,而且我们将使用Rfc2898DeriveBytes的GetBytes()方法来获取密钥,那么接下来让我们使用该方法实现通用的对称加密算法吧!

图5 对称算法加密过程

  首先我们对加密的平文进行编码,这里默认使用UTF8对平文进行编码,也可以使用其他编码方式,接着使用相应加密算法对编码后的平文进行加密,最后把加密后的Byte数组转换为Base64格式字符串返回。

/// <param name="algorithm">The symmertric algorithm (Aes, DES, RC2, Rijndael and TripleDES).</param>
/// <param name="plainText">The plain text need to be encrypted.</param>
/// <param name="key">The secret key to encrypt plain text.</param>
/// <param name="iv">The iv should be 16 bytes.</param>
/// <param name="salt">Salt to encrypt with.</param>
/// <param name="pwdIterations">The number of iterations for plain text.</param>
/// <param name="keySize">Size of the key.</param>
/// <param name="cipherMode">The cipher mode.</param>
/// <param name="paddingMode">The padding mode.</param>
/// <returns></returns>
public static byte[] Encrypt(SymmetricAlgorithm algorithm, byte[] plainText, string key, string iv,
    string salt, int pwdIterations, int keySize, CipherMode cipherMode, PaddingMode paddingMode)
{

    if (null == plainText)
        throw new ArgumentNullException("plainText");
    if (null == algorithm)
        throw new ArgumentNullException("algorithm");
    if (String.IsNullOrEmpty(key))
        throw new ArgumentNullException("key");
    if (String.IsNullOrEmpty(iv))
        throw new ArgumentNullException("iv");
    if (String.IsNullOrEmpty(salt))
        throw new ArgumentNullException("salt");

    // Note the salt should be equal or greater that 64bit (8 byte).
    var rfc = new Rfc2898DeriveBytes(key, salt.ToByteArray(), pwdIterations);
    using (SymmetricAlgorithm symmAlgo = algorithm)
    {
        symmAlgo.Mode = cipherMode;
        //symmAlgo.Padding = paddingMode;
        byte[] cipherTextBytes = null;
        using (var encryptor = symmAlgo.CreateEncryptor(
            rfc.GetBytes(keySize / 8), iv.ToByteArray()))
        {
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(
                    ms, encryptor, CryptoStreamMode.Write))
                {
                    cs.Write(plainText, 0, plainText.Length);
                    cs.FlushFinalBlock();
                    cipherTextBytes = ms.ToArray();
                    ms.Close();
                    cs.Close();
                }
            }
            symmAlgo.Clear();
            return cipherTextBytes;
        }
    }
}

41/41234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

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

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

沪ICP备05003035号

沪公网安备 31010102002173号