public class EncrypHelp
{
static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
byte[] encryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (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.
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.Message); return null;
} } static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (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.
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.ToString()); return null;
} } public static String Encrypt(String plaintext, X509Certificate2 pubcrt)
{
X509Certificate2 _X509Certificate2 = pubcrt;
using (RSACryptoServiceProvider RSACryptography = _X509Certificate2.PublicKey.Key as RSACryptoServiceProvider)
{
Byte[] PlaintextData = Encoding.UTF8.GetBytes(plaintext);
int MaxBlockSize = RSACryptography.KeySize / 8 - 11; //加密块最大长度限制 if (PlaintextData.Length <= MaxBlockSize)
return Convert.ToBase64String(RSACryptography.Encrypt(PlaintextData, false)); using (MemoryStream PlaiStream = new MemoryStream(PlaintextData))
using (MemoryStream CrypStream = new MemoryStream())
{
Byte[] Buffer = new Byte[MaxBlockSize];
int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize); while (BlockSize > 0)
{
Byte[] ToEncrypt = new Byte[BlockSize];
Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize); Byte[] Cryptograph = RSACryptography.Encrypt(ToEncrypt, false);
CrypStream.Write(Cryptograph, 0, Cryptograph.Length); BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
} return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
}
}
} public static String Decrypt(String ciphertext, X509Certificate2 prvpfx)
{
X509Certificate2 _X509Certificate2 = prvpfx;
using (RSACryptoServiceProvider RSACryptography = _X509Certificate2.PrivateKey as RSACryptoServiceProvider)
{
Byte[] CiphertextData = Convert.FromBase64String(ciphertext);
int MaxBlockSize = RSACryptography.KeySize / 8; //解密块最大长度限制 if (CiphertextData.Length <= MaxBlockSize)
return Encoding.UTF8.GetString(RSACryptography.Decrypt(CiphertextData, false)); using (MemoryStream CrypStream = new MemoryStream(CiphertextData))
using (MemoryStream PlaiStream = new MemoryStream())
{
Byte[] Buffer = new Byte[MaxBlockSize];
int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize); while (BlockSize > 0)
{
Byte[] ToDecrypt = new Byte[BlockSize];
Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize); Byte[] Plaintext = RSACryptography.Decrypt(ToDecrypt, false);
PlaiStream.Write(Plaintext, 0, Plaintext.Length); BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
} return Encoding.UTF8.GetString(PlaiStream.ToArray());
}
}
} private static X509Certificate2 RetrieveX509Certificate()
{
return null; //检索用于 RSA 加密的 X509Certificate2 证书
} //调用方法 public void doit()
{ //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("310991");
byte[] encryptedData;
byte[] decryptedData; X509Certificate2 pubcrt = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "cmb.cer");
RSACryptoServiceProvider pubkey = (RSACryptoServiceProvider)pubcrt.PublicKey.Key;
//X509Certificate2 prvcrt = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "bfkey.pfx", "123456789", X509KeyStorageFlags.Exportable);
//RSACryptoServiceProvider prvkey = (RSACryptoServiceProvider)prvcrt.PrivateKey; encryptedData = EncrypHelp.RSAEncrypt(dataToEncrypt, pubkey.ExportParameters(false), false);
string encryptedDataStr = Convert.ToBase64String(encryptedData);
Console.WriteLine("Encrypted plaintext: {0}", Convert.ToBase64String(encryptedData)); //decryptedData = EncrypHelp.RSADecrypt(encryptedData, prvkey.ExportParameters(true), false);
//Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData)); //加密长内容
String data = @"RSA 是常用的非对称加密算法。最近使用时却出现了“不正确的长度”的异常,研究发现是由于待加密的数据超长所致。
   .NET Framework 中提供的 RSA 算法规定:
   待加密的字节数不能超过密钥的长度值除以 8 再减去 11(即:RSACryptoServiceProvider.KeySize / 8 - 11),而加密后得到密文的字节数,正好是密钥的长度值除以 8(即:RSACryptoServiceProvider.KeySize / 8)。
   所以,如果要加密较长的数据,则可以采用分段加解密的方式,实现方式如下:"; string encrypt = EncrypHelp.Encrypt(data, pubcrt);
Console.WriteLine("Encrypted plaintext: {0}", encrypt);
//string decrypt = EncrypHelp.Decrypt(encrypt, prvcrt);
//Console.WriteLine("Decrypted plaintext: {0}", decrypt); //prvkey.Clear();
pubkey.Clear();
Console.Read(); }
}

  

