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

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

RSA加密解密源码:

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("1234567");
            Console.WriteLine(encodeString);

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

            Console.ReadLine();
        }

时间: 2024-09-21 20:41:49

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

php rsa 加密,解密,签名,验签详解_php技巧

php rsa 加密,解密,签名,验签 由于对接第三方机构使用的是Java版本的rsa加解密方法,所有刚开始在网上搜到很多PHP版本的rsa加解密,但是对接java大多都不适用. 以下php版本是适用于对接java接口,java适用密钥再php语言使用是需要添加 -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- 使用密钥:加密公钥  public_key.cer 解密私钥  private_key.key 签名私钥 sign_key.ke

在asp中通过vbs类实现rsa加密与解密,建议入精华

加密|解密|精华 在asp中通过vbs类实现rsa加密与解密,建议入精华 本文章有两文件组成 test.asp 测试演示文件 clsrsa.asp 实现rsa加密与解密的vbs类文件下面是代码: 1. test.asp <%rem 文章标题:在asp中通过vbs类实现rsa加密与解密rem 收集整理:yanekrem 联系:aspboy@263.net %><%Option Explicit%><!--#INCLUDE FILE="clsRSA.asp"-

在asp中通过vbs类实现rsa加密与解密

加密|解密 本文章有两文件组成test.asp 测试演示文件clsrsa.asp 实现rsa加密与解密的vbs类文件下面是代码: 1. test.asp <%rem 文章标题:在asp中通过vbs类实现rsa加密与解密rem 收集整理:yanekrem 联系:aspboy@263.net %><%Option Explicit%><!--#INCLUDE FILE="clsRSA.asp"--><% Dim LngKeyEDim LngKeyD

在ASP中实现RsA加密与解密

加密|解密 文章有两文件组成,test.asp 测试演示文件:clsrsa.asp 实现rsa加密与解密的vbs类文件下面是代码: 1. test.asp <%rem 文章标题:在asp中通过vbs类实现rsa加密与解密 %><%Option Explicit%><!--#INCLUDE FILE="clsRSA.asp"--><% Dim LngKeyEDim LngKeyDDim LngKeyNDim StrMessageDim ObjRS

求帮助!ios用RSA加密和解密!在线等

问题描述 求帮助!ios用RSA加密和解密!在线等 用 oc 实现RSA 加密和解密 在线等 谢谢 解决方案 参考:http://blog.163.com/l1_jun/blog/static/1438638820127292147316/ 解决方案二: 公钥和私钥都是服务端生成好的.直接复制过来的 求个大神啊 解决方案三: 理论上服务端只会给你公钥,私钥,服务端要自己保留. 你只能用公钥加密,或者解密. 如果oc支持不够好,那么就可能要利用c来做.rsa 解决方案四: 现在公司的意思 是 我发

在asp中通过vbs类实现rsa加密与解密的代码_应用技巧

在asp中通过vbs类实现rsa加密与解密,建议入精华 本文章有两文件组成 test.asp 测试演示文件 clsrsa.asp 实现rsa加密与解密的vbs类文件 下面是代码: 1. test.asp  复制代码 代码如下: <%  rem 文章标题:在asp中通过vbs类实现rsa加密与解密  rem 收集整理:yanek  rem 联系:aspboy@263.net  %>  <%Option Explicit%>  <!--#INCLUDE FILE="cl

Android使用RSA加密和解密的示例代码

一.公钥加密和私钥解密 /**RSA算法*/ public static final String RSA = "RSA"; /**加密方式,android的*/ // public static final String TRANSFORMATION = "RSA/None/NoPadding"; /**加密方式,标准jdk的*/ public static final String TRANSFORMATION = "RSA/None/PKCS1Pad

php pki加密技术(openssl)详解

本篇文章是对php中的pki加密技术(openssl)进行了详细的分析介绍,需要的朋友参考下   复制代码 代码如下: <?php//pki加密//使用pki加密需要开启 openssl扩展 //php.ini extension = php_openssl.dll扩展 /*pki模式是 * 公钥加密,私钥解密: * 私钥加密,公钥解密: */ //私钥加密,公钥解密 //客户端 //$data数据 $data = 'abcd'; //获取私钥 $priv_key_id $priv_key_id

php pki加密技术(openssl)详解_php技巧

复制代码 代码如下: <?php//pki加密//使用pki加密需要开启 openssl扩展//php.ini extension = php_openssl.dll扩展/*pki模式是 * 公钥加密,私钥解密: * 私钥加密,公钥解密: *///私钥加密,公钥解密//客户端//$data数据$data = 'abcd';//获取私钥 $priv_key_id$priv_key_id = openssl_get_privatekey(file_get_contents('99bill-rsa.p