asp.net(c#)加密解密算法:sha1、md5、des、aes源码详解

总结:

  • 1、.Net(C#)加密解密使用的类均存在System.Security.Cryptography命名空间下,使用时需先引用。
  • 2、.Net(C#)加密解密类或者其父类都实现IDispose接口,因此需要通过using包裹起来(或者采用.net异常处理机制try catch finally),在使用完后销毁对象。

一、.Net(C#)平台下Des加密解密源码:

public class DesEncryptHelper
{
    /// 
    /// Des默认密钥向量
    /// 
    public static string DesIv
    {
        get
        {
            return "20160602";  // 此处可自定义,8个字符长度
        }
    }
 
    /// 
    /// Des加解密钥必须8位
    /// 
    public static string DesKey
    {
        get
        {
            return "20160602";  // 此处可自定义,8个字符长度
        }
    }
 
    /// 
    /// 获取Des8位密钥
    /// 
    /// Des密钥字符串
    /// 编码类型
    /// Des8位密钥
    static byte[] GetDesKey(string key, Encoding encoding)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key", "Des密钥不能为空");
        }
        if (key.Length > 8)
        {
            key = key.Substring(0, 8);
        }
        if (key.Length < 8)
        {
            // 不足8补全
            key = key.PadRight(8, '0');
        }
        return encoding.GetBytes(key);
    }
 
    /// 
    /// Des加密
    /// 
    /// 源字符串
    /// 编码类型
    /// 加密后的字符串
    public string EncryptDes(string source, Encoding encoding = null)
    {
        return EncryptDes(source, DesKey, DesIv, encoding);
    }
 
    /// 
    /// Des加密
    /// 
    /// 源字符串
    /// des密钥,长度必须8位
    /// 密钥向量
    /// 编码类型
    /// 加密后的字符串
    public static string EncryptDes(string source, string key, string iv, Encoding encoding = null)
    {
        if (encoding == null) encoding = Encoding.UTF8;
 
        byte[] rgbKeys = GetDesKey(key, encoding),
                rgbIvs = GetDesKey(iv, encoding),
                inputByteArray = encoding.GetBytes(source);
        using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, 
                desProvider.CreateEncryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    // 1.第一种
                    cryptoStream.FlushFinalBlock();
                    cryptoStream.Close();
                    memoryStream.Flush();
                    memoryStream.Close();
                    desProvider.Clear();
                    string result = Convert.ToBase64String(memoryStream.ToArray());
                    return result;
 
                    // 2.第二种
                    //StringBuilder result = new StringBuilder();
                    //foreach (byte b in memoryStream.ToArray())
                    //{
                    //    result.AppendFormat("{0:X2}", b);
                    //}
                    //cryptoStream.FlushFinalBlock();
                    //cryptoStream.Close();
                    //memoryStream.Flush();
                    //memoryStream.Close();
                    //desProvider.Clear();
                    //return result.ToString();
                }
            }
        }
    }
 
    /// 
    /// Des解密
    /// 
    /// 源字符串
    /// 编码类型
    /// 解密后的字符串
    public static string DecryptDes(string source, Encoding encoding = null)
    {
        return DecryptDes(source, DesKey, DesIv, encoding);
    }
 
    /// 
    /// Des解密
    /// 
    /// 源字符串
    /// des密钥,长度必须8位
    /// 密钥向量
    /// 编码类型
    /// 解密后的字符串
    public static string DecryptDes(string source, string key, string iv, Encoding encoding = null)
    {
        if (encoding == null) encoding = Encoding.UTF8;
 
        byte[] rgbKeys = GetDesKey(key, encoding),
                rgbIvs = GetDesKey(iv, encoding),
                inputByteArray = Convert.FromBase64String(source);
        using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, 
                desProvider.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cryptoStream.FlushFinalBlock();
                    cryptoStream.Close();
                    memoryStream.Flush();
                    memoryStream.Close();
                    desProvider.Clear();
                    byte[] result = memoryStream.ToArray();
                    return encoding.GetString(result);
                }
            }
        }
    }
}

