• 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();
            }
  • 相关阅读:
    求两个字符串中相同的汉字及字母的个数
    将十进制转成十六进制
    综合模糊查询
    求第一个字符串中第二个串的个数
    去除字符串中连续的分割符
    去除字符串中的html标记及标记中的内容
    sql基础语句
    SQL Server2008函数大全(完整版)
    sql 数字转人民币大写函数(两种方法)
    数字转IP地址函数
  • 原文地址:https://www.cnblogs.com/xiaoerduo/p/10327993.html
Copyright © 2020-2023  润新知