public Task <string> SignData(string fingerPrint, byte[] data, HashAlgorithmTag hash = HashAlgorithmTag.Sha512) { if (fingerPrint.Length == 8 && FP8TO16.ContainsKey(fingerPrint)) { fingerPrint = FP8TO16[fingerPrint]; } if (!decryptedKeys.ContainsKey(fingerPrint)) { throw new KeyNotDecryptedException(fingerPrint); } var pgpSec = privateKeys[fingerPrint]; var pgpPrivKey = decryptedKeys[fingerPrint]; return(Task.Run(() => { using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); using (var bOut = new BcpgOutputStream(s)) { var sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, hash); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); sGen.Update(data, 0, data.Length); sGen.Generate().Encode(bOut); s.Close(); ms.Seek(0, SeekOrigin.Begin); return Encoding.UTF8.GetString(ms.ToArray()); } } })); }
public string Encrypt(string filename, byte[] data, PgpPublicKey publicKey) { using (MemoryStream encOut = new MemoryStream(), bOut = new MemoryStream()) { var comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var cos = comData.Open(bOut); // open it with the final destination var lData = new PgpLiteralDataGenerator(); var pOut = lData.Open( cos, // the compressed output stream PgpLiteralData.Binary, filename, // "filename" to store data.Length, // length of clear data DateTime.UtcNow // current time ); pOut.Write(data, 0, data.Length); lData.Close(); comData.Close(); var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom()); cPk.AddMethod(publicKey); byte[] bytes = bOut.ToArray(); var s = new ArmoredOutputStream(encOut); var cOut = cPk.Open(s, bytes.Length); cOut.Write(bytes, 0, bytes.Length); // obtain the actual bytes from the compressed stream cOut.Close(); s.Close(); encOut.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(encOut); return(reader.ReadToEnd()); } }
private void repeatHeaderTest() { MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); aOut.SetHeader("Comment", "Line 1"); aOut.AddHeader("Comment", "Line 2"); aOut.Write(sample, 0, sample.Length); aOut.Close(); MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); ArmoredInputStream aIn = new ArmoredInputStream(bIn, true); string[] hdrs = aIn.GetArmorHeaders(); int count = 0; for (int i = 0; i != hdrs.Length; i++) { if (hdrs[i].IndexOf("Comment: ") == 0) { count++; } } IsEquals(2, count); }
private static string GetArmorString(Object key) { var memStream = new MemoryStream(); var armoredStream = new ArmoredOutputStream(memStream); if (key as PgpPublicKeyRing != null) { ((PgpPublicKeyRing)key).Encode(armoredStream); } else if (key as PgpPublicKeyRingBundle != null) { ((PgpPublicKeyRingBundle)key).Encode(armoredStream); } else if (key as PgpSecretKeyRing != null) { ((PgpSecretKeyRing)key).Encode(armoredStream); } else if (key as PgpSecretKey != null) { ((PgpSecretKey)key).Encode(armoredStream); } else if (key as PgpSecretKeyRingBundle != null) { ((PgpSecretKeyRingBundle)key).Encode(armoredStream); } else { return(null); } armoredStream.Close(); var ascString = Encoding.ASCII.GetString(memStream.ToArray()); return(ascString); }
public string Encrypt(byte[] message, PgpPublicKey publicKey) { if (message == null || message.Length == 0) { throw new ArgumentException("Message must be supplied", nameof(message)); } if (publicKey == null) { throw new ArgumentException("Public key must be supplied", nameof(publicKey)); } byte[] processedData = Compress(message, PgpLiteralData.Console, CompressionAlgorithmTag.Zip); MemoryStream bOut = new MemoryStream(); Stream output = new ArmoredOutputStream(bOut); PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom()); encGen.AddMethod(publicKey); Stream encOut = encGen.Open(output, processedData.Length); encOut.Write(processedData, 0, processedData.Length); encOut.Close(); output.Close(); return(Encoding.UTF8.GetString(bOut.ToArray())); }
public static Task <string> SignData(byte[] data, HashAlgorithmTag hash = HashAlgorithmTag.Sha512) { if (masterPrivateKey == null) { throw new ErrorObject { ErrorCode = ErrorCodes.SealedStatus, ErrorField = "gpgkey", Message = "The GPG Key is currently encrypted. Please decrypt it first with Unseal" }.ToException(); } return(Task.Run(() => { using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); using (var bOut = new BcpgOutputStream(s)) { var sGen = new PgpSignatureGenerator(masterSecretKey.PublicKey.Algorithm, hash); sGen.InitSign(PgpSignature.BinaryDocument, masterPrivateKey); sGen.Update(data, 0, data.Length); sGen.Generate().Encode(bOut); s.Close(); ms.Seek(0, SeekOrigin.Begin); return Tools.GPG2Quanto(Encoding.UTF8.GetString(ms.ToArray()), masterSecretKey.PublicKey.GetFingerprint().ToHexString(), hash); } } })); }
public Task <string> GenerateGPGKey(string identifier, string password, int bits = 3072) { return(Task.Run(() => { using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); var kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), bits, 25)); var kp = kpg.GenerateKeyPair(); var secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, identifier, SymmetricKeyAlgorithmTag.Cast5, password.ToCharArray(), null, null, new SecureRandom() ); secretKey.Encode(s); s.Close(); ms.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(ms); return reader.ReadToEnd(); } })); }
private void generateTest( string message, string type) { PgpSecretKey pgpSecKey = ReadSecretKey(new MemoryStream(secretKey)); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey("".ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator it = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (it.MoveNext()) { spGen.SetSignerUserId(false, (string)it.Current); sGen.SetHashedSubpackets(spGen.Generate()); } MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(message), false); aOut.BeginClearText(HashAlgorithmTag.Sha256); // // note the last \n m_in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, bIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, bIn); sGen.Update((byte)'\r'); sGen.Update((byte)'\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); }while (lookAhead != -1); } aOut.EndClearText(); BcpgOutputStream bcpgOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bcpgOut); aOut.Close(); byte[] bs = bOut.ToArray(); messageTest(Encoding.ASCII.GetString(bs, 0, bs.Length), type); }
/// <summary> /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath} /// </summary> public static PgpSignatureResult SignFile(PgpSignatureInput input) { HashAlgorithmTag digest = input.HashFunction.ConvertEnum <HashAlgorithmTag>(); using (var privateKeyStream = File.OpenRead(input.PrivateKeyFile)) { var pgpSecKey = PgpServices.SignatureReadSecretKey(privateKeyStream); var pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); var signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); var signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); var enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { signatureSubpacketGenerator.SetSignerUserId(false, (string)enumerator.Current); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); } using (var outputStream = File.Create(input.OutputFile)) { var armoredOutputStream = new ArmoredOutputStream(outputStream); var bcbgOutputStream = new BcpgOutputStream(armoredOutputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(bcbgOutputStream); var file = new FileInfo(input.InputFile); var literalDataGenerator = new PgpLiteralDataGenerator(); var literalDataOut = literalDataGenerator.Open(bcbgOutputStream, PgpLiteralData.Binary, file.Name, file.Length, DateTime.Now); using (var fileIn = file.OpenRead()) { int ch; while ((ch = fileIn.ReadByte()) >= 0) { literalDataOut.WriteByte((byte)ch); signatureGenerator.Update((byte)ch); } fileIn.Close(); literalDataGenerator.Close(); signatureGenerator.Generate().Encode(bcbgOutputStream); armoredOutputStream.Close(); outputStream.Close(); var ret = new PgpSignatureResult { FilePath = input.OutputFile }; return(ret); } } } }
private string GetSecretKey(PgpSecretKey secretKey) { var secretMemStream = new MemoryStream(); var secretArmoredStream = new ArmoredOutputStream(secretMemStream); secretKey.Encode(secretArmoredStream); secretArmoredStream.Close(); var ascPgpSecretKey = Encoding.ASCII.GetString(secretMemStream.ToArray()); return(ascPgpSecretKey); }
private string GetPublicKey(PgpSecretKey secretKey) { var pubMemStream = new MemoryStream(); var pubArmoredStream = new ArmoredOutputStream(pubMemStream); secretKey.PublicKey.Encode(pubArmoredStream); pubArmoredStream.Close(); var ascPgpPublicKey = Encoding.ASCII.GetString(pubMemStream.ToArray()); return(ascPgpPublicKey); }
string PGPEncryptToASCIIArmored(byte[] data, string filename = "encrypted-data.gpg") { using (var encOut = new MemoryStream()) { var byteData = GPGTools.EncryptForKeys(data, keys, filename); var s = new ArmoredOutputStream(encOut); s.Write(byteData, 0, byteData.Length); s.Close(); encOut.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(encOut); return(reader.ReadToEnd()); } }
public void ExportPublicKeyFromDbSecret(long keyId, string saveFileName) { PgpSecretKey secretKey = ReadSecretKey(keyId); Stream outFile = File.Create(saveFileName); outFile = new ArmoredOutputStream(outFile); PgpPublicKey publicKey = secretKey.PublicKey; publicKey.Encode(outFile); outFile.Close(); }
private static string DoSigning(string input, Stream keyIn, Stream outputStream, char[] pass) { var digest = HashAlgorithmTag.Sha256; var pgpSecretKey = ReadSigningSecretKey(keyIn); var pgpPrivateKey = pgpSecretKey.ExtractPrivateKey(pass); var signatureGenerator = new PgpSignatureGenerator(pgpSecretKey.PublicKey.Algorithm, digest); var subpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureGenerator.InitSign(PgpSignature.StandAlone, pgpPrivateKey); foreach (var userId in pgpSecretKey.PublicKey.GetUserIds()) { subpacketGenerator.SetSignerUserId(false, userId.ToString()); signatureGenerator.SetHashedSubpackets(subpacketGenerator.Generate()); } Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(input)); var armoredOut = new ArmoredOutputStream(outputStream); armoredOut.BeginClearText(digest); // note the last \n/\r/\r\n in the file is ignored var lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, inputStream); ProcessLine(armoredOut, signatureGenerator, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, inputStream); signatureGenerator.Update((byte)'\n'); ProcessLine(armoredOut, signatureGenerator, lineOut.ToArray()); }while (lookAhead != -1); } inputStream.Close(); armoredOut.EndClearText(); var bcpgOutput = new BcpgOutputStream(armoredOut); signatureGenerator.Generate().Encode(bcpgOutput); armoredOut.Close(); outputStream.Seek(0, 0); return(new StreamReader(outputStream).ReadToEnd()); }
public void EncryptAndSign(byte[] data, Stream outStream) { try { outStream = new ArmoredOutputStream(outStream); PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); encryptedDataGenerator.AddMethod(publicKey); PgpCompressedDataGenerator compressedData = null; try { Stream encryptedOut = encryptedDataGenerator.Open(outStream, new byte[BUFFER_SIZE]); compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); try { Stream compressedOut = compressedData.Open(encryptedOut); PgpSignatureGenerator signatureGenerator = createSignatureGenerator(); signatureGenerator.GenerateOnePassVersion(false).Encode(compressedOut); WriteToLiteralData(signatureGenerator, compressedOut, data); signatureGenerator.Generate().Encode(compressedOut); compressedOut.Close(); } catch (Exception e) { } encryptedOut.Close(); } finally { if (compressedData != null) { compressedData.Close(); } try { encryptedDataGenerator.Close(); } catch (IOException e) { } outStream.Close(); } } catch (Exception ex) { throw new CryptoException(ex.Message, ex); } }
public void UpdateDbSecretKey(PgpSecretKey key, string keyExportName) { Stream outFile = File.Create(keyExportName); Stream outArmor = new ArmoredOutputStream(outFile); string secKey = string.Empty; key.Encode(outArmor); outArmor.Close(); using (StreamReader rdr = new StreamReader(outFile)) { rdr.BaseStream.Position = 0; secKey = rdr.ReadToEnd(); } KeyStores updKey = m_keyStoreDb.KeyStores.Find(key.KeyId); updKey.ArmouredKeyFile = secKey; m_keyStoreDb.SaveChanges(); }
public string GetPublicKeyASCII(string fingerPrint) { var publicKey = krm[fingerPrint]; if (publicKey == null) { throw new KeyNotLoadedException(fingerPrint); } using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); publicKey.Encode(s); s.Close(); ms.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(ms); return(reader.ReadToEnd()); } }
private Keypair Armor(AsymmetricCipherKeyPair keyPair, string email) { var privateKey = keyPair.Private; var publicKey = keyPair.Public; var memOut = new MemoryStream(); var secretOut = new ArmoredOutputStream(memOut); var secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.Now, email, SymmetricKeyAlgorithmTag.Null, null, null, null, new SecureRandom() ); secretKey.Encode(secretOut); secretOut.Close(); var memPublicOut = new MemoryStream(); Stream publicOut = new ArmoredOutputStream(memPublicOut); var key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); var privateKeyStr = Encoding.Default.GetString(memOut.ToArray()); var publicKeyStr = Encoding.Default.GetString(memPublicOut.ToArray()); var pair = new Keypair { PrivateKey = privateKeyStr, PublicKey = publicKeyStr }; return(pair); }
private Keypair Armor(AsymmetricCipherKeyPair keyPair, String email) { AsymmetricKeyParameter privateKey = keyPair.Private; AsymmetricKeyParameter publicKey = keyPair.Public; MemoryStream memOut = new MemoryStream(); ArmoredOutputStream secretOut = new ArmoredOutputStream(memOut); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.Now, email, SymmetricKeyAlgorithmTag.Null, null, null, null, new SecureRandom() ); secretKey.Encode(secretOut); secretOut.Close(); MemoryStream memPublicOut = new MemoryStream(); Stream publicOut = new ArmoredOutputStream(memPublicOut); PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); String privateKeyStr = System.Text.Encoding.Default.GetString(memOut.ToArray()); String publicKeyStr = System.Text.Encoding.Default.GetString(memPublicOut.ToArray()); Keypair pair = new Keypair(); pair.PrivateKey = privateKeyStr; pair.PublicKey = publicKeyStr; return(pair); }
bool TestPrivateKey(PgpPublicKey publicKey, PgpPrivateKey privateKey) { try { byte[] testData = Encoding.ASCII.GetBytes("testdata"); var signature = ""; using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); using (var bOut = new BcpgOutputStream(s)) { var sGen = new PgpSignatureGenerator(publicKey.Algorithm, HashAlgorithmTag.Sha512); sGen.InitSign(PgpSignature.BinaryDocument, privateKey); sGen.Update(testData); sGen.Generate().Encode(bOut); s.Close(); ms.Seek(0, SeekOrigin.Begin); signature = Encoding.UTF8.GetString(ms.ToArray()); } } return(VerifySignature(testData, signature, publicKey)); } catch (Exception e) { Logger.Error(PGPManagerLog, $"Error verifing private key: {e}"); return(false); } }
public static void Main( string[] args) { if (args.Length == 1) { Stream fis = File.OpenRead(args[0]); PgpPublicKeyRing ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(fis)); PgpPublicKey key = ring.GetPublicKey(); // iterate through all direct key signautures and look for NotationData subpackets foreach (PgpSignature sig in key.GetSignaturesOfType(PgpSignature.DirectKey)) { Console.WriteLine("Signature date is: " + sig.GetHashedSubPackets().GetSignatureCreationTime()); NotationData[] data = sig.GetHashedSubPackets().GetNotationDataOccurrences(); for (int i = 0; i < data.Length; i++) { Console.WriteLine("Found Notation named '" + data[i].GetNotationName() + "' with content '" + data[i].GetNotationValue() + "'."); } } fis.Close(); } else if (args.Length == 5) { Stream secFis = File.OpenRead(args[0]); Stream pubFis = File.OpenRead(args[2]); // gather command line arguments PgpSecretKeyRing secRing = new PgpSecretKeyRing( PgpUtilities.GetDecoderStream(secFis)); String secretKeyPass = args[1]; PgpPublicKeyRing ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(pubFis)); String notationName = args[3]; String notationValue = args[4]; // create the signed keyRing PgpPublicKeyRing sRing = null; sRing = new PgpPublicKeyRing( new MemoryStream( SignPublicKey(secRing.GetSecretKey(), secretKeyPass, ring.GetPublicKey(), notationName, notationValue, true), false)); ring = sRing; secFis.Close(); pubFis.Close(); Stream fos = File.Create("SignedKey.asc"); // write the created keyRing to file ArmoredOutputStream aOut = new ArmoredOutputStream(fos); sRing.Encode(aOut); aOut.Close(); // Note: ArmoredOutputStream.Close() leaves underlying stream open fos.Close(); } else { Console.Error.WriteLine("usage: DirectKeySignature secretKeyFile secretKeyPass publicKeyFile(key to be signed) NotationName NotationValue"); Console.Error.WriteLine("or: DirectKeySignature signedPublicKeyFile"); } }
/// <summary> /// Create a file with PGP clear text signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpClearTextSignature Returns: Object {string FilePath} /// </summary> public static Result PGPClearTextSignFile(Input input) { HashAlgorithmTag digest; if (input.HashFunction == HashFunctionType.MD5) { digest = HashAlgorithmTag.MD5; } else if (input.HashFunction == HashFunctionType.RipeMD160) { digest = HashAlgorithmTag.RipeMD160; } else if (input.HashFunction == HashFunctionType.Sha1) { digest = HashAlgorithmTag.Sha1; } else if (input.HashFunction == HashFunctionType.Sha224) { digest = HashAlgorithmTag.Sha224; } else if (input.HashFunction == HashFunctionType.Sha384) { digest = HashAlgorithmTag.Sha384; } else if (input.HashFunction == HashFunctionType.Sha512) { digest = HashAlgorithmTag.Sha512; } else { digest = HashAlgorithmTag.Sha256; } Stream privateKeyStream = File.OpenRead(input.PrivateKeyFile); PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(input.InputFile); Stream outputStream = File.Create(input.OutputFile); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte)'\r'); sGen.Update((byte)'\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); }while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); outputStream.Close(); Result ret = new Result { FilePath = input.OutputFile }; return(ret); }
/// <summary> /// Signs the specified byte array using the specified key after unlocking the key with the specified passphrase. /// </summary> /// <param name="bytes">The byte array containing the payload to sign.</param> /// <param name="key">The PGP key to be used to sign the payload.</param> /// <param name="passphrase">The passphrase used to unlock the PGP key.</param> /// <returns>A byte array containing the generated PGP signature.</returns> public static byte[] Sign(byte[] bytes, string key, string passphrase) { // prepare a memory stream to hold the signature MemoryStream memoryStream = new MemoryStream(); // prepare an armored output stream to produce an armored ASCII signature Stream outputStream = new ArmoredOutputStream(memoryStream); // retrieve the keys PgpSecretKey secretKey = ReadSecretKeyFromString(key); PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passphrase.ToCharArray()); // create and initialize a signature generator PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha512); signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey); // retrieve the first user id contained within the public key and use it to set the signature signer foreach (string userId in secretKey.PublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureSubpacketGenerator.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); break; } // prepare a compressed data generator and compressed output stream to compress the data PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib); Stream compressedOutputStream = compressedDataGenerator.Open(outputStream); // generate the signature taken pretty much verbatim from the bouncycastle example; not sure what all of it does. BcpgOutputStream bcpgOutputStream = new BcpgOutputStream(compressedOutputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(bcpgOutputStream); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); Stream literalOutputStream = literalDataGenerator.Open(bcpgOutputStream, PgpLiteralData.Binary, "signatureData", DateTime.UtcNow, new byte[4092]); foreach (byte b in bytes) { literalOutputStream.WriteByte(b); signatureGenerator.Update(b); } literalDataGenerator.Close(); signatureGenerator.Generate().Encode(bcpgOutputStream); compressedDataGenerator.Close(); outputStream.Close(); // fetch a byte array containing the contents of the memory stream byte[] retVal = memoryStream.ToArray(); // close the memory stream memoryStream.Close(); // return the generated signature return(retVal); }
private void generateTest( string message, string type) { PgpSecretKey pgpSecKey = ReadSecretKey(new MemoryStream(secretKey)); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey("".ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator it = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (it.MoveNext()) { spGen.SetSignerUserId(false, (string)it.Current); sGen.SetHashedSubpackets(spGen.Generate()); } MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(message), false); aOut.BeginClearText(HashAlgorithmTag.Sha256); // // note the last \n m_in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, bIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, bIn); sGen.Update((byte) '\r'); sGen.Update((byte) '\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); } while (lookAhead != -1); } aOut.EndClearText(); BcpgOutputStream bcpgOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bcpgOut); aOut.Close(); byte[] bs = bOut.ToArray(); messageTest(Encoding.ASCII.GetString(bs, 0, bs.Length), type); }
private byte[] GetEncryptedData(byte[] data) { var baos = new MemoryStream(); var outStr = new ArmoredOutputStream(baos); PgpPublicKey publicKey = null; var inputStream = PgpUtilities.GetDecoderStream(new MemoryStream(_encryptionKey)); var pgpPub = new PgpPublicKeyRingBundle(inputStream); for (var i = pgpPub.GetKeyRings().GetEnumerator(); i.MoveNext();) { var pgpPublicKeyRing = (PgpPublicKeyRing)i.Current; if (pgpPublicKeyRing != null) { for (var j = pgpPublicKeyRing.GetPublicKeys().GetEnumerator(); publicKey == null && j.MoveNext();) { var k = (PgpPublicKey)j.Current; if (k != null && k.IsEncryptionKey) { publicKey = k; } } } } if (publicKey == null) { throw new Exception("Can't find encryption key in key ring."); } var pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(new MemoryStream(_signingKey))); PgpPrivateKey privateKey = null; PgpSecretKey secretKey = null; for (var i = pgpSec.GetKeyRings().GetEnumerator(); privateKey == null && i.MoveNext();) { var keyRing = (PgpSecretKeyRing)i.Current; if (keyRing != null) { for (var j = keyRing.GetSecretKeys().GetEnumerator(); j.MoveNext();) { secretKey = (PgpSecretKey)j.Current; if (secretKey != null) { privateKey = secretKey.ExtractPrivateKey(_password); } break; } } } if (secretKey == null) { throw new Exception("Can't find signature key in key ring."); } var cb = new MemoryStream(); var compressedGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var compressedOut = compressedGenerator.Open(cb); var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha512); signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey); for (var i = secretKey.PublicKey.GetUserIds().GetEnumerator(); i.MoveNext();) { var spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, (String)i.Current); signatureGenerator.SetHashedSubpackets(spGen.Generate()); } signatureGenerator.GenerateOnePassVersion(true).Encode(compressedOut); var lgen = new PgpLiteralDataGenerator(); var finalOut = lgen.Open(compressedOut, PgpLiteralData.Binary, "", DateTime.Now, new byte[4096]); finalOut.Write(data, 0, data.Length); signatureGenerator.Update(data); finalOut.Close(); lgen.Close(); signatureGenerator.Generate().Encode(compressedOut); compressedGenerator.Close(); compressedOut.Close(); var compressedData = cb.ToArray(); var encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom()); encryptedDataGenerator.AddMethod(publicKey); var encryptedOut = encryptedDataGenerator.Open(outStr, compressedData.Length); encryptedOut.Write(compressedData, 0, compressedData.Length); encryptedOut.Close(); encryptedDataGenerator.Close(); outStr.Close(); return(baos.ToArray()); }
public void TestMethod1() { string secretKeyFile = @"-----BEGIN PGP PRIVATE KEY BLOCK----- Version: BCPG C# v1.7.4137.9688 lQc0BFTbeXUBEACgRx6VZYo0M8Vhv7D+ukhEPAIQHmbv41oae3vCIN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GDkAQWAe9L+i BQ7R6w== =Z4JC -----END PGP PRIVATE KEY BLOCK-----"; File.WriteAllText(Path.Combine(@"C:\Users\John\BcPGP", "testuser1@example_com_secret.asc"), secretKeyFile); MemoryStream msSec = new MemoryStream(Encoding.UTF8.GetBytes(secretKeyFile)); PgpSecretKeyRing secRing = new PgpSecretKeyRing(PgpUtilities.GetDecoderStream(msSec)); char[] passPhrase = new char[] { 't', 'e', 's', 't', 'u', 's', 'e', 'r' }; PgpPublicKeyRing pubRing = new PgpPublicKeyRing(secRing.GetPublicKey().GetEncoded()); PgpPublicKeyRing newRing = new PgpPublicKeyRing( new MemoryStream(RevokePublicKey(secRing.GetSecretKey(), passPhrase, pubRing.GetPublicKey(), true))); msSec.Close(); Assert.IsTrue(newRing.GetPublicKey().IsRevoked()); Stream fos = File.Create(@"C:\Users\John\BcPGP\RevokedKey.asc"); ArmoredOutputStream aOut = new ArmoredOutputStream(fos); newRing.Encode(aOut); aOut.Close(); fos.Close(); PgpSecretKey newSecret = PgpSecretKey.ReplacePublicKey(secRing.GetSecretKey(), newRing.GetPublicKey()); Stream foSec = File.Create(@"C:\Users\John\BcPGP\SecretRevokedKey.asc"); ArmoredOutputStream sOut = new ArmoredOutputStream(foSec); newSecret.Encode(sOut); sOut.Close(); foSec.Close(); Assert.IsTrue(newSecret.PublicKey.IsRevoked()); }
/* * create a clear text signed file. */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, string digestName) { HashAlgorithmTag digest; if (digestName.Equals("SHA256")) { digest = HashAlgorithmTag.Sha256; } else if (digestName.Equals("SHA384")) { digest = HashAlgorithmTag.Sha384; } else if (digestName.Equals("SHA512")) { digest = HashAlgorithmTag.Sha512; } else if (digestName.Equals("MD5")) { digest = HashAlgorithmTag.MD5; } else if (digestName.Equals("RIPEMD160")) { digest = HashAlgorithmTag.RipeMD160; } else { digest = HashAlgorithmTag.Sha1; } PgpSecretKey pgpSecKey = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(fileName); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte)'\r'); sGen.Update((byte)'\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); }while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); }
public override void PerformTest() { // // test immediate close // MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); aOut.Close(); byte[] data = bOut.ToArray(); if (data.Length != 0) { Fail("No data should have been written"); } // // multiple close // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); aOut.Close(); int mc = markerCount(bOut.ToArray()); if (mc < 1) { Fail("No end marker found"); } if (mc > 1) { Fail("More than one end marker found"); } // // writing and reading single objects // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); PgpObjectFactory fact = new PgpObjectFactory(aIn); int count = 0; while (fact.NextPgpObject() != null) { count++; } if (count != 1) { Fail("wrong number of objects found: " + count); } // // writing and reading multiple objects - in single block // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Write(sample, 0, sample.Length); aOut.Close(); aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); fact = new PgpObjectFactory(aIn); count = 0; while (fact.NextPgpObject() != null) { count++; } if (count != 2) { Fail("wrong number of objects found: " + count); } // // writing and reading multiple objects - in single block // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); // does not close underlying stream aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); count = 0; bool atLeastOne; do { atLeastOne = false; fact = new PgpObjectFactory(aIn); while (fact.NextPgpObject() != null) { atLeastOne = true; count++; } }while (atLeastOne); if (count != 2) { Fail("wrong number of objects found: " + count); } blankLineTest(); pgpUtilTest(); repeatHeaderTest(); }
/* * create a clear text signed file. */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, string digestName) { HashAlgorithmTag digest; if (digestName.Equals("SHA256")) { digest = HashAlgorithmTag.Sha256; } else if (digestName.Equals("SHA384")) { digest = HashAlgorithmTag.Sha384; } else if (digestName.Equals("SHA512")) { digest = HashAlgorithmTag.Sha512; } else if (digestName.Equals("MD5")) { digest = HashAlgorithmTag.MD5; } else if (digestName.Equals("RIPEMD160")) { digest = HashAlgorithmTag.RipeMD160; } else { digest = HashAlgorithmTag.Sha1; } PgpSecretKey pgpSecKey = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string) enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(fileName); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte) '\r'); sGen.Update((byte) '\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); } while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); }
public static void AddSignature(PgpPublicKey key, KeyStoreDB keyDb, string keyExportName, PgpSecretKey secKey, char[] passPhrase, SignatureOperation op, DateTime expiryDate, PgpSignature certLevel = null, string userId = "") { string fileData = string.Empty; bool useTemp = true; if (key == null) { throw new ArgumentNullException("key"); } if (keyDb == null) { throw new ArgumentNullException("keyDb"); } if (!Enum.IsDefined(typeof(SignatureOperation), op)) { throw new ArgumentOutOfRangeException(string.Format("op: {0}", op)); } AlgorithmAgreement algorithms = new AlgorithmAgreement(new List <PgpPublicKey>() { key }); PgpPrivateKey privateKey = secKey.ExtractPrivateKey(passPhrase); PgpSignatureGenerator sigGen = new PgpSignatureGenerator(key.Algorithm, algorithms.AgreedHashAlgorithm); switch (op) { case SignatureOperation.AddUserId: break; case SignatureOperation.RevokeKey: MemoryStream mStream = new MemoryStream(); using (ArmoredOutputStream outArmour = new ArmoredOutputStream(mStream)) { outArmour.SetHeader("Version", "Lynx Privacy"); sigGen.InitSign(PgpSignature.KeyRevocation, privateKey); PgpSignature sig = sigGen.GenerateCertification(secKey.PublicKey); PgpPublicKey.AddCertification(secKey.PublicKey, sig); sig.InitVerify(secKey.PublicKey); if (!sig.VerifyCertification(secKey.PublicKey)) { throw new PgpException("revocation verification failed."); } sig.Encode(outArmour); outArmour.Close(); } mStream.Position = 0; StreamReader srdr = new StreamReader(mStream); string armour = srdr.ReadToEnd(); string outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK") .Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK"); mStream.Close(); if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } File.WriteAllText(keyExportName, outstr); keyExportName = ""; //Debug.Assert(secKey.PublicKey.IsRevoked() == true); break; case SignatureOperation.SetKeyExpiry: break; case SignatureOperation.CertifyKey: break; default: break; } if (secKey.PublicKey != null) { if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } ExportKey expKey = new ExportKey(keyDb); expKey.UpdateDbSecretKey(secKey, keyExportName); if (useTemp) { //File.Delete(keyExportName); } } }
/* * create a clear text signed file. */ public static void SignFile( //string fileName, Stream fIn, PgpSecretKey pgpSecKey, Stream outputStream, char[] pass, string digestName, bool version = true ) { HashAlgorithmTag digest; if (string.Equals(digestName, "Sha256", StringComparison.CurrentCultureIgnoreCase)) { digest = HashAlgorithmTag.Sha256; } else if (string.Equals(digestName, "Sha384", StringComparison.CurrentCultureIgnoreCase)) { digest = HashAlgorithmTag.Sha384; } else if (string.Equals(digestName, "Sha512", StringComparison.CurrentCultureIgnoreCase)) { digest = HashAlgorithmTag.Sha512; } else if (string.Equals(digestName, "MD5", StringComparison.CurrentCultureIgnoreCase)) { digest = HashAlgorithmTag.MD5; } else if (string.Equals(digestName, "RipeMD160", StringComparison.CurrentCultureIgnoreCase)) { digest = HashAlgorithmTag.RipeMD160; } else { digest = HashAlgorithmTag.Sha512; } // Instanciate signature generator. var sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); var spGen = new PgpSignatureSubpacketGenerator(); // Extract private key PgpPrivateKey pgpPrivKey; try { pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); } catch { throw new PgpException("Wrong Passphrase, could not extract private key."); } var enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } var aOut = new ArmoredOutputStream(outputStream); if (version) { aOut.SetHeader("Version", "Posh-OpenPGP"); } aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // var lineOut = new MemoryStream(); var lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte)'\r'); sGen.Update((byte)'\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); }while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); var bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); }
public override void PerformTest() { // // test immediate close // MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); aOut.Close(); byte[] data = bOut.ToArray(); if (data.Length != 0) { Fail("No data should have been written"); } // // multiple close // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); aOut.Close(); int mc = markerCount(bOut.ToArray()); if (mc < 1) { Fail("No end marker found"); } if (mc > 1) { Fail("More than one end marker found"); } // // writing and reading single objects // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); PgpObjectFactory fact = new PgpObjectFactory(aIn); int count = 0; while (fact.NextPgpObject() != null) { count++; } if (count != 1) { Fail("wrong number of objects found: " + count); } // // writing and reading multiple objects - in single block // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Write(sample, 0, sample.Length); aOut.Close(); aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); fact = new PgpObjectFactory(aIn); count = 0; while (fact.NextPgpObject() != null) { count++; } if (count != 2) { Fail("wrong number of objects found: " + count); } // // writing and reading multiple objects - in single block // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); // does not close underlying stream aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); count = 0; bool atLeastOne; do { atLeastOne = false; fact = new PgpObjectFactory(aIn); while (fact.NextPgpObject() != null) { atLeastOne = true; count++; } } while (atLeastOne); if (count != 2) { Fail("wrong number of objects found: " + count); } blankLineTest(); }
/// <summary> /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath} /// </summary> public static Result PGPSignFile(Input input) { HashAlgorithmTag digest; if (input.HashFunction == HashFunctionType.MD5) { digest = HashAlgorithmTag.MD5; } else if (input.HashFunction == HashFunctionType.RipeMD160) { digest = HashAlgorithmTag.RipeMD160; } else if (input.HashFunction == HashFunctionType.Sha1) { digest = HashAlgorithmTag.Sha1; } else if (input.HashFunction == HashFunctionType.Sha224) { digest = HashAlgorithmTag.Sha224; } else if (input.HashFunction == HashFunctionType.Sha384) { digest = HashAlgorithmTag.Sha384; } else if (input.HashFunction == HashFunctionType.Sha512) { digest = HashAlgorithmTag.Sha512; } else { digest = HashAlgorithmTag.Sha256; } Stream privateKeyStream = File.OpenRead(input.PrivateKeyFile); PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(Org.BouncyCastle.Bcpg.OpenPgp.PgpSignature.BinaryDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream outputStream = File.Create(input.OutputFile); ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream); BcpgOutputStream bOut = new BcpgOutputStream(armoredOutputStream); sGen.GenerateOnePassVersion(false).Encode(bOut); FileInfo file = new FileInfo(input.InputFile); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file); FileStream fIn = file.OpenRead(); int ch; while ((ch = fIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } fIn.Close(); lGen.Close(); sGen.Generate().Encode(bOut); armoredOutputStream.Close(); outputStream.Close(); Result ret = new Result { FilePath = input.OutputFile }; return(ret); }