C# RSA加解密和MD5加密

2021-06-17 18:03

阅读:479

标签:enc   encoding   span   build   null   return   har   create   pre   

1.RSA加密

  /// 
        /// 加密处理
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string RSAEncrypt(string content, string publicKeyPem, string charset = "UTF-8")
        {
            try
            {
                string sPublicKeyPEM = File.ReadAllText(publicKeyPem);

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.PersistKeyInCsp = false;
                RSACryptoServiceProviderExtension.LoadPublicKeyPEM(rsa, sPublicKeyPEM);

                byte[] data = Encoding.GetEncoding(charset).GetBytes(content);
                int maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制
                if (data.Length  maxBlockSize)
                {
                    byte[] cipherbytes = rsa.Encrypt(data, false);
                    return Convert.ToBase64String(cipherbytes);
                }

                MemoryStream plaiStream = new MemoryStream(data);
                MemoryStream crypStream = new MemoryStream();
                Byte[] buffer = new Byte[maxBlockSize];
                int blockSize = plaiStream.Read(buffer, 0, maxBlockSize);
                while (blockSize > 0)
                {
                    Byte[] toEncrypt = new Byte[blockSize];
                    Array.Copy(buffer, 0, toEncrypt, 0, blockSize);
                    Byte[] cryptograph = rsa.Encrypt(toEncrypt, false);
                    crypStream.Write(cryptograph, 0, cryptograph.Length);
                    blockSize = plaiStream.Read(buffer, 0, maxBlockSize);
                }

                return Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None);
            }
            catch (Exception e)
            {
                e.Error();
                return null;
            }
        }

2.RSA解密

public static string RSADecrypt(string content, string privateKeyPem, string charset = "UTF-8")
        {
            try
            {
                RSACryptoServiceProvider rsaCsp = LoadCertificateFile(privateKeyPem);

                if (string.IsNullOrEmpty(charset))
                {
                    charset = "UTF-8";
                }
                byte[] data = Convert.FromBase64String(content);
                int maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制

                if (data.Length  maxBlockSize)
                {
                    byte[] cipherbytes = rsaCsp.Decrypt(data, false);
                    return Encoding.GetEncoding(charset).GetString(cipherbytes);
                }

                MemoryStream crypStream = new MemoryStream(data);
                MemoryStream plaiStream = new MemoryStream();
                Byte[] buffer = new Byte[maxBlockSize];
                int blockSize = crypStream.Read(buffer, 0, maxBlockSize);

                while (blockSize > 0)
                {
                    Byte[] toDecrypt = new Byte[blockSize];
                    Array.Copy(buffer, 0, toDecrypt, 0, blockSize);
                    Byte[] cryptograph = rsaCsp.Decrypt(toDecrypt, false);
                    plaiStream.Write(cryptograph, 0, cryptograph.Length);
                    blockSize = crypStream.Read(buffer, 0, maxBlockSize);
                }

                return Encoding.GetEncoding(charset).GetString(plaiStream.ToArray());
            }
            catch
            {
                //e.Error();
                return null;
            }
        }

3.RSA签名

/// 
        /// RSA签名
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string RSASign(string data, string privateKeyPem, string charset)
        {
            RSACryptoServiceProvider rsaCsp = LoadCertificateFile(privateKeyPem);
            byte[] dataBytes = null;
            if (string.IsNullOrEmpty(charset))
            {
                dataBytes = Encoding.UTF8.GetBytes(data);
            }
            else
            {
                dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
            }

            byte[] signatureBytes = rsaCsp.SignData(dataBytes, "SHA1");

            return Convert.ToBase64String(signatureBytes);
        }
```
```
private static RSACryptoServiceProvider LoadCertificateFile(string privateKeyPem)
        {
            using (System.IO.FileStream fs = System.IO.File.OpenRead(privateKeyPem))
            {
                byte[] data = new byte[fs.Length];
                string res = string.Empty;
                fs.Read(data, 0, data.Length);
                if (data[0] != 0x30)
                {
                    res = GetPem("RSA PRIVATE KEY", data);
                }
                try
                {
                    RSACryptoServiceProvider rsa = DecodePemPrivateKey(res);
                    return rsa;
                }
                catch (Exception e)
                {
                    e.Error();
                    return null;
                }

            }
        }
```
RSA签名验签
```
public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset)
        {
            try
            {
                string sPublicKeyPEM = File.ReadAllText(publicKeyPem);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.PersistKeyInCsp = false;
                RSACryptoServiceProviderExtension.LoadPublicKeyPEM(rsa, sPublicKeyPEM);
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                if (string.IsNullOrEmpty(charset))
                {
                    charset = DEFAULT_CHARSET;
                }
                bool bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), sha1, Convert.FromBase64String(sign));
                return bVerifyResultOriginal;
            }
            catch(Exception e)
            {
                e.Error();
                return false;
            }
        }

4.MD5加密

/// 
        /// MD5加密算法
        /// 
        /// 
        /// 
        public static string MD5(String str, string encoder = "UTF8")
        {
            byte[] result = null;
            byte[] inputbyt = null;
            switch (encoder)
            {
                case "UTF8":
                    inputbyt = Encoding.UTF8.GetBytes(str);
                    break;
                case "GBK":
                    inputbyt = Encoding.GetEncoding("GBK").GetBytes(str);
                    break;
                default:
                    inputbyt = Encoding.GetEncoding("GB2312").GetBytes(str);
                    break;
            }
            result = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(inputbyt);
            StringBuilder output = new StringBuilder(16);
            for (int i = 0; i )
            {
                output.Append((result[i]).ToString("x2", System.Globalization.CultureInfo.InvariantCulture));
            }
            return output.ToString();
        }

 

C# RSA加解密和MD5加密

标签:enc   encoding   span   build   null   return   har   create   pre   

原文地址:https://www.cnblogs.com/xiaoerduo/p/10327993.html


评论


亲,登录后才可以留言!