原文:C#实现RSA加密和解密详解

RSA加密解密源码:



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

-->using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace MyRSA
{
publicclass MyRSA
...{

privatestaticstring publicKey =
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
privatestaticstring privateKey =
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent>"+
"<P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4d"+
"L411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRd"+
"VgzvvAxXD7ESw==</P><Q>6kqclrEunX/fmOle"+
"VTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpG"+
"lq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q>"+
"<DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FU"+
"GrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Te"+
"zc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArY"+
"gw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjA"+
"StUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>"+
"GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjn"+
"cWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4"+
"aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2D"+
"Cr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZ"+
"s7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40"+
"H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQry"+
"oHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";

staticpublicstring Decrypt(string base64code)
...{
try
...{

//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter =new UnicodeEncoding();

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();
RSA.FromXmlString(privateKey);

byte[] encryptedData;
byte[] decryptedData;
encryptedData = Convert.FromBase64String(base64code);

//Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(
encryptedData, RSA.ExportParameters(true), false);

//Display the decrypted plaintext to the console.
return ByteConverter.GetString(decryptedData);
}
catch (Exception exc)
...{
//Exceptions.LogException(exc);
Console.WriteLine(exc.Message);
return"";
}
}

staticpublicstring Encrypt(string toEncryptString)
...{
try
...{
//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter =new UnicodeEncoding();

//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt =
ByteConverter.GetBytes(toEncryptString);
byte[] encryptedData;
byte[] decryptedData;

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

RSA.FromXmlString(privateKey);

//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(
dataToEncrypt, RSA.ExportParameters(false), false);

string base64code = Convert.ToBase64String(encryptedData);
return base64code;
}
catch (Exception exc)
...{
//Catch this exception in case the encryption did
//not succeed.
//Exceptions.LogException(exc);
Console.WriteLine(exc.Message);
return"";
}



}

staticprivatebyte[] RSAEncrypt(
byte[] DataToEncrypt,
RSAParameters RSAKeyInfo,
bool DoOAEPPadding)
...{
try
...{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);

//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
...{
//Exceptions.LogException(e);
Console.WriteLine(e.Message);

returnnull;
}

}

staticprivatebyte[] RSADecrypt(
byte[] DataToDecrypt,
RSAParameters RSAKeyInfo,
bool DoOAEPPadding)
...{
try
...{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);

//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
...{
//Exceptions.LogException(e);
Console.WriteLine(e.Message);

returnnull;
}
}
}
}

namespace MyRSA

