Nuget:
PasswordFinder.cs
using Org.BouncyCastle.OpenSsl;
namespace SHA256Demo
{
internal class PasswordFinder : IPasswordFinder
{
private string v;
public PasswordFinder(string v)
{
this.v = v;
}
public char[] GetPassword()
{
return v.ToCharArray();
}
}
}
Product.cs
namespace SHA256Demo
{
public class Product
{
public string Name { get; set; }
}
}
Program.cs
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace SHA256Demo
{
partial class Program
{
//自己生成
static string _publicKeyString = @"-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmu5B+WIU9ZK+uy11qmdj
KygwcH6r8YOui2jc87pWShKAEnEE2Q81twgQ4KGFylodpNsXs+EGeQA8HUiDKK11
Pm6AMzrqHQ8rtNNWbQA6Ca+BJJHEoyrizaHTGLWU7oHe9TcRQ8Iq5vihF74x1jD2
BHXpgR6KUhx9DUMFgdwpLXhZ2EgG85eOuajcHl+tLN52bEpGwSHyL5iWuX2U5qfN
Ln3h/lCmdktPwCjVVyaoLALxP0oDtalRwLKRJuD91p6YxrAeN3eRkGWoYXH5bSrS
BR+5id5yBplxayVrozJXFpOFySTrCHD2snnfjmn39dKsRjwRjKG/zKUPO54GPovv
rODK32c1xiKpQQ7XAzyXPNij3MWPJFu6z24eNdILm4wF1jFWQlrsca0znpjoAVFY
e1yp1lXAtYlxgNURMQ2RwvBtnT3BUhUP382GYd0XPdV1xodOaJVf8ce3YImrGaAY
jPjbTPTbTyzwcHyc1LHwYw4W7aYiTyX8p5+7PkdkRr8uiKA9iFhH6iq+7MPv5O0F
NGSktGZkyFSKg9vazQmESlUC+blC2yQRBJsqV84weMKG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uMjLbeXIAHuOG9wjuuV/Yla
XJBgOImw0Jhib7NqS0BKv3SvhHA7olduqOv9z0yGHXcHZKxB6O7+YKATc1nszjwc
cAEm30c3/mhCHPuathM0laKV36Z4hp2y8ginJdK7gZQSkyzjRDI2yx5cq6U=
-----END RSA PRIVATE KEY-----";
static string keyPwd = "123456";
static void Main(string[] args)
{
/*私钥数字签名,公钥验证*/
var priKeyFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cer/private.pfx");
var pubKeyFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cer/public.cer");
var contentForSign = "name=123&sex=boy";
var signedData = Sign(contentForSign, priKeyFile, keyPwd);
var verifyResult = VerifySign(contentForSign, signedData, pubKeyFile);
/*公钥加密,私钥解密*/
GenRSAKeyPair("xjl");
/*公钥加密,私钥解密*/
string encryptedTxt = RsaEncryptWithPublic(new Product { Name = "My test" });
RsaDecryptWithPrivate(encryptedTxt);
/*私钥加密,公钥解密*/
var _encryptedWithPrivateStr = RsaEncryptWithPrivate(new Product { Name = "My test" });
RsaDecryptWithPublic(_encryptedWithPrivateStr);
Console.WriteLine("Hello World!");
Console.ReadKey();
}
#region 私钥数字签名,公钥验证
private static string Sign(string contentForSign, string priKeyFile, string keyPwd)
{
var rsa = GetPrivateKey(priKeyFile, keyPwd);
// Create a new RSACryptoServiceProvider
var rsaClear = new RSACryptoServiceProvider();
// Export RSA parameters from 'rsa' and import them into 'rsaClear'
var paras = rsa.ExportParameters(true);
rsaClear.ImportParameters(paras);
var signData = rsa.SignData(Encoding.UTF8.GetBytes(contentForSign), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return BytesToHex(signData);
}
private static bool VerifySign(string contentForSign, string signedData, string pubKeyFile)
{
var rsa = GetPublicKey(pubKeyFile);
return rsa.VerifyData(Encoding.UTF8.GetBytes(contentForSign), HexToBytes(signedData), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
///
/// 获取签名证书私钥
///
///
///
///
private static RSACng GetPrivateKey(string priKeyFile, string keyPwd)
{
var pc = new X509Certificate2(priKeyFile, keyPwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
return (RSACng)pc.PrivateKey;
}
///
/// 获取验签证书
///
///
///
private static RSACng GetPublicKey(string pubKeyFile)
{
var pc = new X509Certificate2(pubKeyFile);
return (RSACng)pc.PublicKey.Key;
}
public static byte[] HexToBytes(string text)
{
if (text.Length % 2 != 0)
throw new ArgumentException("text 长度为奇数。");
List lstRet = new List();
for (int i = 0; i < text.Length; i = i + 2)
{
lstRet.Add(Convert.ToByte(text.Substring(i, 2), 16));
}
return lstRet.ToArray();
}
///
/// bytes转换hex
///
/// bytes
/// 转换后的hex字符串
public static string BytesToHex(byte[] data)
{
StringBuilder sbRet = new StringBuilder(data.Length * 2);
for (int i = 0; i < data.Length; i++)
{
sbRet.Append(Convert.ToString(data[i], 16).PadLeft(2, '0'));
}
return sbRet.ToString();
}
#endregion
///
/// 生成公钥/私钥
///
///
public static void GenRSAKeyPair(string name)
{
var generator = new RsaKeyPairGenerator();
var seed = Encoding.UTF8.GetBytes(name);
var secureRandom = new SecureRandom();
secureRandom.SetSeed(seed);
generator.Init(new KeyGenerationParameters(secureRandom, 4096));
var pair = generator.GenerateKeyPair();
//第一种方案
//var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
//var serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
//var serializedPrivate = Convert.ToBase64String(serializedPrivateBytes);
//Console.WriteLine("Private Key:" + serializedPrivate);
//var publickKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);
//var serializedPublicBytes = publickKeyInfo.ToAsn1Object().GetDerEncoded();
//var serializedPublic = Convert.ToBase64String(serializedPublicBytes);
//Console.WriteLine("Public Key:" + serializedPublic);
//第二种方案
var twPrivate = new StringWriter();
PemWriter pwPrivate = new PemWriter(twPrivate);
pwPrivate.WriteObject(pair.Private);
pwPrivate.Writer.Flush();
var privateKey = twPrivate.ToString();
Console.WriteLine("Private Key:" + privateKey);
var twPublic = new StringWriter();
PemWriter pwPublic = new PemWriter(twPublic);
pwPublic.WriteObject(pair.Public);
pwPublic.Writer.Flush();
var publicKey = twPublic.ToString();
Console.WriteLine("Public Key:" + publicKey);
}
///
/// 公钥加密
///
/// 待加密文本
public static string RsaEncryptWithPublic(Product dataToEncrypt)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dataToEncrypt));
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtReader = new StringReader(_publicKeyString))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtReader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
var encryptedText = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
// 获取publickKey对应的keyParameter的第一种方法
//var stringReader = new StringReader(_publicKeyString);
//var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(stringReader);
//var keyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();
// 获取publickKey对应的keyparameter的第二种方法
//var publicKey = Convert.FromBase64String(_publicKeyString);
//var keyParameter = PublicKeyFactory.CreateKey(publicKey);
//用公钥加密的第一种方法
//var engine = new RsaEngine();
//engine.Init(true, keyParamter);
//var blockSize = engine.GetInputBlockSize();
//return engine.ProcessBlock(data, 0, blockSize);
//用公钥加密的第二种方法
//IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
//cipher.Init(true, keyParameter);
//var encryptedText = Convert.ToBase64String(cipher.DoFinal(bytesToEncrypt));
Console.WriteLine("利用公钥加密后的数据:" + encryptedText);
return encryptedText;
}
///
/// 私钥加密
///
/// 待加密文本
public static string RsaEncryptWithPrivate(Product dataToEncrypt)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dataToEncrypt));
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtReader = new StringReader(_privateKeyString))
{
var keyPair = (AsymmetricCipherKeyPair)new PemReader(txtReader, new PasswordFinder("xjl")).ReadObject();
encryptEngine.Init(true, keyPair.Private);
}
var encryptedText = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
Console.WriteLine("利用私钥加密后的数据:" + encryptedText);
return encryptedText;
}
///
/// 私钥解密
///
/// 待解密的数据
public static void RsaDecryptWithPrivate(string dataToDecrypt)
{
var bytesToDecrypt = Convert.FromBase64String(dataToDecrypt);
获取privatekey对应的keyparameter的第一种方法
var stringReader = new StringReader(_privateKeyString);
//var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(stringReader);
var pemReader = new PemReader(stringReader, new PasswordFinder("xjl"));
var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
var keyParameter = keyPair.Private;
//获取privatekey对应的keyparameter的第二种方法
//var publicKey = Convert.FromBase64String(_publicKeyString);
//var keyParameter = PublicKeyFactory.CreateKey(publicKey);
// 用私钥解密的第一种方法
//var engine = new RsaEngine();
//engine.Init(false, keyParameter);
//var blockSize = engine.GetInputBlockSize();
//engine.ProcessBlock(dataToDecrypt, 0, blockSize);
// 用私钥解密的第二种方法
IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
cipher.Init(false, keyParameter);
var decipheredBytes = cipher.DoFinal(bytesToDecrypt);
var decipheredText = Encoding.UTF8.GetString(decipheredBytes);
Console.WriteLine("用私钥解密后的数据:" + decipheredText);
}
///
/// 公钥解密
///
/// 待解密的数据
public static void RsaDecryptWithPublic(string dataToDecrypt)
{
var bytesToDecrypt = Convert.FromBase64String(dataToDecrypt);
// 获取privatekey对应的keyparameter的第一种方法
var stringReader = new StringReader(_publicKeyString);
//var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(stringReader);
var pemReader = new PemReader(stringReader);
var keyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();
// 获取privatekey对应的keyparameter的第二种方法
//var publicKey = Convert.FromBase64String(_publicKeyString);
//var keyParameter = PublicKeyFactory.CreateKey(publicKey);
// 用私钥解密的第一种方法
//var engine = new RsaEngine();
//engine.Init(false, keyParameter);
//var blockSize = engine.GetInputBlockSize();
//engine.ProcessBlock(dataToDecrypt, 0, blockSize);
// 用私钥解密的第二种方法
IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
cipher.Init(false, keyParameter);
var decipheredBytes = cipher.DoFinal(bytesToDecrypt);
var decipheredText = Encoding.UTF8.GetString(decipheredBytes);
Console.WriteLine("用公钥解密后的数据:" + decipheredText);
}
}
}