C#实现RSA加密和解密详解

原文: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;

    }

}

}

}
 测试代码:

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->        static void Main(string[] args)
        {
            string encodeString = MyRSA.Encrypt("1234567");
            Console.WriteLine(encodeString);

string decode = MyRSA.Decrypt(encodeString);
            Console.WriteLine(decode);

Console.ReadLine();
        }

时间: 2024-10-24 10:32:34

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

简易版DES加密和解密详解

在DES密码里,是如何进行加密和解密的呢?这里采用DES的简易版来进行说明. 二进制数据的变换 由于不仅仅是DES密码,在其它的现代密码中也应用了二进制数据,所以无论是文章还是数字,都需要将明文变换为二进制数据,如图表所示,这里仅将使用的16字符(其中含有1个没有意义的空字符),将每个字符都对应不同的4bit的二进制编码进行变换,将明文表示成"0"和"1"的系列 表2.8 表2.9 本文部分参考自漫画密码,此文博主花了几个小时的时间整理,转载请注明http://ww

iOS rsa加密与解密

转自 --响铃  IOS rsa加密与解密 ras加密需要两组秘钥,一组公共秘钥,一组私有秘钥. 生成命令: openssl req -x509 -out public_key.der -outform der -new -newkey rsa:2048 -keyout private_key.pem public_key.der为公共秘钥文件,private_key.pem为私有秘钥文件. 生成ios可引用的私有秘钥文件.pfx: 1. OpenSSL rsa -in private_key.

通过ios实现RSA加密和解密

在加密和解密中,我们需要了解的知识有什么事openssl:RSA加密算法的基本原理:如何通过openssl生成最后我们需要的der和p12文件. 废话不多说,直接写步骤: 第一步:openssl来生成公钥和私钥证书,最后需要得到公钥证书和私钥证书 . 这是在mac OX系统下显示的证书,如果我们用文本编辑器打开它,会发现里面是----BEGIN RSA 开头  并且----END RSA 结尾的一串字符串. 第二步:我们需要在代码中写我们的加密和机密方法,加密的字符串通过公钥进行加密,加密后的字

RSA加密和解密工具类

1 import org.apache.commons.codec.binary.Base64; 2 3 import javax.crypto.Cipher; 4 import java.security.*; 5 import java.security.spec.PKCS8EncodedKeySpec; 6 import java.security.spec.X509EncodedKeySpec; 7 import java.util.HashMap; 8 import java.util

Maven项目的RSA加密及解密(用户数据)的配置流程:

做过三年多的程序员了,之前同事们都喜欢发表博客文章 而鄙人特例.  一般都是看文章,毕竟有现成的粮食,干嘛还多此一举额,呵呵. 也就没想着注册一下账号  就在前不久注册这个账号了  也是没怎更好的利用起来 : 这不心血来潮 ,突然意识到不发表些博客文章 感觉就不是一个完整的程序员  ,因此就有了以下文章  . 头一次发表  若有人查阅  如有什不足之处,多提意见,  多多见谅... 第一步: 获得RSA公钥私钥(秘钥格式:PKCS#8 测试:建议是无私钥密码的,省一些麻烦) 公钥: -----B

RSA加密、解密、签名、验签 DSA签名、验签

重要的事情说三遍,该篇文章主要是验证JAVA的RSA签名.验签的测试代码,主要代码参考 http://xw-z1985.iteye.com/blog/1837376 重要的事情说三遍,该篇文章主要是验证JAVA的RSA签名.验签的测试代码,主要代码参考 http://xw-z1985.iteye.com/blog/1837376 重要的事情说三遍,该篇文章主要是验证JAVA的RSA签名.验签的测试代码,主要代码参考 http://xw-z1985.iteye.com/blog/1837376 下

php 的rsa加密与解密

系统:centos6.5 linux系统生成公私钥对方法: openssl genrsa -out rsa_private_key.pem 1024 openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem 第一条命令生成

C# 与 Java Rsa加密与解密互通

Rsa 加密标准的制定已经过去了十多年了. 这两天在看rsa 加密的文章,基本上都是在说 .net 与 java 之间的 rsa加密是不能互通的.因为项目有用到,所以花了点时间对rsa加密做了一点点了解,发现,不管是java 还是 C# 都对 rsa 的标准加密进行了实现, 是 对于标准是实现,不能互通就讲不过去了. 今天特意写了一段java 代码试了一下,发现是完全可以的. 密钥的描述: C#(.net) 中有三种方式导出密钥,一种是blob,一种是 xml 另一种是参数,其中xml 的方式是

利用openssl生成公钥、私钥 Rsa加密、解密及验证签名

//获取公钥私钥 X509Certificate2 c4 = DataCertificate.GetCertFromCerFile(path + "\\cer\\xx.pem"); string PublicKey = c4.PublicKey.Key.ToXmlString(false);//公钥 X509Certificate2 c3 = DataCertificate.GetCertificateFromPfxFile(path + "\\cer\\yy.pfx&quo