zoukankan      html  css  js  c++  java
  • C# 常用加密处理

    AES

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace Common
    {
        public class AESProvider
        {
            public static int KEYSIZE = 128;
    
    
            /// <summary>
            /// 获取随机的加密密钥
            /// </summary>
            /// <param name="Key"></param>
            /// <param name="IV"></param>
            /// <returns></returns>
            public static void GenerateKey(out string Key, out string IV)
            {
                Key = GenerateKey();
                IV = GenerateIV();
            }
    
            /// <summary>
            /// 获取随机的加密密钥
            /// </summary>
            /// <returns></returns>
            public static string GenerateKey()
            {
                int n = KEYSIZE / 8;
                char[] arrChar = new char[]{
               'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
               '0','1','2','3','4','5','6','7','8','9',
               'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
              };
    
                StringBuilder num = new StringBuilder();
    
                Random rnd = new Random();
                for (int i = 0; i < n; i++)
                {
                    num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());
                }
    
                return num.ToString();
            }
    
            /// <summary>
            /// 获取随机的初始化向量
            /// </summary>
            /// <returns></returns>
            public static string GenerateIV()
            {
                int n = KEYSIZE / 8;
                char[] arrChar = new char[]{
               'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
               '0','1','2','3','4','5','6','7','8','9',
               'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
              };
    
                StringBuilder num = new StringBuilder();
    
                Random rnd = new Random(DateTime.Now.Millisecond);
                for (int i = 0; i < n; i++)
                {
                    num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());
                }
    
                return num.ToString();
            }
    
            /// <summary>
            /// AES加密 
            /// </summary>
            /// <param name="TextData">待加密字符</param>
            /// <param name="Key">加密密钥</param>
            /// <param name="IV">初始化向量</param>
            /// <param name="CryptText">输出:已加密字符串</param>
            /// <returns>0:成功加密 -1:待加密字符串不为能空 -2:加密密钥不能为空 -3:初始化向量字节长度不为KEYSIZE/8 -4:其他错误</returns>
            public static int EncryptText(string TextData, string Key, string IV, out string CryptText)
            {
                CryptText = "";
                TextData = TextData.Trim();
                if (string.IsNullOrEmpty(TextData)) return -1;
                if (string.IsNullOrEmpty(Key)) return -2;
                if (string.IsNullOrEmpty(IV) || IV.Length != KEYSIZE / 8) return -3;
    
                try
                {
                    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    
                    rijndaelCipher.Mode = CipherMode.CBC;
                    rijndaelCipher.Padding = PaddingMode.PKCS7;
                    rijndaelCipher.KeySize = KEYSIZE;
                    rijndaelCipher.BlockSize = KEYSIZE;
    
                    byte[] pwdBytes = Encoding.UTF8.GetBytes(Key);
                    byte[] ivBytes = Encoding.UTF8.GetBytes(IV);
    
                    byte[] keyBytes = new byte[KEYSIZE / 8];
                    int len = pwdBytes.Length;
                    if (len > keyBytes.Length) len = keyBytes.Length;
                    System.Array.Copy(pwdBytes, keyBytes, len);
    
                    rijndaelCipher.Key = keyBytes;
                    rijndaelCipher.IV = ivBytes;
    
                    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
                    byte[] plainText = Encoding.UTF8.GetBytes(TextData);
                    byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
    
                    CryptText = Convert.ToBase64String(cipherBytes);
    
                    return 0;
                }
                catch
                {
                    return -4;
                }
            }
    
            /// <summary>
            /// AES解密
            /// </summary>
            /// <param name="CryptText">待解密字符串</param>
            /// <param name="Key">加密密钥</param>
            /// <param name="IV">初始化向量</param>
            /// <param name="TextData">输出:已解密的字符串</param>
            /// <returns>0:成功解密 -1:待解密字符串不为能空 -2:加密密钥不能为空 -3:初始化向量字节长度不为KEYSIZE/8 -4:其他错误</returns>
            public static int DecryptText(string CryptText, string Key, string IV, out string TextData)
            {
                TextData = "";
                if (string.IsNullOrEmpty(CryptText)) return -1;
                if (string.IsNullOrEmpty(Key)) return -2;
                if (string.IsNullOrEmpty(IV) || IV.Length != KEYSIZE / 8) return -3;
    
                try
                {
                    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    
                    rijndaelCipher.Mode = CipherMode.CBC;
                    rijndaelCipher.Padding = PaddingMode.PKCS7;
                    rijndaelCipher.KeySize = KEYSIZE;
                    rijndaelCipher.BlockSize = KEYSIZE;
    
                    byte[] encryptedData = Convert.FromBase64String(CryptText);
                    byte[] pwdBytes = Encoding.UTF8.GetBytes(Key);
                    byte[] ivBytes = Encoding.UTF8.GetBytes(IV);
    
                    byte[] keyBytes = new byte[KEYSIZE / 8];
                    int len = pwdBytes.Length;
                    if (len > keyBytes.Length) len = keyBytes.Length;
                    System.Array.Copy(pwdBytes, keyBytes, len);
    
                    rijndaelCipher.Key = keyBytes;
                    rijndaelCipher.IV = ivBytes;
    
                    ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                    byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    
                    TextData = Encoding.UTF8.GetString(plainText).Trim();
                    return 0;
                }
                catch
                {
                    return -4;
                }
            }
        }
    }

    RSA

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace Common
    {
        public class RSAProvider
        {
            public static int KEYSIZE = 1024;
            /// <summary>
            /// 自动生成公私密钥
            /// </summary>
            /// <param name="Modulus">输出:加密公钥</param>
            /// <param name="Exponent">输入:公钥指数</param>
            /// <param name="PrivateKey">输出:私钥</param>
            public static void GenerateKey(out string Modulus, out string Exponent, out string PrivateKey)
            {
                RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(KEYSIZE);
    
                RSAParameters pubparam = rsaProvider.ExportParameters(false);
                byte[] mod = pubparam.Modulus;
                byte[] exp = pubparam.Exponent;
    
                byte[] prikey = rsaProvider.ExportCspBlob(true);
    
                Modulus = Convert.ToBase64String(mod);
                Exponent = Convert.ToBase64String(exp);
                PrivateKey = Convert.ToBase64String(prikey);
            }
    
            /// <summary>
            /// RSA加密 
            /// </summary>
            /// <param name="TextData">待加密字符</param>
            /// <param name="Modulus">加密公钥</param>
            /// <param name="Exponent">加密指数</param>
            /// <param name="CryptText">输出:已加密字符串</param>
            /// <returns>0:成功加密 -1:待加密字符串不为能空 -2:加密公钥不能为空 -3:待加密字符串超长  -4:其他错误</returns>      
            public static int EncryptText(string TextData, string Modulus, string Exponent, out string CryptText)
            {
                CryptText = "";
                if (string.IsNullOrEmpty(TextData)) return -1;
                if (string.IsNullOrEmpty(Modulus)) return -2;
                if (TextData.Length > KEYSIZE / 8 - 11) return -3;
                try
                {
                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(KEYSIZE);
                    byte[] modBytes = Convert.FromBase64String(Modulus);
                    byte[] expBytes = Convert.FromBase64String(Exponent);
    
                    RSAParameters p = new RSAParameters();
                    p.Modulus = modBytes;
                    p.Exponent = expBytes;
    
                    rsa.ImportParameters(p);
                    byte[] plainText = Encoding.UTF8.GetBytes(TextData);
                    byte[] cipherBytes = rsa.Encrypt(plainText, false);
    
                    CryptText = Convert.ToBase64String(cipherBytes);
    
                    return 0;
                }
                catch { return -4; }
            }
    
            /// <summary>
            /// RSA解密
            /// </summary>
            /// <param name="CryptText">待解密字符串</param>
            /// <param name="Key">解密私钥</param>
            /// <param name="TextData">输出:已解密的字符串</param>
            /// <returns>0:成功解密 -1:待解密字符串不为能空 -2:解密私钥不能为空 -4:其他错误</returns>
            public static int DecryptText(string CryptText, string PrivateKey, out string TextData)
            {
                TextData = "";
    
                if (string.IsNullOrEmpty(CryptText)) return -1;
                if (string.IsNullOrEmpty(PrivateKey)) return -2;
    
                try
                {
                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(KEYSIZE);
    
                    byte[] prikey = Convert.FromBase64String(PrivateKey); ;
                    rsa.ImportCspBlob(prikey);
    
                    byte[] cipherBytes = Convert.FromBase64String(CryptText);
                    byte[] plainText = rsa.Decrypt(cipherBytes, false);
    
                    TextData = Encoding.UTF8.GetString(plainText);
    
                    return 0;
                }
                catch { return -4; }
            }
        }
    }

    MD5

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Common
    {
      public  class EncryptMD5
        {
    
            public static string GetMd5(string s, Encoding encoding)
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();//实例化一个MD5
                byte[] t = md5.ComputeHash(encoding.GetBytes(s));//生成MD5哈希值
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < t.Length; i++)
                {
                    sb.Append(t[i].ToString("x").PadLeft(2, '0'));//将哈希值转换为字符串
                }
                return sb.ToString().ToUpper();
            } 
        }
    }
  • 相关阅读:
    计算广告学学习1
    scala学习手记20
    scala学习手记19
    scala学习手记18
    scala学习手记17
    SAM4E单片机之旅——12、USART
    SAM4E单片机之旅——11、UART之PDC收发
    SAM4E单片机之旅——10、UART与MCK之PLL
    SAM4E单片机之旅——9、UART与MCK之MAINCK
    SAM4E单片机之旅——8、UART初步
  • 原文地址:https://www.cnblogs.com/longling2344/p/5158151.html
Copyright © 2011-2022 走看看