原文: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. VB.Net出口Excel原则

        在VB机房的版本中,我们已经暴露导出Excel特征,此功能已重新接触到不同的理解 一.原理 要实现导出Excel的功能,首先要引用命名空间,目的是能够使用该命名空间下的方法和类 Imports ...

  2. Shell编程入门(再版)(在)

    简单的演示样本Shell规划 演示样例1. #!/bin/bash #This is to show what a shell script looks like echo "Our fir ...

  3. 3D数学学习笔记——笛卡尔坐标系

    本系列文章由birdlove1987编写.转载请注明出处. 文章链接: http://blog.csdn.net/zhurui_idea/article/details/24601215 1.3D数学 ...

  4. 一个IT学生的personal statement

    前一段时间的英语老师要求我们写一个自己的personal statement,我相信,作为一个IT学生,人很多personal statement应该都了如指掌.进一步的研究是必要的出国留学,当然,也 ...

  5. poj1083 思考题

    http://poj.org/problem?id=1083 Description The famous ACM (Advanced Computer Maker) Company has rent ...

  6. Telephone Lines USACO 月赛

    以前做过这套题目 这个题又重新写了:http://www.cnblogs.com/jh818012/archive/2013/05/05/3182681.html 还是以前的思路 一直错在一个地方:决 ...

  7. Group By去除重复数据

    今天在写一个sql,目的是去除表里某一个字段相同的数据,只保留最新的一条.之前group by 用的少.特此记录一下. SELECT * FROM litb_approval_task SELECT ...

  8. Gitserver几家互联网代理安装方法未能解决。

    1.gem安装下面的错误 root@ubuntu:/home/git/gitlab# sudo gem install bundler --no-ri --no-rdoc ERROR:  Could ...

  9. android账号与同步之发起同步

    上一篇博文我介绍了账号与同步的同步实现过程,当中提供了一个工系统进程调用的服务,那么这个服务究竟是怎么被启动和使用的呢?这篇博文我就大体梳理一下启动过程. 事实上作为一个一般开发者,我们仅仅要知道要想 ...

  10. [cocos2d-x 3.0] 触摸显示器

    一.基本使用 1.首先,声明一个监听器 有两种,EventListenerTouchOneByOne 和 EventListenerTouchAllAtOnce,前者是单点触控.后者是多点触控.后者我 ...