栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带有传输的C#RSA加密/解密

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带有传输的C#RSA加密/解密

嗯,确实有足够的示例,但是无论如何,在这里

using System;using System.Security.Cryptography;namespace RsaCryptoExample{  static class Program  {    static void Main()    {      //lets take a new CSP with a new 2048 bit rsa key pair      var csp = new RSACryptoServiceProvider(2048);      //how to get the private key      var privKey = csp.ExportParameters(true);      //and the public key ...      var pubKey = csp.ExportParameters(false);      //converting the public key into a string representation      string pubKeyString;      {        //we need some buffer        var sw = new System.IO.StringWriter();        //we need a serializer        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));        //serialize the key into the stream        xs.Serialize(sw, pubKey);        //get the string from the stream        pubKeyString = sw.ToString();      }      //converting it back      {        //get a stream from the string        var sr = new System.IO.StringReader(pubKeyString);        //we need a deserializer        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));        //get the object back from the stream        pubKey = (RSAParameters)xs.Deserialize(sr);      }      //conversion for the private key is no black magic either ... omitted      //we have a public key ... let's get a new csp and load that key      csp = new RSACryptoServiceProvider();      csp.importParameters(pubKey);      //we need some data to encrypt      var plainTextData = "foobar";      //for encryption, always handle bytes...      var bytesPlainTextData = System.Text.Encoding.Unipre.GetBytes(plainTextData);      //apply pkcs#1.5 padding and encrypt our data       var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);      //we might want a string representation of our cypher text... base64 will do      var cypherText = Convert.Tobase64String(bytesCypherText);            //first, get our bytes back from the base64 string ...      bytesCypherText = Convert.Frombase64String(cypherText);      //we want to decrypt, therefore we need a csp and load our private key      csp = new RSACryptoServiceProvider();      csp.importParameters(privKey);      //decrypt and strip pkcs#1.5 padding      bytesPlainTextData = csp.Decrypt(bytesCypherText, false);      //get our original plainText back...      plainTextData = System.Text.Encoding.Unipre.GetString(bytesPlainTextData);    }  }}

附带说明:对Encrypt()和Decrypt()的调用具有一个布尔参数,该参数在OAEP和PKCS#1.5填充之间切换…如果您遇到的情况可用,则可能要选择OAEP



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号