zoukankan      html  css  js  c++  java
  • 【转】asp.net(c#)加密解密算法之sha1、md5、des、aes实现源码详解

    原文地址:http://docode.top/Article/Detail/10003

    目录:

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

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

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

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

    5、总结

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    public class DesEncryptHelper
    {
        /// <summary>
        /// Des默认密钥向量
        /// </summary>
        public static string DesIv
        {
            get
            {
                return "20160602";  // 此处可自定义,8个字符长度
            }
        }
     
        /// <summary>
        /// Des加解密钥必须8位
        /// </summary>
        public static string DesKey
        {
            get
            {
                return "20160602";  // 此处可自定义,8个字符长度
            }
        }
     
        /// <summary>
        /// 获取Des8位密钥
        /// </summary>
        /// <param name="key">Des密钥字符串</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>Des8位密钥</returns>
        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);
        }
     
        /// <summary>
        /// Des加密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>加密后的字符串</returns>
        public string EncryptDes(string source, Encoding encoding = null)
        {
            return EncryptDes(source, DesKey, DesIv, encoding);
        }
     
        /// <summary>
        /// Des加密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">des密钥,长度必须8位</param>
        /// <param name="iv">密钥向量</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>加密后的字符串</returns>
        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();
                    }
                }
            }
        }
     
        /// <summary>
        /// Des解密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>解密后的字符串</returns>
        public static string DecryptDes(string source, Encoding encoding = null)
        {
            return DecryptDes(source, DesKey, DesIv, encoding);
        }
     
        /// <summary>
        /// Des解密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">des密钥,长度必须8位</param>
        /// <param name="iv">密钥向量</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>解密后的字符串</returns>
        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加密解密源代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    public class AesEncryptHelper
    {
        /// <summary>
        /// Aes加解密钥必须32位
        /// </summary>
        public static string AesKey
        {
            get
            {
                return "asekey32w"// 此处可自定义,32个字符长度
            }
        }
     
        /// <summary>
        /// 获取Aes32位密钥
        /// </summary>
        /// <param name="key">Aes密钥字符串</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>Aes32位密钥</returns>
        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);
        }
     
        /// <summary>
        /// Aes加密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string EncryptAes(string source)
        {
            return EncryptAes(source, AesKey);
        }
     
        /// <summary>
        /// Aes加密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">aes密钥,长度必须32位</param>
        /// <param name="model">运算模式</param>
        /// <param name="padding">填充模式</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>加密后的字符串</returns>
        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);
                }
            }
        }
     
        /// <summary>
        /// Aes解密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string DecryptAes(string source)
        {
            return DecryptAes(source, AesKey);
        }
     
        /// <summary>
        /// Aes解密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">aes密钥,长度必须32位</param>
        /// <param name="model">运算模式</param>
        /// <param name="padding">填充模式</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>解密后的字符串</returns>
        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加密解密源代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    /// <summary>
    /// 对字符串SHA1加密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="encoding">编码类型</param>
    /// <returns>加密后的十六进制字符串</returns>
    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加密解密源代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    /// <summary>
    /// 对字符串md5加密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="encoding">编码类型</param>
    /// <returns>加密后的十六进制字符串</returns>
    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();
        }
    }

    五、总结:

        1、.Net(C#)加密解密使用的类均存在System.Security.Cryptography命名空间下,使用时需先引用。

        2、.Net(C#)加密解密类或者其父类都实现IDispose接口,因此需要通过using包裹起来(或者采用.net异常处理机制try catch finally),在使用完后销毁对象。

    扫一扫获取百度网盘超级vip账号

  • 相关阅读:
    js原生小小总结(二)
    js原生小小总结(一)
    js原生小小总结
    寻找峰值
    第一个错误的版本
    [JSOI2018] 战争
    CF232E Quick Tortoise
    [JLOI2015] 骗我呢
    CF1428G Lucky Numbers
    CF1239E Turtle
  • 原文地址:https://www.cnblogs.com/GodX/p/5669665.html
Copyright © 2011-2022 走看看