C#使用RSA证书文件加密和解密的更多相关文章

  1. C#使用RSA证书文件加密和解密示例

    修改MSDN上的示例,使之可以通过RSA证书文件加密和解密,中间遇到一个小问题. Q:执行ExportParameters()方法时,回报CryptographicException:该项不适于在指定 ...

  2. Angular+Ionic+RSA实现后端加密前端解密功能

    因业务需要,需要给android应用安装证书,通过读取证书文件内容实现某些功能的控制: 流程:后台通过publicKey对指定内容的文件进行加密,生成文件共客户下载,客户下载后选择该证书文件读取到应用 ...

  3. 使用PHP实现RSA算法的加密和解密

    本文提供使用RSA算法加密解密数据的PHP程序类(签名和验签的实现方式可以查看使用PHP实现RSA算法的签名和验签 这篇文章),封装了格式化公钥和私钥文件的方法,这样无论使用什么格式的公钥或者私钥都可 ...

  4. RSA加密算法的加密与解密

    转发原文链接:RSA加密算法加密与解密过程解析 1.加密算法概述 加密算法根据内容是否可以还原分为可逆加密和非可逆加密. 可逆加密根据其加密解密是否使用的同一个密钥而可以分为对称加密和非对称加密. 所 ...

  5. TEA加密算法的文件加密和解密的实现

    一.TEA加密算法简介 TEA加密算法是由英国剑桥大学计算机实验室提出的一种对称分组加密算法.它采用扩散和混乱方法,对64位的明文数据块,用128位密钥分组进行加密,产生64位的密文数据块,其循环轮数 ...

  6. RSA算法 JS加密 JAVA解密

    有这样一个需求,前端登录的usernamepassword,password必需加密.但不可使用MD5,由于后台要检測password的复杂度,那么在保证安全的前提下将password传到后台呢,答案 ...

  7. RSA生成、加密、解密、签名。

    首先,要会生成RSA密码对. https://app.alipay.com/market/document.htm?name=saomazhifu#page-23    (事例中的密钥对好像有问题,最 ...

  8. Android中文件加密和解密的实现

    最近项目中需要用到加解密功能,言外之意就是不想让人家在反编译后通过不走心就能获取文件里一些看似有用的信息,但考虑到加解密的简单实现,这里并不使用AES或DES加解密 为了对android中assets ...

  9. RSA非对称性前端加密后端解密

    前端加密代码 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

随机推荐

  1. CentOS7 手动部署flannel并启用vxlan

    本以为docker准备妥当之后,就可以直接上k8s了,结果yum install kubernetes,报错:Error: docker-ce conflicts with docker-1.9.1 ...

  2. volatile关键字作用

    1.阻止编译器对代码进行优化.即读取某个变量值时,不从寄存器中读取而是从变量里读. 2.编译器的优化 在本次线程内,当读取一个变量时,为提高存取速度,编译器优化时有时会先把变量读取到一个寄存器中:以后 ...

  3. 记录es在虚拟机的开启步骤

    最近开始接触elasticserach数据库,于是想在虚拟机上装一个练练手,装的时候可是费了好多时间,百度了许多教程,但是教程太多太乱,怕自己容易忘,所以记录一下,但是我主要记录是装好的es数据库如何 ...

  4. Linux环境下部署开源版“禅道”方法

    1.开源版安装包下载(Linux系统版本查看命令 uname -a) 32位 [root@iZbp~]# wget http://dl.cnezsoft.com/zentao/9.0.1/ZenTao ...

  5. deepin Gtk-WARNING **: 无法在模块路径中找到主题引擎:“adwaita”

    虽然没影响使用,但是看着有点不爽. 执行 sudo apt-get install gnome-themes-standard 就可以了.

  6. NAT穿透的详解及分析

    一.什么是NAT?为什么要使用NAT?NAT是将私有地址转换为合法IP地址的技术,通俗的讲就是将内网与内网通信时怎么将内网私有IP地址转换为可在网络中传播的合法IP地址.NAT的出现完美地解决了lP地 ...

  7. JavaScript核心--Function

    什么是: 保存一段可重用的代码段的对象 何时: 只要一段代码可能反复使用时,都要封装为函数,反复调用函数 如何: 创建: 3种: 1. 直接量: function 函数名(参数列表){ 函数体; re ...

  8. Got error on conf /etc/mha/app1.cnf: Parameter name master_ip_failover_scrip is invalid!

    问题: [root@db03-53 ~]# masterha_check_repl --conf=/etc/mha/app1.cnf Tue Apr 2 20:24:58 2019 - [warnin ...

  9. (转)Illustrated: Efficient Neural Architecture Search ---Guide on macro and micro search strategies in ENAS

    Illustrated: Efficient Neural Architecture Search --- Guide on macro and micro search strategies in  ...

  10. LintCode 846.多关键字排序

    LintCode 846.多关键字排序 描述 给定 n 个学生的学号(从 1 到 n 编号)以及他们的考试成绩,表示为(学号,考试成绩),请将这些学生按考试成绩降序排序,若考试成绩相同,则按学号升序排 ...