公钥加密私钥解密验证

public void Encrypt()
        {
            //加密解密用到的公钥与私钥
            RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
            string privatekey = oRSA.ToXmlString(true);//私钥
            string publickey = oRSA.ToXmlString(false);//公钥
            privatekey = XDocument.Load(Server.MapPath("privatekey.xml")).ToString();
            publickey = XDocument.Load(Server.MapPath("publickey.xml")).ToString();
            //备注:privatekey.xml  and publickey.xml 就是oRSA.ToXmlString true and false 对应的值
            byte[] messagebytes = Encoding.UTF8.GetBytes("苏林2013"); //需要加密的数据
            //公钥加密   
            RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider();
            oRSA1.FromXmlString(publickey); //加密要用到公钥所以导入公钥
            byte[] AOutput = oRSA1.Encrypt(messagebytes, false); //AOutput 加密以后的数据

            //私钥解密
            RSACryptoServiceProvider oRSA2 = new RSACryptoServiceProvider();
            oRSA2.FromXmlString(privatekey);
            byte[] AInput = oRSA2.Decrypt(AOutput, false);
            string reslut = Encoding.UTF8.GetString(AInput);
            Response.Write("<br/>" + reslut);
           
            //私钥签名
            RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider();
            oRSA3.FromXmlString(privatekey);
            AOutput = oRSA3.SignData(messagebytes, "SHA1");
            //公钥验证
            RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();

            oRSA4.FromXmlString(publickey);
            bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", AOutput);
            Response.Write("<br/>" + bVerify);
        }

posted @ 2013-12-23 09:37  sulin  阅读(633)  评论(0编辑  收藏  举报