一.由于.net项目中用到了pgp加密协议 主要是生成公钥和私钥 利用公钥加密 私钥解密
DidiSoft.BouncyCastle DidiSoft.Pgp 两个dll 并在项目中引入DidiSoft.Pgp命名空间
类库下载地址 https://didisoft.com/net-openpgp
二
1.首先生成秘钥存储
///
/// 生成存储秘钥
///
///
public static void GenerateKeyStore()
{
//文件路劲和密码
KeyStore ks = new KeyStore(@"D:\key.store", "changeit");
//私钥密码
String userId = "rsa_demo@didisoft.com";
String privateKeyPassword = "private key password";
String privateKeyPassword = "private key password";
HashAlgorithm[] hashing = { HashAlgorithm.SHA1,
HashAlgorithm.MD5,
HashAlgorithm.SHA256,
HashAlgorithm.SHA384,
HashAlgorithm.SHA512};
CompressionAlgorithm[] compression =
{ CompressionAlgorithm.ZIP,
CompressionAlgorithm.ZLIB,
CompressionAlgorithm.UNCOMPRESSED};
CypherAlgorithm[] cypher = { CypherAlgorithm.CAST5,
CypherAlgorithm.AES_128,
CypherAlgorithm.AES_192,
CypherAlgorithm.AES_256,
CypherAlgorithm.BLOWFISH};
ks.GenerateKeyPair(2048,
userId,
KeyAlgorithm.RSA,
privateKeyPassword,
compression,
hashing,
cypher);
}
2.生成秘钥对
///
/// 生成秘钥对
///
public static void ExportKeyPair()
{
// 存储秘钥路径 和密码
KeyStore ks = KeyStore.OpenFile(@“D:\key.store”, “changeit”);
// 导出的文件应该是 ASCII 还是二进制
bool asciiArmored = true;
// 导出公钥和私钥以及一个文件中的所有子密钥
}
3.利用公钥加密
///
/// 加密
///
/// 明文
/// 公钥路径
///
public static String EncryptString(string plainText,string publicKeyFilePath)
{
// initialize the library
PGPLib pgp = new PGPLib();
// FileInfo publicKeyFile = new FileInfo(@“DataFiles\public.key”);
FileInfo publicKeyFile = new FileInfo(publicKeyFilePath);
string encryptedString = pgp.EncryptString(plainText, publicKeyFile);
return encryptedString;
}
3. 利用私钥解密
///
/// 解密
///
/// 密文
/// 私钥文件路径
/// 私钥密码
///
public static String DecryptString(String encryptedString,string privateKeyFile, string privateKeyPassword)
{
PGPLib pgp = new PGPLib();
//String plainString = pgp.DecryptString(encryptedString,
// new FileInfo(@“DataFiles\secretkey.asc”),
// “changeit”);
//String plainString = pgp.DecryptString(encryptedString,
// new FileInfo(@“DataFiles\secretkey.asc”),
// “Welcome2sohu!”);
String plainString = pgp.DecryptString(encryptedString,privateKeyFile,privateKeyPassword);
return plainString; }