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

原文: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;
            }

        }
    }
}
时间: 2024-10-13 00:48:16

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

文件加密及解密

1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using System.Runtime.Serialization; 6 using System.Security.Cryptography; 7 8 namespace Sky.Decrypt 9 { 10 /// <summary> 11 /// 解密 12 /// </summary>

用openssl对文件加密及解密

Openssl是一个开源的用以实现SSL协议的产品,它主要包括了三个部分:密码算法库.应用程序.SSL协议库.Openssl实现了SSL协议所需要的大多数算法. 下面我将单介绍使用Openssl进行文件的对称加密操作. 一.Openssl支持的加密算法有: -aes-128-cbc -aes-128-cfb -aes-128-cfb1 -aes-128-cfb8 -aes-128-ecb -aes-128-ofb -aes-192-cbc -aes-192-cfb -aes-192-cfb1 -

java spring中对properties属性文件加密及其解密

原创整理不易,转载请注明出处:java spring中对properties属性文件加密及其解密 代码下载地址:http://www.zuidaima.com/share/1781588957400064.htm 加密类: package com.zuidaima.commons.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import

C# 文件加密和解密

1.加密 using System;using System.Collections.Generic;using System.Text;using System.Runtime.Serialization;using System.IO;using System.Security.Cryptography; namespace Sky.Encrypt{    /// <summary>    /// 加密    /// </summary>    public class Enc

RSA算法 JS加密 JAVA解密

有这样一个需求,前端登录的用户名密码,密码必需加密,但不可使用MD5,因为后台要检测密码的复杂度,那么在保证安全的前提下将密码传到后台呢,答案就是使用RSA非对称加密算法解决 . java代码 需要依赖 commons-codec 包 RSACoder.java import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.*; import java.securit

RSA加密算法的加密与解密

转发原文链接:RSA加密算法加密与解密过程解析 1.加密算法概述 加密算法根据内容是否可以还原分为可逆加密和非可逆加密. 可逆加密根据其加密解密是否使用的同一个密钥而可以分为对称加密和非对称加密. 所谓对称加密即是指在加密和解密时使用的是同一个密钥:举个简单的例子,对一个字符串C做简单的加密处理,对于每个字符都和A做异或,形成密文S.解密的时候再用密文S和密钥A做异或,还原为原来的字符串C.这种加密方式有一个很大的缺点就是不安全,因为一旦加密用的密钥泄露了之后,就可以用这个密钥破解其他所有的密文

使用Vi/Vim给文件加密和解密

一. 利用vi加密: 优点:加密后,如果不知道密码,就看不到明文,包括root用户也看不了: 缺点:很明显让别人知道加密了,容易让别人把加密的文件破坏掉,包括内容破坏和删除: vi编辑器相信大家都很熟悉了吧,vi里有一个命令是给文件加密的,举个例子吧: 1) 首先在root主目录/root/下建立一个实验文件text.txt: [[email protected] ~]# vi text.txt 2) 进到编辑模式,输入完内容后按ESC,然后输入:X(注意是大写的X),回车: 3) 这时系统提示

CryptoJS文件加密与解密

import React, { Component } from 'react';import CryptoJS from 'crypto-js/crypto-js'import { Button } from 'antd'; class Encryption extends Component { constructor(){ super(); this.state={ value2:'qqqqqqqqqqqq', encryptioned:'', Decrypted:'' } } compo

xxtea 文件加密与解密

加密 cocos luacompile -s src -d dst_dir -e -b xxxxx -k xxxxx --disable-compile 解密 cocos luacompile -s src -d dst_dir -e -j  -b xxxxx -k xxxxx --disable-compile 说明:cocos默认只支持加密,不支持反向解密, 本人改一下python脚本 使其支持解密. -b 后面接的参数是在文件中可以见的. #!/usr/bin/python # -----