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> ...
随机推荐
- tinyhttpd-0.1.0_hacking
/**************************************************************************** * * tinyhttpd-0.1.0_ha ...
- LeetCode Rotate Image (模拟)
题意: 将一个n*n的矩阵顺时针旋转90度. 思路: 都是差不多的思路,交换3次也行,反转再交换也是行的. class Solution { public: void rotate(vector< ...
- 【Avalon】获取隐藏元素的尺寸
保存原来的属性 设置成显示的属性 获取尺寸 设置回原来的属性 var cssShow = { position: "absolute", visibility: "hid ...
- (实用篇)php精确的统计在线人数的方法
这是一个非常精确的,通过php实现统计在线人数的方法,想知道怎么实现的请耐心阅读. <?php $filename='online.txt';//数据文件 $cookiename='VGOTCN ...
- java serializable深入了解
声明:本文转自csdn论坛,原文地址为http://blog.csdn.net/zdw890412/article/details/7380069,对原作者表示感谢! 引言 将 Java 对象序列化为 ...
- CentOS下解决”用户账户is not in the sudoers file“问题
如上图,在当前用户cent(我的用户名)下使用sudo命令时,提示"cent is not in the sudoers file. This incident will be report ...
- HS光流算法详解<转载>
HS 光流法详解 前言 本文较为详细地介绍了一种经典的光流法 - HS 光流法. 光流法简介 当人的眼睛与被观察物体发生相对运动时,物体的影像在视网膜平面上形成一系列连续变化的图像,这一系列变化的图像 ...
- 软件或jar包等名字里的GA意思
首页 > 转贴的文章 > 软件的版本"GA"代表什么意思?如MyEclipse 5.0 GA 软件的版本"GA"代表什么意思?如MyEclips ...
- leetcode 124. Binary Tree Maximum Path Sum ----- java
Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence ...
- URAL 1080 Map Coloring(染色)
Map Coloring Time limit: 1.0 secondMemory limit: 64 MB We consider a geographical map with N countri ...