二、.Net(C#)平台下Aes加密解密源代码:

public class AesEncryptHelper
{
    /// 
    /// Aes加解密钥必须32位
    /// 
    public static string AesKey
    {
        get
        {
            return "asekey32w"; // 此处可自定义,32个字符长度
        }
    }
 
    /// 
    /// 获取Aes32位密钥
    /// 
    /// Aes密钥字符串
    /// 编码类型
    /// Aes32位密钥
    static byte[] GetAesKey(string key, Encoding encoding)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key", "Aes密钥不能为空");
        }
        if (key.Length < 32)
        {
            // 不足32补全
            key = key.PadRight(32, '0');
        }
        if (key.Length > 32)
        {
            key = key.Substring(0, 32);
        }
        return encoding.GetBytes(key);
    }
 
    /// 
    /// Aes加密
    /// 
    /// 源字符串
    /// 加密后的字符串
    public static string EncryptAes(string source)
    {
        return EncryptAes(source, AesKey);
    }
 
    /// 
    /// Aes加密
    /// 
    /// 源字符串
    /// aes密钥,长度必须32位
    /// 运算模式
    /// 填充模式
    /// 编码类型
    /// 加密后的字符串
    public static string EncryptAes(string source, string key, CipherMode model = CipherMode.ECB, 
    PaddingMode padding = PaddingMode.PKCS7, Encoding encoding = null)
    {
        if (encoding == null) encoding = Encoding.UTF8;
 
        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            aesProvider.Key = GetAesKey(key, encoding);
            aesProvider.Mode = model;
            aesProvider.Padding = padding;
            using (ICryptoTransform cryptoTransform = aesProvider.CreateEncryptor())
            {
                byte[] inputBuffers = encoding.GetBytes(source),
                    results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aesProvider.Clear();
                return Convert.ToBase64String(results, 0, results.Length);
            }
        }
    }
 
    /// 
    /// Aes解密
    /// 
    /// 源字符串
    /// 解密后的字符串
    public static string DecryptAes(string source)
    {
        return DecryptAes(source, AesKey);
    }
 
    /// 
    /// Aes解密
    /// 
    /// 源字符串
    /// aes密钥,长度必须32位
    /// 运算模式
    /// 填充模式
    /// 编码类型
    /// 解密后的字符串
    public static string DecryptAes(string source, string key, CipherMode model = CipherMode.ECB, 
    PaddingMode padding = PaddingMode.PKCS7, Encoding encoding = null)
    {
        if (encoding == null) encoding = Encoding.UTF8;
 
        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            aesProvider.Key = GetAesKey(key, encoding);
            aesProvider.Mode = model;
            aesProvider.Padding = padding;
            using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor())
            {
                byte[] inputBuffers = Convert.FromBase64String(source);
                byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aesProvider.Clear();
                return encoding.GetString(results);
            }
        }
    }
}

三、.Net(C#)平台下Sha1加密解密源代码:

/// 
/// 对字符串SHA1加密
/// 
/// 源字符串
/// 编码类型
/// 加密后的十六进制字符串
public static string Sha1Encrypt(string source, Encoding encoding = null)
{
    if (encoding == null) encoding = Encoding.UTF8;
 
    // 第一种方式
    byte[] byteArray = encoding.GetBytes(source);
    using (HashAlgorithm hashAlgorithm = new SHA1CryptoServiceProvider())
    {
        byteArray = hashAlgorithm.ComputeHash(byteArray);
        StringBuilder stringBuilder = new StringBuilder(256);
        foreach (byte item in byteArray)
        {
            stringBuilder.AppendFormat("{0:x2}", item);
        }
        hashAlgorithm.Clear();
        return stringBuilder.ToString();
    }
 
     第二种方式
    //using (SHA1 sha1 = SHA1.Create())
    //{
    //    byte[] hash = sha1.ComputeHash(encoding.GetBytes(source));
    //    StringBuilder stringBuilder = new StringBuilder();
    //    for (int index = 0; index < hash.Length; ++index)
    //        stringBuilder.Append(hash[index].ToString("x2"));
    //    sha1.Clear();
    //    return stringBuilder.ToString();
    //}
}

四、.Net(C#)平台下MD5加密解密源代码:

/// 
/// 对字符串md5加密
/// 
/// 源字符串
/// 编码类型
/// 加密后的十六进制字符串
public static string Md5Encrypt(string source, Encoding encoding = null)
{
    if (encoding == null) encoding = Encoding.UTF8;
 
    byte[] byteArray = encoding.GetBytes(source);
    using (HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider())
    {
        byteArray = hashAlgorithm.ComputeHash(byteArray);
        StringBuilder stringBuilder = new StringBuilder();
        foreach (byte item in byteArray)
        {
            stringBuilder.AppendFormat("{0:x2}", item);
        }
        hashAlgorithm.Clear();
        return stringBuilder.ToString();
    }
}

你可能感兴趣的:(c#,开发语言)