C# 常用加密处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        } 
    }
}

 

以上是关于C# 常用加密处理的主要内容,如果未能解决你的问题,请参考以下文章

记录C#常用的代码片段

C#中一些常用的加密和哈希处理

Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段

C#程序员经常用到的10个实用代码片段 - 操作系统

python常用代码片段总结

C# 常用加密方式