rsa加密算法使用示例分享


复制代码 代码如下:

产生私钥和公钥
System.Security.Cryptography.RSACryptoServiceProvider myrsa = new RSACryptoServiceProvider();
//得到私钥主要保存了RSAParameters中的8各参数
privateKey = myrsa.ToXmlString(true);
//得到公钥保存了RSAParameters中2个参数
publicKey = myrsa.ToXmlString(false);

RAS实现加密
System.Security.Cryptography.RSACryptoServiceProvider myrsa = new RSACryptoServiceProvider();
//得到公钥
myrsa.FromXmlString(publicKey);
//把你要加密的内容转换成byte[]
byte[] PlainTextBArray = (new UnicodeEncoding()).GetBytes("这里是你要加密的内容");
//使用.NET中的Encrypt方法加密
byte[] CypherTextBArray = myrsa.Encrypt(PlainTextBArray, false);
//最后吧加密后的byte[]转换成Base64String,这里就是加密后的内容了
Result = Convert.ToBase64String(CypherTextBArray)


RAS实现解密
System.Security.Cryptography.RSACryptoServiceProvider myrsa = new RSACryptoServiceProvider();
//得到私钥
myrsa.FromXmlString(xmlPrivateKey);
//把原来加密后的String转换成byte[]
byte[] PlainTextBArray = Convert.FromBase64String("刚才加密后的string");
//使用.NET中的Decrypt方法解密
byte[] DypherTextBArray = myrsa.Decrypt(PlainTextBArray, false);
//转换解密后的byte[],这就得到了我们原来的加密前的内容了
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);


byte[] messagebytes = Encoding.UTF8.GetBytes("luo罗");
            RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
            string privatekey = oRSA.ToXmlString(true);
            string publickey = oRSA.ToXmlString(false);

            //私钥签名 
            RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider();
            oRSA3.FromXmlString(privatekey);
            byte[] AOutput = oRSA3.SignData(messagebytes, "SHA1");
            //公钥验证 
            RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();
            oRSA4.FromXmlString(publickey);
            bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", AOutput);



« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3