C#使用RSA证书文件加密和解密示例
修改MSDN上的示例,使之可以通过RSA证书文件加密和解密,中间遇到一个小问题。
Q:执行ExportParameters()方法时,回报CryptographicException:该项不适于在指定状态下使用(Key not valid for use in specified state)。
A:导入带有私钥的证书时,需要使用"X509KeyStorageFlags"参数标记"私钥可导出"。
X509Certificate2 prvcrt = new X509Certificate2(@"X:\path\to\CA.pfx", "***password***", X509KeyStorageFlags.Exportable);
以下为示例程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TeatApp_Crypto
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text; class RSACSPSample
{ static void Main()
{
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("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData; X509Certificate2 pubcrt = new X509Certificate2(@"X:\path\to\CA.crt");
RSACryptoServiceProvider pubkey = (RSACryptoServiceProvider)pubcrt.PublicKey.Key;
X509Certificate2 prvcrt = new X509Certificate2(@"X:\path\to\CA.pfx", "***password***", X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider prvkey = (RSACryptoServiceProvider)prvcrt.PrivateKey;
//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
//using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
//{
//Console.WriteLine(RSA.ToXmlString(false));
//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt, pubkey.ExportParameters(false), false);
Console.WriteLine("Encrypted plaintext: {0}", Convert.ToBase64String(encryptedData)); //Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData, prvkey.ExportParameters(true), false); //Display the decrypted plaintext to the console.
Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
//}
prvkey.Clear();
pubkey.Clear();
Console.Read();
}
catch (ArgumentNullException)
{
//Catch this exception in case the encryption did
//not succeed.
Console.WriteLine("Encryption failed."); }
} 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;
} }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TeatApp_Crypto
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text; class RSACSPSample
{ static void Main()
{
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("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData; X509Certificate2 pubcrt = new X509Certificate2(@"X:\path\to\CA.crt");
RSACryptoServiceProvider pubkey = (RSACryptoServiceProvider)pubcrt.PublicKey.Key;
X509Certificate2 prvcrt = new X509Certificate2(@"X:\path\to\CA.pfx", "***password***", X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider prvkey = (RSACryptoServiceProvider)prvcrt.PrivateKey;
//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
//using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
//{
//Console.WriteLine(RSA.ToXmlString(false));
//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt, pubkey.ExportParameters(false), false);
Console.WriteLine("Encrypted plaintext: {0}", Convert.ToBase64String(encryptedData)); //Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData, prvkey.ExportParameters(true), false); //Display the decrypted plaintext to the console.
Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
//}
prvkey.Clear();
pubkey.Clear();
Console.Read();
}
catch (ArgumentNullException)
{
//Catch this exception in case the encryption did
//not succeed.
Console.WriteLine("Encryption failed."); }
} 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;
} }
}
}
C#使用RSA证书文件加密和解密示例的更多相关文章
- C#使用RSA证书文件加密和解密
public class EncrypHelp { static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKey ...
- Angular+Ionic+RSA实现后端加密前端解密功能
因业务需要,需要给android应用安装证书,通过读取证书文件内容实现某些功能的控制: 流程:后台通过publicKey对指定内容的文件进行加密,生成文件共客户下载,客户下载后选择该证书文件读取到应用 ...
- 使用PHP实现RSA算法的加密和解密
本文提供使用RSA算法加密解密数据的PHP程序类(签名和验签的实现方式可以查看使用PHP实现RSA算法的签名和验签 这篇文章),封装了格式化公钥和私钥文件的方法,这样无论使用什么格式的公钥或者私钥都可 ...
- RSA加密算法的加密与解密
转发原文链接:RSA加密算法加密与解密过程解析 1.加密算法概述 加密算法根据内容是否可以还原分为可逆加密和非可逆加密. 可逆加密根据其加密解密是否使用的同一个密钥而可以分为对称加密和非对称加密. 所 ...
- TEA加密算法的文件加密和解密的实现
一.TEA加密算法简介 TEA加密算法是由英国剑桥大学计算机实验室提出的一种对称分组加密算法.它采用扩散和混乱方法,对64位的明文数据块,用128位密钥分组进行加密,产生64位的密文数据块,其循环轮数 ...
- RSA算法 JS加密 JAVA解密
有这样一个需求,前端登录的usernamepassword,password必需加密.但不可使用MD5,由于后台要检測password的复杂度,那么在保证安全的前提下将password传到后台呢,答案 ...
- RSA生成、加密、解密、签名。
首先,要会生成RSA密码对. https://app.alipay.com/market/document.htm?name=saomazhifu#page-23 (事例中的密钥对好像有问题,最 ...
- Android中文件加密和解密的实现
最近项目中需要用到加解密功能,言外之意就是不想让人家在反编译后通过不走心就能获取文件里一些看似有用的信息,但考虑到加解密的简单实现,这里并不使用AES或DES加解密 为了对android中assets ...
- RSA非对称性前端加密后端解密
前端加密代码 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...
随机推荐
- Linux性能监控
转自:http://blog.csdn.net/chosen0ne/article/details/8200737 linux性能监控,就是要监控系统的各个子系统是否正常.linux主要的子系统包括: ...
- Xen虚拟机磁盘镜像模板制作(四)—CentOS 7
在<Xen虚拟机磁盘镜像模板制作(三)—CentOS 7>一文中,我们已经成功制作出了 CentOS7 磁盘镜像.下面我们说明下如何通过它来生成目标虚拟机,同时测试下之前制作好的虚拟机磁盘 ...
- 神逸之作:国产快速启动软件神品ALTRun
http://xbeta.info/altrun.htm 作者: ET民工和塞壬 日期: 2010-09-15 分类: windows 标签: quick-launch <神逸之作:国产快速启动 ...
- android 升级APK
Intent intent = new Intent(); //执行动作 intent.setAction(Intent.ACTION_VIEW); //执行完打开应用 intent.setFlags ...
- C陷阱与缺陷 1
1,符号之间的空白被忽略 符号中间不能嵌入空白 2,词法分析中的贪心法 a---b 和 a-- -b相同 和 a- --b不同 1 a=b/*p //根据贪心法 /*被解释成 注释符,便不再往下读,直 ...
- 故障模块名称: mso.dll
本人今天早上打开word文档的时候打不开了,反复试了n次也不成,一想八成儿要重新装了,结果我点开详细信息看了一下,看到了“故障模块名称: mso.dll”这个提示,结果我就放到了百度上找了一下,都是只 ...
- POJ 2186 Popular Cows(强连通)
Popular Cows Time Limit: 2000MS Memo ...
- JsonModelStrategy策略添加
今天在学习 zf2的时候,发现后端如果返回的是JsonModel的话,则在前台异步请求的时候发现取不到数据了,后来经过多次研究,才发现要在view_manager中创建策略,代ma是这样子的,stra ...
- hdu5442(2015长春赛区网络赛1006)后缀数组+KMP /最小表示法?
题意:给定一个由小写字母组成的长度为 n 的字符串,首尾相连,可以从任意一个字符开始,顺时针或逆时针取这个串(长度为 n),求一个字典序最大的字符串的开始字符位置和顺时针或逆时针.如果有多个字典序最大 ...
- 《剑指Offer》之二维数组中的查找
1.题目描述 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 2.代码实现 pu ...