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> ...
随机推荐
- 《JS高程》创建对象的7种方式(完整版)
一.理解对象 ECMA-262定义对象:无序属性的集合,其属性可以包含基本值.对象或者属性. 我们可以把 ECMAScript 的对象想象成 散列表:无非就是一组 名值对,其中值可以是数据或函数. 创 ...
- 基于Open vSwitch的OpenFlow实践
Open vSwitch(下面简称为 OVS)是由 Nicira Networks 主导的,运行在虚拟化平台(例如 KVM,Xen)上的虚拟交换机.在虚拟化平台上,OVS 可以为动态变化的端点提供 2 ...
- (实用篇)PHP不用递归遍历目录下所有文件的代码
<?php /** * PHP 非递归实现查询该目录下所有文件 * @param unknown $dir * @return multitype:|multitype:string */ fu ...
- Codeforces Round #372 (Div. 2) A B C 水 暴力/模拟 构造
A. Crazy Computer time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- IOKit找不到问题定义
Xcode511下Undefined symbols for architecture armv7s: "_IOMasterPort", referenced from: ...
- 关于C中scanf()函数读取字符串的问题
#include <stdio.h> int main(void) { ]; scanf("%s", s_name); printf("Hello, %s!\ ...
- 单元测试--四则运算2程序(c++)
源代码: //2016 3.6 Cheng Qiqin //四则运算改进 #include <iostream> #include<ctime> #include<cst ...
- WindowsServer问题总结
1.System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志.不可访问的日志: Security.在安装的“回滚”阶段发生异常.将忽略该异常并继续回 ...
- Codeforces Round #133 (Div. 2)
A. Tiling with Hexagons 看成大三角形扣去3个小三角形. B. Forming Teams 由于每个点的度数不超过2,所以最后每个点要么在一条链上要么在一个环上. 在环上的话,每 ...
- Codeforces Round #116 (Div. 2, ACM-ICPC Rules)
Codeforces Round #116 (Div. 2, ACM-ICPC Rules) 代码 Codeforces Round #116 (Div. 2, ACM-ICPC Rules) A. ...