/// <summary> /// Attempt to sign a PGP message using the specific private key. /// </summary> /// <param name="messageStream">Stream containing the message to sign.</param> /// <param name="signatureStream">Stream to write the signature into.</param> /// <param name="senderPublicKey">The BouncyCastle public key associated with the signature.</param> /// <param name="senderPrivateKey">The BouncyCastle private key to be used for signing.</param> /// <param name="hashAlgorithmTag">The hash algorithm tag to use for signing.</param> /// <param name="armor">Whether to wrap the message with ASCII armor.</param> /// <returns>Whether the signature completed successfully.</returns> public static bool Sign(Stream messageStream, Stream signatureStream, PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, bool armor = true) { // Create a signature generator. PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(senderPublicKey.Algorithm, hashAlgorithmTag); signatureGenerator.InitSign(PgpSignature.BinaryDocument, senderPrivateKey); // Add the public key user ID. foreach (string userId in senderPublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator signatureSubGenerator = new PgpSignatureSubpacketGenerator(); signatureSubGenerator.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(signatureSubGenerator.Generate()); break; } // Handle ASCII armor. if (armor) { using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(signatureStream)) { armoredStream.BeginClearText(hashAlgorithmTag); // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { armoredStream.WriteByte((byte)messageChar); signatureGenerator.Update((byte)messageChar); } armoredStream.EndClearText(); using (BcpgOutputStream bcpgStream = new BcpgOutputStream(armoredStream)) { signatureGenerator.Generate().Encode(bcpgStream); } } } else { // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { signatureGenerator.Update((byte)messageChar); } signatureGenerator.Generate().Encode(signatureStream); } return true; }