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

简介: 原文:C#使用RSA证书文件加密和解密示例修改MSDN上的示例,使之可以通过RSA证书文件加密和解密,中间遇到一个小问题。 Q:执行ExportParameters()方法时,回报CryptographicException:该项不适于在指定状态下使用(Key not valid for use in specified state)。
原文: 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);

以下为示例程序:

View Code
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;
            }

        }
    }
}

 

 

 

目录
相关文章
|
2月前
|
算法 安全 Java
Java 实现 RSA 非对称加密算法-加解密和签名验签
Java 实现 RSA 非对称加密算法-加解密和签名验签
|
2月前
|
机器学习/深度学习 算法 安全
【加密算法】RSA非对称加密算法简介
【加密算法】RSA非对称加密算法简介
|
3月前
|
前端开发 JavaScript Java
RSA加密---前端---后端解密
RSA加密---前端加---后端解密
119 0
|
4月前
|
JavaScript 前端开发 测试技术
Postman 加密接口测试 | 使用Rsa、Aes对参数加密
Postman 加密接口测试 | 使用Rsa、Aes对参数加密
149 0
|
2天前
|
存储 安全 网络安全
C#编程的安全性与加密技术
【4月更文挑战第21天】C#在.NET框架支持下,以其面向对象和高级特性成为安全软件开发的利器。本文探讨C#在安全加密领域的应用,包括使用System.Security.Cryptography库实现加密算法,利用SSL/TLS保障网络传输安全,进行身份验证,并强调编写安全代码的重要性。实际案例涵盖在线支付、企业应用和文件加密,展示了C#在应对安全挑战的同时,不断拓展其在该领域的潜力和未来前景。
|
3月前
|
定位技术 C# 图形学
Unity和C#游戏编程入门:创建迷宫小球游戏示例
Unity和C#游戏编程入门:创建迷宫小球游戏示例
72 2
|
3月前
|
存储 安全 Go
加密必备技能:深入理解RSA与AES
加密必备技能:深入理解RSA与AES
78 0
|
3月前
|
C#
C# 布尔值和条件语句:入门指南和实用示例
在编程中,通常需要一个只能有两个值之一的数据类型,比如: 是 / 否 开 / 关 真 / 假 为此,C# 有一个 bool 数据类型,可以取 true 或 false 的值。
70 3
|
3月前
|
存储 C#
C# 数据类型与类型转换:包含教程与示例
使用正确的数据类型对应于相应的变量是重要的;这样可以避免错误、节省时间和内存,还会使您的代码更易于维护和阅读。最常见的数据类型有:
29 0
|
3月前
|
算法 Java 数据安全/隐私保护
如何使用 RSA 加密 JWT
如何使用 RSA 加密 JWT
28 0