Created
April 26, 2020 21:25
-
-
Save ihorbond/f316e14d0572fbbcc13eaa1362bf5dd1 to your computer and use it in GitHub Desktop.
Encrypt file with BouncyCastle and C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Org.BouncyCastle.Bcpg; | |
using Org.BouncyCastle.Bcpg.OpenPgp; | |
using Org.BouncyCastle.Security; | |
using System; | |
using System.IO; | |
namespace Helpers | |
{ | |
public class EncryptionHelper | |
{ | |
public static void EncryptFile(string inputFilePath, Stream outputStream, string publicKeyFilePath, | |
SymmetricKeyAlgorithmTag algorithmTag = SymmetricKeyAlgorithmTag.Aes128, bool withIntegrityPacket = true, bool armor = false) | |
{ | |
try | |
{ | |
using (Stream publicKeyStream = File.OpenRead(publicKeyFilePath)) | |
{ | |
PgpPublicKey encKey = ReadPublicKey(publicKeyStream); | |
using (MemoryStream bOut = new MemoryStream()) | |
{ | |
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); | |
PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary, new FileInfo(inputFilePath)); | |
comData.Close(); | |
PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(algorithmTag, withIntegrityPacket, new SecureRandom()); | |
cPk.AddMethod(encKey); | |
byte[] bytes = bOut.ToArray(); | |
if (armor) | |
outputStream = new ArmoredOutputStream(outputStream); | |
using (Stream cOut = cPk.Open(outputStream, bytes.Length)) | |
{ | |
cOut.Write(bytes, 0, bytes.Length); | |
} | |
} | |
} | |
} | |
catch (PgpException) | |
{ | |
throw; | |
} | |
} | |
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 Exception("Can't find encryption key in key ring."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment