zoukankan      html  css  js  c++  java
  • RSA加密解密等用法

    rsa是非对称加密,有公钥和私钥

    公钥用于加密,私钥用于解密,私钥无法加密,但是私钥可以对内容签名,公钥可以对签名进行验证,这是rsa常用的使用场景

    如果你想加密一小段关键的信息,那么你可以用公钥进行加密,对方收到后用私钥进行解密。

    如果你想发送一段文字,内容很长,你并不需要对内容进行加密,只是想用私钥对内容进行数字签名,对方收到你发的信息后,可以通过公钥验证签名来证实这段信息是不是你发的,并且发的消息有没有被篡改过。

    所以这是rsa基本的两种使用场景。

        public class RSACryption
        {
            #region RSA 加密解密
    
            #region RSA 的密钥产生
    
            /// <summary>
            /// RSA产生密钥
            /// </summary>
            /// <param name="xmlKeys">私钥</param>
            /// <param name="xmlPublicKey">公钥</param>
            public void RSAKey(out string xmlKeys, out string xmlPublicKey)
            {
                try
                {
                    System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    xmlKeys = rsa.ToXmlString(true);
                    xmlPublicKey = rsa.ToXmlString(false);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 生成密钥文件
            /// </summary>
            public void RSACreateKeyFile()
            {
                try
                {
                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    using (StreamWriter writer = new StreamWriter("PrivateKey.key"))  //这个文件要保密...
                    {
                        writer.WriteLine(rsa.ToXmlString(true));
                    }
                    using (StreamWriter writer = new StreamWriter("PublicKey.key"))
                    {
                        writer.WriteLine(rsa.ToXmlString(false));
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 读取可执行目录下的key文件内容
            /// </summary>
            /// <param name="directory"></param>
            /// <returns></returns>
            public string ReadKeyFile(string directory)
            {
                try
                {
                    string key = string.Empty;
                    //查找目录下的.KEY后缀文件 获取密钥
                    DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                    var keyFiles = directoryInfo.GetFiles("*.KEY", SearchOption.TopDirectoryOnly).OrderByDescending(m => m.CreationTime).ToList();
                    if (keyFiles.Any())
                    {
                        var keyFile = keyFiles[0];
                        key = ReadFile(keyFile.FullName);
                        return key;
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 获取可执行目录下的key文件内容
            /// </summary>
            /// <param name="directory"></param>
            /// <param name="keyFileName"></param>
            /// <returns></returns>
            public string ReadKeyFile(string directory, string keyFileName)
            {
                try
                {
                    string key = string.Empty;
                    //查找目录下的.KEY后缀文件 获取密钥
                    DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                    var keyFiles = directoryInfo.GetFiles(keyFileName, SearchOption.TopDirectoryOnly).OrderByDescending(m => m.CreationTime).ToList();
                    if (keyFiles.Any())
                    {
                        var keyFile = keyFiles[0];
                        key = ReadFile(keyFile.FullName);
                        return key;
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
    
            private string ReadFile(string path)
            {
                StringBuilder sb = new StringBuilder();
                try
                {
                    using (StreamReader sr = new StreamReader(path))
                    {
                        string line;
    
                        // 从文件读取并显示行,直到文件的末尾 
                        while ((line = sr.ReadLine()) != null)
                        {
                            sb.Append(line);
                        }
                    }
                    return sb.ToString();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
    
            #endregion
    
            #region RSA加密函数
            /// <summary>
            /// RSA的加密函数
            /// </summary>
            /// <param name="xmlPublicKey">公钥</param>
            /// <param name="encryptString">待加密的字符串</param>
            /// <returns></returns>
            public string RSAEncrypt(string xmlPublicKey, string encryptString)
            {
                try
                {
                    byte[] PlainTextBArray;
                    byte[] CypherTextBArray;
                    string Result;
                    System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.FromXmlString(xmlPublicKey);
                    PlainTextBArray = Encoding.UTF8.GetBytes(encryptString);
                    CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
                    Result = Convert.ToBase64String(CypherTextBArray);
                    return Result;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// RSA的加密函数 
            /// </summary>
            /// <param name="xmlPublicKey">公钥</param>
            /// <param name="EncryptString">待加密的字节数组</param>
            /// <returns></returns>
            public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
            {
                try
                {
                    byte[] CypherTextBArray;
                    string Result;
                    System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.FromXmlString(xmlPublicKey);
                    CypherTextBArray = rsa.Encrypt(EncryptString, false);
                    Result = Convert.ToBase64String(CypherTextBArray);
                    return Result;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region RSA的解密函数        
            /// <summary>
            /// RSA的解密函数
            /// </summary>
            /// <param name="xmlPrivateKey">私钥</param>
            /// <param name="decryptString">待解密的字符串</param>
            /// <returns></returns>
            public string RSADecrypt(string xmlPrivateKey, string decryptString)
            {
                try
                {
                    byte[] PlainTextBArray;
                    byte[] DypherTextBArray;
                    string Result;
                    System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.FromXmlString(xmlPrivateKey);
                    PlainTextBArray = Convert.FromBase64String(decryptString);
                    DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
                    Result = Encoding.UTF8.GetString(DypherTextBArray);
                    return Result;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// RSA的解密函数 
            /// </summary>
            /// <param name="xmlPrivateKey">私钥</param>
            /// <param name="DecryptString">待解密的字节数组</param>
            /// <returns></returns>
            public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
            {
                try
                {
                    byte[] DypherTextBArray;
                    string Result;
                    System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.FromXmlString(xmlPrivateKey);
                    DypherTextBArray = rsa.Decrypt(DecryptString, false);
                    Result = Encoding.UTF8.GetString(DypherTextBArray);
                    return Result;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #endregion
    
    
            #region RSA数字签名
    
            #region 获取Hash描述表        
            /// <summary>
            /// 获取Hash描述表
            /// </summary>
            /// <param name="strSource">待签名的字符串</param>
            /// <param name="HashData">Hash描述</param>
            /// <returns></returns>
            public byte[] GetHashByte(string strSource)
            {
                try
                {
                    byte[] Buffer;
                    System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
                    Buffer = System.Text.Encoding.UTF8.GetBytes(strSource);
                    return MD5.ComputeHash(Buffer);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 获取Hash描述表
            /// </summary>
            /// <param name="strSource"></param>
            /// <returns></returns>
            public string GetHashStr(string strSource)
            {
                try
                {
                    //从字符串中取得Hash描述 
                    byte[] Buffer;
                    byte[] HashData;
                    System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
                    Buffer = System.Text.Encoding.UTF8.GetBytes(strSource);
                    HashData = MD5.ComputeHash(Buffer);
                    return Convert.ToBase64String(HashData);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 获取Hash描述表
            /// </summary>
            /// <param name="objFile"></param>
            /// <returns></returns>
            public byte[] GetHashByte(System.IO.FileStream objFile)
            {
                try
                {
                    //从文件中取得Hash描述 
                    System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
                    byte[] HashData = MD5.ComputeHash(objFile);
                    objFile.Close();
                    return HashData;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 获取Hash描述表
            /// </summary>
            /// <param name="objFile"></param>
            /// <returns></returns>
            public string GetHashStr(System.IO.FileStream objFile)
            {
                try
                {
                    //从文件中取得Hash描述 
                    byte[] HashData;
                    System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
                    HashData = MD5.ComputeHash(objFile);
                    objFile.Close();
                    return Convert.ToBase64String(HashData);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region RSA签名
    
    
            /// <summary>
            /// RSA签名
            /// </summary>
            /// <param name="strKeyPrivate"></param>
            /// <param name="HashbyteSignature"></param>
            /// <returns></returns>
            public string Signature(string strKeyPrivate, byte[] HashbyteSignature)
            {
                try
                {
                    byte[] EncryptedSignatureData;
                    System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                    RSA.FromXmlString(strKeyPrivate);
                    System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                    //设置签名的算法为MD5 
                    RSAFormatter.SetHashAlgorithm("MD5");
                    //执行签名 
                    EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
                    return Convert.ToBase64String(EncryptedSignatureData);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
    
    
            /// <summary>
            /// RSA签名
            /// </summary>
            /// <param name="strKeyPrivate"></param>
            /// <param name="strHashbyteSignature"></param>
            /// <returns></returns>
            public string Signature(string strKeyPrivate, string strHashbyteSignature)
            {
                try
                {
                    byte[] HashbyteSignature;
                    byte[] EncryptedSignatureData;
                    HashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
                    System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                    RSA.FromXmlString(strKeyPrivate);
                    System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                    //设置签名的算法为MD5 
                    RSAFormatter.SetHashAlgorithm("MD5");
                    //执行签名 
                    EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
                    return Convert.ToBase64String(EncryptedSignatureData);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region RSA 签名验证
            /// <summary>
            /// RSA签名验证
            /// </summary>
            /// <param name="strKeyPublic">公钥</param>
            /// <param name="HashbyteDeformatter">Hash描述</param>
            /// <param name="DeformatterData">签名后的结果</param>
            /// <returns></returns>
            public bool SignatureVerify(string strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
            {
                try
                {
                    System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                    RSA.FromXmlString(strKeyPublic);
                    System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                    //指定解密的时候HASH算法为MD5 
                    RSADeformatter.SetHashAlgorithm("MD5");
                    if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// RSA签名验证
            /// </summary>
            /// <param name="strKeyPublic">公钥</param>
            /// <param name="strHashbyteDeformatter">Hash描述</param>
            /// <param name="DeformatterData">签名后的结果</param>
            /// <returns></returns>
            public bool SignatureVerify(string strKeyPublic, string strHashbyteDeformatter, byte[] DeformatterData)
            {
                try
                {
                    byte[] HashbyteDeformatter;
                    HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter);
                    System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                    RSA.FromXmlString(strKeyPublic);
                    System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                    //指定解密的时候HASH算法为MD5 
                    RSADeformatter.SetHashAlgorithm("MD5");
                    if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// RSA签名验证
            /// </summary>
            /// <param name="strKeyPublic">公钥</param>
            /// <param name="HashbyteDeformatter">Hash描述</param>
            /// <param name="strDeformatterData">签名后的结果</param>
            /// <returns></returns>
            public bool SignatureVerify(string strKeyPublic, byte[] HashbyteDeformatter, string strDeformatterData)
            {
                try
                {
                    byte[] DeformatterData;
                    System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                    RSA.FromXmlString(strKeyPublic);
                    System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                    //指定解密的时候HASH算法为MD5 
                    RSADeformatter.SetHashAlgorithm("MD5");
                    DeformatterData = Convert.FromBase64String(strDeformatterData);
                    if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// RSA签名验证
            /// </summary>
            /// <param name="strKeyPublic">公钥</param>
            /// <param name="strHashbyteDeformatter">Hash描述</param>
            /// <param name="strDeformatterData">签名后的结果</param>
            /// <returns></returns>
            public bool SignatureVerify(string strKeyPublic, string strHashbyteDeformatter, string strDeformatterData)
            {
                try
                {
                    byte[] DeformatterData;
                    byte[] HashbyteDeformatter;
                    HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter);
                    System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                    RSA.FromXmlString(strKeyPublic);
                    System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                    //指定解密的时候HASH算法为MD5 
                    RSADeformatter.SetHashAlgorithm("MD5");
                    DeformatterData = Convert.FromBase64String(strDeformatterData);
                    if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #endregion
        }
  • 相关阅读:
    go通道小案例
    go执行cmd命令并获取输出内容
    vue快速生成二维码
    vue.js数字简化 万转化k显示
    uniapp实现小程序获取用户信息
    实现图片预加载功能
    C# MD5加密字符串方法
    一个封装的 HttpClientHelper
    简易通过队列存储并异步打日志实现
    变量
  • 原文地址:https://www.cnblogs.com/njcxwz/p/15798294.html
Copyright © 2011-2022 走看看