RSA加密与解密、数字签名与验证数字签名

RSA加密算法是一种非对称加密算法。在公钥加密标准和电子商业中RSA被广泛使用。RSA是1977年由罗纳德•李维斯特(Ron Rivest)、阿迪•萨莫尔(Adi Shamir)和伦纳德•阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。.Net的推出,我们能够利用.Net Framework中的类提供的加密服务来保证数据安全。目前应用较为广泛的加密方法是使用RSA算法进行加密。在.Net Framework中与RSA加密算法相关的类主要有两个:RSA 类和RSACryptoServiceProvider 类。按照MSDN的说法RSA 类是“表示 RSA 算法的所有实现均从中继承的基类”,而RSACryptoServiceProvider 类是“使用加密服务提供程序 (CSP) 提供的 RSA 算法的实现执行不对称加密和解密”。另外,“表示 RSA 算法的标准参数”的RSAParameters 结构也是很重要的,它保存了RSA算法的参数。

 

这是本人刚刚写的RSA加密与解密、数字签名与验证数字签名的一个简单例子

希望对初学者能起到一定作用

 

    class RSAEncode
    {
        public RSACryptoServiceProvider MyRsa;
        public RSAEncode()
        {
            MyRsa = new RSACryptoServiceProvider();
        }
        public void RSAKey(out string XmlKey,out string XmlPublicKey)
        {
            try
            {
                XmlKey = MyRsa.ToXmlString(true);
                XmlPublicKey = MyRsa.ToXmlString(false);
                string xx = MyRsa.ToXmlString(true);
                //Console.Write(XmlKey + "/n");
                //Console.Write(xx);
                //WriteInKeys("E://key.xml", XmlKey);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

            }
        }
        /加密
        public string RSAEncodeData(string XmlPublicKey, string InputString)
        {
            byte[] BlankStr;
            byte[] EncodeStr;
            int len, len1,blockLen;
            string temp;
            string result="";
            try
            {
                len = InputString.Length;
                if (len % 128 == 0) len1 = len / 128;
                else len1 = len / 128 + 1;
                MyRsa.FromXmlString(XmlPublicKey);
                for (int i = 0; i < len1; i++)
                {
                    if (len >= 128)
                        blockLen = 128;
                    else blockLen = len;
                    len -= blockLen;
                    BlankStr = (new UnicodeEncoding()).GetBytes(InputString.Substring(i * 128, blockLen));
                    EncodeStr = MyRsa.Encrypt(BlankStr, false);
                    temp = Convert.ToBase64String(EncodeStr);
                    result += temp;
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        解密
        public string RSADecodeData(string PrivateKey, string InputString)
        {
            string result="";
            byte[] EncodeStr;
            byte[] BlankStr;
            int len, len1, blockLen;
            string temp;
            try
            {
                len = InputString.Length;
                if (len % 256 == 0) len1 = len / 256;
                else len1 = len / 256 + 1;
                MyRsa.FromXmlString(PrivateKey);
                for (int i = 0; i < len1; i++)
                {
                    if (len >= 256)
                        blockLen = 256;
                    else blockLen = len;
                    len -= blockLen;
                    EncodeStr = Convert.FromBase64String(InputString.Substring(i*256,blockLen));
                    BlankStr=MyRsa.Decrypt(EncodeStr, false);
                    temp =(new UnicodeEncoding()).GetString(BlankStr);
                    result += temp;
                }
                return result;
               
                //Console.Write(result);
               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        获取hash签名
        public bool GetHash(string SendData, out string CreateHashSign)
        {
            try
            {
                byte[] Buffer;
                byte[] HashData;
                System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
                Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(SendData);
                HashData = MD5.ComputeHash(Buffer);
                CreateHashSign = Convert.ToBase64String(HashData);
                //Console.Write(CreateHashSign);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //return true;
            }
        }
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="PrivateKey"></param>
        /// <param name="HashSign"></param>
        /// <param name="EncodedSignData"></param>
        /// <returns></returns>

        public bool SignatureFormatter(string PrivateKey, string HashSign, out string EncodedSignData)
        {
            try
            {
                byte[] ByteHashSign;
                byte[] ByteData;
                ByteHashSign = Convert.FromBase64String(HashSign);
                //ByteData = Convert.FromBase64String(EncodedData);
                MyRsa.FromXmlString(PrivateKey);
                RSAPKCS1SignatureFormatter RSAFormat = new RSAPKCS1SignatureFormatter(MyRsa);
                RSAFormat.SetHashAlgorithm("MD5");

                ByteData = RSAFormat.CreateSignature(ByteHashSign);

                EncodedSignData = Convert.ToBase64String(ByteData);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //验证签名
        //p_strHashbyteDeformatter
        //p_strDeformatterData
        public bool SignatureDeformatter(string PublicKey, string p_strHashbyteDeformatter, string p_strDeformatterData)
        {
           try
           {
                byte[] DeformatterData;
                byte[] HashbyteDeformatter;

                HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(PublicKey);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的时候HASH算法为MD5
                RSADeformatter.SetHashAlgorithm("MD5");

                DeformatterData =Convert.FromBase64String(p_strDeformatterData);

                if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
           }
           catch(Exception ex)
           {
            throw ex;
           }
       }
        ///写入密钥
        ///
        private void WriteInKeys(string path,string key)
        {
            FileStream File = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(File);
            sw.WriteLine(key);
            sw.Close();
            File.Close();
        }
        ///读取密钥
        ///
        public bool ReadKeys(string path, out string Keys)
        {
            try
            {
                StreamReader sr = new StreamReader(path);
                XmlPublicKey = sr.ReadToEnd();
                sr.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

上面是加密解密签名验证的类 

结合自己的理解  RSA加密解密的就一句话:公钥加密 私钥解密 私钥签名 公钥验证

不足之处还忘指出

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值