...{

publicclass MyRSA

...{



privatestaticstring publicKey =

    "<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+

    "TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+

    "wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+

    "PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+

    "/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+

    "w9YRXiac=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

privatestaticstring privateKey =

    "<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+

    "TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+

    "wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+

    "PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+

    "/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+

    "w9YRXiac=</Modulus><Exponent>AQAB</Exponent>"+

    "<P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4d"+

    "L411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRd"+

    "VgzvvAxXD7ESw==</P><Q>6kqclrEunX/fmOle"+

    "VTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpG"+

    "lq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q>"+

    "<DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FU"+

    "GrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Te"+

    "zc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArY"+

    "gw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjA"+

    "StUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>"+

    "GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjn"+

    "cWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4"+

    "aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2D"+

    "Cr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZ"+

    "s7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40"+

    "H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQry"+

    "oHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";



staticpublicstring Decrypt(string base64code)

...{

    try

    ...{



        //Create a UnicodeEncoder to convert between byte array and string.

        UnicodeEncoding ByteConverter =new UnicodeEncoding();



        //Create a new instance of RSACryptoServiceProvider to generate

        //public and private key data.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

        RSA.FromXmlString(privateKey);



        byte[] encryptedData;

        byte[] decryptedData;

        encryptedData = Convert.FromBase64String(base64code);



        //Pass the data to DECRYPT, the private key information

        //(using RSACryptoServiceProvider.ExportParameters(true),

        //and a boolean flag specifying no OAEP padding.

        decryptedData = RSADecrypt(

            encryptedData, RSA.ExportParameters(true), false);



        //Display the decrypted plaintext to the console.

        return ByteConverter.GetString(decryptedData);

    }

    catch (Exception exc)

    ...{

        //Exceptions.LogException(exc);

        Console.WriteLine(exc.Message);

        return"";

    }

}



staticpublicstring Encrypt(string toEncryptString)

...{

    try

    ...{

        //Create a UnicodeEncoder to convert between byte array and string.

        UnicodeEncoding ByteConverter =new UnicodeEncoding();



        //Create byte arrays to hold original, encrypted, and decrypted data.

        byte[] dataToEncrypt =

            ByteConverter.GetBytes(toEncryptString);

        byte[] encryptedData;

        byte[] decryptedData;



        //Create a new instance of RSACryptoServiceProvider to generate

        //public and private key data.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();



        RSA.FromXmlString(privateKey);



        //Pass the data to ENCRYPT, the public key information

        //(using RSACryptoServiceProvider.ExportParameters(false),

        //and a boolean flag specifying no OAEP padding.

        encryptedData = RSAEncrypt(

            dataToEncrypt, RSA.ExportParameters(false), false);



        string base64code = Convert.ToBase64String(encryptedData);

        return base64code;

    }

    catch (Exception exc)

    ...{

        //Catch this exception in case the encryption did

        //not succeed.

        //Exceptions.LogException(exc);

        Console.WriteLine(exc.Message);

        return"";

    }







}



staticprivatebyte[] RSAEncrypt(

    byte[] DataToEncrypt,

    RSAParameters RSAKeyInfo,

    bool DoOAEPPadding)

...{

    try

    ...{

        //Create a new instance of RSACryptoServiceProvider.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();



        //Import the RSA Key information. This only needs

        //toinclude the public key information.

        RSA.ImportParameters(RSAKeyInfo);



        //Encrypt the passed byte array and specify OAEP padding. 

        //OAEP padding is only available on Microsoft Windows XP or

        //later. 

        return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);

    }

    //Catch and display a CryptographicException 

    //to the console.

    catch (CryptographicException e)

    ...{

        //Exceptions.LogException(e);

        Console.WriteLine(e.Message);



        returnnull;

    }



}



staticprivatebyte[] RSADecrypt(

    byte[] DataToDecrypt,

    RSAParameters RSAKeyInfo,

    bool DoOAEPPadding)

...{

    try

    ...{

        //Create a new instance of RSACryptoServiceProvider.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();



        //Import the RSA Key information. This needs

        //to include the private key information.

        RSA.ImportParameters(RSAKeyInfo);



        //Decrypt the passed byte array and specify OAEP padding. 

        //OAEP padding is only available on Microsoft Windows XP or

        //later. 

        return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);

    }

    //Catch and display a CryptographicException 

    //to the console.

    catch (CryptographicException e)

    ...{

        //Exceptions.LogException(e);

        Console.WriteLine(e.Message);



        returnnull;

    }

}

}

}
 测试代码:

        static void Main(string[] args)        {            string encodeString = MyRSA.Encrypt("");            Console.WriteLine(encodeString);            string decode = MyRSA.Decrypt(encodeString);            Console.WriteLine(decode);            Console.ReadLine();        }

