C# RSA加解密和MD5加密

1.RSA加密

  /// <summary>
        /// 加密处理
        /// </summary>
        /// <param name="content"></param>
        /// <param name="publicKeyPem"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        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签名

/// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="data"></param>
        /// <param name="privateKeyPem"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        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加密

/// <summary>
        /// MD5加密算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        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 < result.Length; i++)
            {
                output.Append((result[i]).ToString("x2", System.Globalization.CultureInfo.InvariantCulture));
            }
            return output.ToString();
        }

猜你喜欢

转载自www.cnblogs.com/xiaoerduo/p/10327993.html