欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

rsa加密算法使用示例分享

程序员文章站 2024-02-24 22:33:28
复制代码 代码如下:产生私钥和公钥system.security.cryptography.rsacryptoserviceprovider myrsa = new 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);