C#实现RSA加密和解密详解的更多相关文章

  1. 简易版DES加密和解密详解

    在DES密码里,是如何进行加密和解密的呢?这里采用DES的简易版来进行说明. 二进制数据的变换 由于不仅仅是DES密码,在其它的现代密码中也应用了二进制数据,所以无论是文章还是数字,都需要将明文变换为 ...

  2. 通过ios实现RSA加密和解密

    在加密和解密中,我们需要了解的知识有什么事openssl:RSA加密算法的基本原理:如何通过openssl生成最后我们需要的der和p12文件. 废话不多说,直接写步骤: 第一步:openssl来生成 ...

  3. ASP.NET Core RSA加密或解密

    前言 这两天主要是公司同事用到了RSA加密,事后也看了下,以为很简单,最终利用RSACryptoServiceProvider来实现RSA加密,然后大致了解到RSACryptoServiceProvi ...

  4. C#实现RSA加密与解密、签名与认证(转)

    一.RSA简介 RSA公钥加密算法是1977年由Ron Rivest.Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的.RSA取名来自开发他们三者的名字.RSA是目前最有影响力 ...

  5. RSA加密和解密工具类

    import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.*; i ...

  6. IOS, Android, Java Web Rest : RSA 加密和解密问题

    IOS, Android, Java Web Rest :  RSA 加密和解密问题 一对公钥私钥可以使用 OpenSSL创建, 通常 1024位长度够了. 注意: 1. 公钥私钥是BASE64编码的 ...

  7. C#实现RSA加密与解密、签名与认证

    一.RSA简介 RSA公钥加密算法是1977年由Ron Rivest.Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的.RSA取名来自开发他们三者的名字.RSA是目前最有影响力 ...

  8. C# -- RSA加密与解密

    1.  RSA加密与解密  --  使用公钥加密.私钥解密 public class RSATool { public string Encrypt(string strText, string st ...

  9. python RSA加密、解密、签名

    python RSA加密.解密.签名 python中用于RSA加解密的库有好久个,本文主要讲解rsa.M2Crypto.Crypto这三个库对于RSA加密.解密.签名.验签的知识点. 知识基础 加密是 ...

随机推荐

  1. Git协作流程(转)

    Git 作为一个源码管理系统,不可避免涉及到多人协作. 协作必须有一个规范的流程,让大家有效地合作,使得项目井井有条地发展下去."协作流程"在英语里,叫做"workflo ...

  2. 标准SVD和改进的SVD

    参考链接:http://www.cnblogs.com/yangxiao99/p/4752890.html 参考链接:http://www.cnblogs.com/yangxiao99/p/47529 ...

  3. Java内部类详解(转)

    说起内部类这个词,想必很多人都不陌生,但是又会觉得不熟悉.原因是平时编写代码时可能用到的场景不多,用得最多的是在有事件监听的情况下,并且即使用到也很少去总结内部类的用法.今天我们就来一探究竟.下面是本 ...

  4. 2g-3g

  5. 手游client思考框架

    手游新公司新项目client我不太同意框架.虽然我也终于让步,当他居然问老板,使这个幼稚的行为而悔恨. 然而,就在最近我写了一些代码视图,我更坚定了自己的想法和思想.和思路不一定适合其它人,所以我并不 ...

  6. Linux netstat订购具体解释

    简单介绍 Netstat 命令用于显示各种网络相关信息,如网络连接,路由表,接口状态 (Interface Statistics).masquerade 连接.多播成员 (Multicast Memb ...

  7. PHP使用MySQL数据库

    原文:PHP使用MySQL数据库 PHP使用MySQL数据库,从建立连接到结果的显示. 完整代码如下: <?php //连接MySQL $db = mysql_connect("loc ...

  8. thoughtworks笔试整理

    笔试了,时间1个半小时.没想到居然有7/10是开放性问题.大意例如以下:1.为什么选择增加ThoughtWorks.200字以内,不能用"interesting"."ch ...

  9. IOS ARC和非ARC文件混用

    ARC在SDK4.0的时候增加的,因为要和曾经的项目融合,就会有arc和非arc文件的混合. 当然,也就这两种情况: 1.自己的旧项目没有使用ARC,可是引入的第三方库却是使用了ARC的. 2.自己的 ...

  10. MySQL定义和变量赋值

    变量可以在子程序(性能.存储过程.匿名块)声明和使用.这些变量的范围是在BEGIN...END规划. 变量的定义 语法格式: DECLARE var_name [, var_name]... data ...