原文: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. Could not roll back JDBC transaction途径

    [异常]接口数量:DM02;错误代码:ERR_EAI_02_014; 错误叙述性说明:当将中间库异常Could not roll back JDBC transaction; nested excep ...

  2. 深和学习导航CSS样式

    一个很容易理解,具体导航栏CSS授课风格 诚奉献给朋友: 原文地址:点击这里.

  3. java观察者模式(转)

    简单地说,观察者模式定义了一个一对多的依赖关系,让一个或多个观察者对象监察一个主题对象.这样一个主题对象在状态上的变化能够通知所有的依赖于此对象的那些观察者对象,使这些观察者对象能够自动更新. 不多说 ...

  4. requestWindowFeature()应用

    我们在开发程序是常常会须要软件全屏显示.自己定义标题(使用button等控件)和其它的需求,今天这一讲就是怎样控制Android应用程序的窗口显示. 首先介绍一个重要方法那就是requestWindo ...

  5. Java 反射 想

    所谓反射.是指在执行时状态中,获取类中的属性和方法.以及调用当中的方法的一种机制. 这样的机制的作用在于获取执行时才知道的类(Class)及当中的属性(Field).方法(Method)以及调用当中的 ...

  6. ASP.NET MVC Boilerplate简介

    ASP.NET MVC Boilerplate简介 ASP.NET MVC Boilerplate是专业的ASP.NET MVC模版用来创建安全.快速.强壮和适应性强的Web应用或站点.它在微软默认M ...

  7. 数据结构《21》----2014 WAP 第一个问题----Immutable queue

    2014 WAP第一个问题----实现一个不可改变的队列: 看似非常easy.. 其实,不同的版本号之间的效率差距可能是巨大的.. 甚至难以想象. . 使用前STL图书馆queue我们进行了比较.大差 ...

  8. 队列 <queue>

    STL: 队列中pop完成的不是取出最顶端的元素,而是取出最低端的元素.也就是说最初放入的元素能够最先被取出(这种行为被叫做FIFO:First In First Out,即先进先出). queue: ...

  9. windows已安装solr

    下载地址:http://archive.apache.org/dist/lucene/solr/ 操作环境:  Win7,Tomcat6, Solr4.3, Jdk6 下载solr4.3的包,解压到本 ...

  10. &quot;错: void 值不被忽略,因为预期&quot;解决

    在C陷阱与缺陷,实现assert什么时候,在这个过程很聪明,化为一个表达式,在当条件为假时就会调用_assert_error报错并终止程序. 刚開始_assert_error 的返回值类型是 void ...