.net核心PGP加密解密 [英] .net core PGP Encryption Decryption
本文介绍了.net核心PGP加密解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void Encryption()
遇到错误。
public void Encryption()
{
#region PGP Encryption
PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(@"C:\Keys\PGPPublicKey.asc", @"C:\Keys\PGPPrivateKey.asc", "password");
PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys);
using (Stream outputStream = File.Create("C:\\Keys\\EncryptData.txt"))
{
encrypter.EncryptAndSign(outputStream, new FileInfo(@"D:\Keys\PlainText.txt"));
}
Console.WriteLine("Encryption Done !");
#endregion
}
我使用了 https://code.msdn.microsoft.com/vstudio/Pretty-Good- Privacy-using-4f473c67
作为参考。
I used https://code.msdn.microsoft.com/vstudio/Pretty-Good-Privacy-using-4f473c67 as a reference.
我对 PgpEncryptionKeys
中的参数感到困惑。
I am confused about the parameters in the PgpEncryptionKeys
.
有人有可行的示例或帮助吗?这是我第一次加密,因此我几乎不会丢失。
Does anyone have a working example or help? This is my first time encrypting so I am little lost.
推荐答案
我正在通过这种方式使用:
I'm using by this way:
我认为可以帮助您!
助手:
public static void EncryptPgpFile(string inputFile, string outputFile, string publicKeyFile, bool armor, bool withIntegrityCheck)
{
using (Stream publicKeyStream = File.OpenRead(publicKeyFile))
{
PgpPublicKey pubKey = ReadPublicKey(publicKeyStream);
using (MemoryStream outputBytes = new MemoryStream())
{
PgpCompressedDataGenerator dataCompressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
PgpUtilities.WriteFileToLiteralData(dataCompressor.Open(outputBytes), PgpLiteralData.Binary, new FileInfo(inputFile));
dataCompressor.Close();
PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
dataGenerator.AddMethod(pubKey);
byte[] dataBytes = outputBytes.ToArray();
using (Stream outputStream = File.Create(outputFile))
{
if (armor)
{
using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream))
using (Stream outputStream = dataGenerator.Open(armoredStream, dataBytes.Length))
outputStream.Write(dataBytes, 0, dataBytes.Length);
}
else
{
using (Stream outputStream = dataGenerator.Open(armoredStream, dataBytes.Length))
outputStream.Write(dataBytes, 0, dataBytes.Length);
}
}
}
}
}
private static PgpPublicKey ReadPublicKey(Stream inputStream)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);
foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings())
{
foreach (PgpPublicKey key in keyRing.GetPublicKeys())
{
if (key.IsEncryptionKey)
return key;
}
}
throw new ArgumentException("Can't find encryption key in key ring.");
}
用法:
EncryptPgpFile(inputFile, outputFile, publicKeyPath, true, true);
这篇关于.net核心PGP加密解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文