/// <summary> /// Attempt to encrypt a message using PGP with the specified public key(s). /// </summary> /// <param name="messageStream">Stream containing the message to encrypt.</param> /// <param name="encryptedMessageStream">Stream to write the encrypted message into.</param> /// <param name="fileName">File name of for the message.</param> /// <param name="recipientPublicKeys">Collection of BouncyCastle public keys to be used for encryption.</param> /// <param name="symmetricKeyAlgorithmTag">The symmetric key algorithm tag to use for encryption.</param> /// <param name="armor">Whether to wrap the message with ASCII armor.</param> /// <returns>Whether the encryption completed successfully.</returns> public static bool Encrypt(Stream messageStream, Stream encryptedMessageStream, string fileName, IEnumerable<PgpPublicKey> recipientPublicKeys, SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = SymmetricKeyAlgorithmTag.TripleDes, bool armor = true) { // Allow any of the corresponding keys to be used for decryption. PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(symmetricKeyAlgorithmTag, true, new SecureRandom()); foreach (PgpPublicKey publicKey in recipientPublicKeys) { encryptedDataGenerator.AddMethod(publicKey); } // Handle optional ASCII armor. if (armor) { using (Stream armoredStream = new ArmoredOutputStream(encryptedMessageStream)) { using (Stream encryptedStream = encryptedDataGenerator.Open(armoredStream, new byte[Constants.LARGEBUFFERSIZE])) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed); using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream)) { PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); using (Stream literalDataStream = literalDataGenerator.Open(encryptedStream, PgpLiteralData.Binary, fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE])) { messageStream.Seek(0, SeekOrigin.Begin); messageStream.CopyTo(literalDataStream); } } } } } else { using (Stream encryptedStream = encryptedDataGenerator.Open(encryptedMessageStream, new byte[Constants.LARGEBUFFERSIZE])) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed); using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream)) { PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); using (Stream literalDataStream = literalDataGenerator.Open(encryptedStream, PgpLiteralData.Binary, fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE])) { messageStream.Seek(0, SeekOrigin.Begin); messageStream.CopyTo(literalDataStream); } } } } return true; }
/// <summary> /// Attempt to encrypt a message using PGP with the specified public key(s). /// </summary> /// <param name="messageStream">Stream containing the message to encrypt.</param> /// <param name="fileName">File name of for the message.</param> /// <param name="signedAndEncryptedMessageStream">Stream to write the encrypted message 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="recipientPublicKeys">Collection of BouncyCastle public keys to be used for encryption.</param> /// <param name="hashAlgorithmTag">The hash algorithm tag to use for signing.</param> /// <param name="symmetricKeyAlgorithmTag">The symmetric key algorithm tag to use for encryption.</param> /// <param name="armor">Whether to wrap the message with ASCII armor.</param> /// <returns>Whether the encryption completed successfully.</returns> public static bool SignAndEncrypt(Stream messageStream, string fileName, Stream signedAndEncryptedMessageStream, PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, IEnumerable<PgpPublicKey> recipientPublicKeys, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = SymmetricKeyAlgorithmTag.TripleDes, 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; } // Allow any of the corresponding keys to be used for decryption. PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, true, new SecureRandom()); foreach (PgpPublicKey publicKey in recipientPublicKeys) { encryptedDataGenerator.AddMethod(publicKey); } // Handle optional ASCII armor. if (armor) { using (Stream armoredStream = new ArmoredOutputStream(signedAndEncryptedMessageStream)) { using (Stream encryptedStream = encryptedDataGenerator.Open(armoredStream, new byte[Constants.LARGEBUFFERSIZE])) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed); using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream)) { signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary, fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE])) { // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { literalStream.WriteByte((byte)messageChar); signatureGenerator.Update((byte)messageChar); } } signatureGenerator.Generate().Encode(compressedStream); } } } } else { using (Stream encryptedStream = encryptedDataGenerator.Open(signedAndEncryptedMessageStream, new byte[Constants.LARGEBUFFERSIZE])) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed); using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream)) { signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary, fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE])) { // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { literalStream.WriteByte((byte)messageChar); signatureGenerator.Update((byte)messageChar); } } signatureGenerator.Generate().Encode(compressedStream); } } } return true; }
public override void Close() { if (this.type != null) { if (this.bufPtr > 0) { ArmoredOutputStream.Encode(this.outStream, this.buf, this.bufPtr); } this.DoWrite(ArmoredOutputStream.nl + '='); int value = this.crc.Value; this.buf[0] = (value >> 16 & 255); this.buf[1] = (value >> 8 & 255); this.buf[2] = (value & 255); ArmoredOutputStream.Encode(this.outStream, this.buf, 3); this.DoWrite(ArmoredOutputStream.nl); this.DoWrite(ArmoredOutputStream.footerStart); this.DoWrite(this.type); this.DoWrite(ArmoredOutputStream.footerTail); this.DoWrite(ArmoredOutputStream.nl); this.outStream.Flush(); this.type = null; this.start = true; base.Close(); } }
public static byte[] ToAsc(byte[] pgp) { MemoryStream ms = new MemoryStream(); var ring = new PgpPublicKeyRing(GetStream(pgp)); var armored = new ArmoredOutputStream(ms); ring.Encode(armored); armored.Dispose(); return ms.ToArray(); }
private string signEnvelopeData(string msg) { Stream privateKeyStream = getPrivateKeyStream(_privateKey); MemoryStream result = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(result); BcpgOutputStream bOut = null; char[] privateKeyPassword = _passPhrase.ToCharArray(); var utf8Encoding = new System.Text.UTF8Encoding(); try { PgpSecretKey sk = readSecretKey(privateKeyStream); PgpPrivateKey pk = sk.ExtractPrivateKey(privateKeyPassword); PgpSignatureGenerator sigGen = new PgpSignatureGenerator(sk.PublicKey.Algorithm,HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); var enumerator = sk.PublicKey.GetUserIds().GetEnumerator(); if(enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sigGen.SetHashedSubpackets(spGen.Generate()); } aOut.BeginClearText(HashAlgorithmTag.Sha256); sigGen.InitSign(PgpSignature.CanonicalTextDocument, pk); byte[] msgBytes = utf8Encoding.GetBytes(msg); sigGen.Update(msgBytes, 0, msgBytes.Length); aOut.Write(msgBytes, 0, msgBytes.Length); bOut = new BcpgOutputStream(aOut); aOut.EndClearText(); sigGen.Generate().Encode(bOut); using (BinaryReader br = new BinaryReader(result)) { br.BaseStream.Position = 0; return utf8Encoding.GetString(br.ReadBytes((int)result.Length)); } } catch (Exception e) { Console.WriteLine("This happened: " + e.Message); throw new Exception("Signing Failed: " + e.Message); } finally { try { if (privateKeyStream != null) privateKeyStream.Close(); //if(bOut != null) //bOut.Close(); //aOut.Close(); result.Close(); } catch (IOException) {} } }
public static void Encrypt(byte[] clearData, PgpPublicKey encKey, string fileName, FileStream fos, bool withIntegrityCheck, bool armor) { if (fileName == null) { fileName = PgpLiteralData.Console; } MemoryStream encOut = new MemoryStream(); Stream outPut = encOut; if (armor) { outPut = new Org.BouncyCastle.Bcpg.ArmoredOutputStream(outPut); } MemoryStream bOut = new MemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); Stream cos = comData.Open(bOut); // open it with the final // destination PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); // we want to generate compressed data. This might be a user option // later, // in which case we would pass in bOut. Stream pOut = lData.Open(cos, PgpLiteralData.Binary, fileName, clearData.Length, DateTime.Now); pOut.Write(clearData, 0, clearData.Length); lData.Close(); comData.Close(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new Org.BouncyCastle.Security.SecureRandom()); cPk.AddMethod(encKey); byte[] bytes = bOut.ToArray(); Stream cOut = cPk.Open(outPut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); outPut.Close(); //FileStream fileStream = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); // Writes a block of bytes to this stream using data from // a byte array. fos.Write(encOut.ToArray(), 0, encOut.ToArray().Length); // close file stream fos.Close(); }
private const int BufferSize = 0x10000; // should always be power of 2 #region Encrypt /// <summary> /// Encrypts the file. /// </summary> /// <param name="inputFile">The input file.</param> /// <param name="outputFile">The output file.</param> /// <param name="publicKeyFile">The public key file.</param> /// <param name="armor">if set to <c>true</c> [armor].</param> /// <param name="withIntegrityCheck">if set to <c>true</c> [with integrity check].</param> public static void EncryptFile(string inputFile, string outputFile, string publicKeyFile, bool armor, bool withIntegrityCheck) { try { using (Stream publicKeyStream = File.OpenRead(publicKeyFile)) { PgpPublicKey encKey = ReadPublicKey(publicKeyStream); using (MemoryStream bOut = new MemoryStream()) { PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary, new FileInfo(inputFile)); comData.Close(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); cPk.AddMethod(encKey); byte[] bytes = bOut.ToArray(); using (Stream outputStream = File.Create(outputFile)) { if (armor) { using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream)) { using (Stream cOut = cPk.Open(armoredStream, bytes.Length)) { cOut.Write(bytes, 0, bytes.Length); } } } else { using (Stream cOut = cPk.Open(outputStream, bytes.Length)) { cOut.Write(bytes, 0, bytes.Length); } } } } } } catch (PgpException e) { throw e; } }
private static void EncryptFile(Stream outputStream, string fileName, PgpPublicKey encKey, bool armor, bool withIntegrityCheck) { if (armor) outputStream = new ArmoredOutputStream(outputStream); try { MemoryStream bOut = new MemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpUtilities.WriteFileToLiteralData( comData.Open(bOut), PgpLiteralData.Binary, new FileInfo(fileName)); comData.Close(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); cPk.AddMethod(encKey); byte[] bytes = bOut.ToArray(); Stream cOut = cPk.Open(outputStream, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); if (armor) outputStream.Close(); } catch (PgpException e) { Console.Error.WriteLine(e); Exception underlyingException = e.InnerException; if (underlyingException != null) { Console.Error.WriteLine(underlyingException.Message); Console.Error.WriteLine(underlyingException.StackTrace); } } }
public static void SignFile(Stream input, Stream outputStream, Stream keyIn, char[] pass) { var secretKey = ReadSecretKey(keyIn); var privateKey = secretKey.ExtractPrivateKey(pass); var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); var subpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureGenerator.InitSign(PgpSignature.CanonicalTextDocument, privateKey); foreach (string userId in secretKey.PublicKey.GetUserIds()) { var signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureSubpacketGenerator.SetSignerUserId(isCritical: false, userId: userId); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); // Just the first one! break; } // Closing armouredOutputStream does not close the underlying stream var armouredOutputStream = new ArmoredOutputStream(outputStream); using (var bcpgOutputStream = new BcpgOutputStream(armouredOutputStream)) { armouredOutputStream.BeginClearText(HashAlgorithmTag.Sha1); int chr; while ((chr = input.ReadByte()) > 0) { signatureGenerator.Update((byte)chr); bcpgOutputStream.Write((byte)chr); } // For some reason we need to add a trailing newline bcpgOutputStream.Write((byte)'\n'); armouredOutputStream.EndClearText(); signatureGenerator.Generate().Encode(bcpgOutputStream); } }
/// <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; }
public static void Main(string[] args) { if (args.Length == 1) { Stream fis = File.OpenRead(args[0]); var ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(fis)); var 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()); var data = sig.GetHashedSubPackets().GetNotationDataOccurences(); for (int i = 0; i < data.Length; i++) { Console.WriteLine("Found Notaion 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"); } }
private static void ExportKeyPair( Stream secretOut, Stream publicOut, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passPhrase, bool armor) { if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.Now, identity, SymmetricKeyAlgorithmTag.Cast5, passPhrase, null, null, new SecureRandom() // ,"BC" ); secretKey.Encode(secretOut); secretOut.Close(); if (armor) { publicOut = new ArmoredOutputStream(publicOut); } PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); }
static Stream Encrypt (PgpEncryptedDataGenerator encrypter, Stream content) { var memory = new MemoryBlockStream (); using (var armored = new ArmoredOutputStream (memory)) { using (var compressed = Compress (content)) { using (var encrypted = encrypter.Open (armored, compressed.Length)) { compressed.CopyTo (encrypted, 4096); encrypted.Flush (); } } armored.Flush (); } memory.Position = 0; return memory; }
/// <summary> /// Cryptographically signs the content. /// </summary> /// <remarks> /// Cryptographically signs the content using the specified signer and digest algorithm. /// </remarks> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="signer"/> cannot be used for signing. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The <paramref name="digestAlgo"/> was out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The <paramref name="digestAlgo"/> is not supported. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public ApplicationPgpSignature Sign (PgpSecretKey signer, DigestAlgorithm digestAlgo, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (!signer.IsSigningKey) throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer"); if (content == null) throw new ArgumentNullException ("content"); var hashAlgorithm = GetHashAlgorithm (digestAlgo); var memory = new MemoryBlockStream (); using (var armored = new ArmoredOutputStream (memory)) { var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib); using (var compressed = compresser.Open (armored)) { var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm); var buf = new byte[4096]; int nread; signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer)); while ((nread = content.Read (buf, 0, buf.Length)) > 0) signatureGenerator.Update (buf, 0, nread); var signature = signatureGenerator.Generate (); signature.Encode (compressed); compressed.Flush (); } armored.Flush (); } memory.Position = 0; return new ApplicationPgpSignature (memory); }
/// <summary> /// Sign data using key /// </summary> /// <param name="data">Data to sign</param> /// <param name="key">Email address of key</param> /// <returns>Returns ascii armored signature</returns> public string Sign(byte[] data, string key, Dictionary<string, string> headers) { Context = new CryptoContext(Context); var senderKey = GetSecretKeyForSigning(key); if (senderKey == null) throw new SecretKeyNotFoundException("Error, unable to locate signing key \"" + key + "\"."); var compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var literalData = new PgpLiteralDataGenerator(); // Setup signature stuff // var tag = senderKey.PublicKey.Algorithm; var signatureData = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha256); signatureData.InitSign(PgpSignature.BinaryDocument, senderKey.ExtractPrivateKey(Context.Password)); foreach (string userId in senderKey.PublicKey.GetUserIds()) { var subPacketGenerator = new PgpSignatureSubpacketGenerator(); subPacketGenerator.SetSignerUserId(false, userId); signatureData.SetHashedSubpackets(subPacketGenerator.Generate()); // Just the first one! break; } // // using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { foreach (var header in headers) armoredOut.SetHeader(header.Key, header.Value); using (var compressedOut = compressedData.Open(armoredOut)) using (var outputStream = new BcpgOutputStream(compressedOut)) { signatureData.GenerateOnePassVersion(false).Encode(outputStream); using (var literalOut = literalData.Open(outputStream, 'b', "", data.Length, DateTime.Now)) { literalOut.Write(data, 0, data.Length); signatureData.Update(data); } signatureData.Generate().Encode(outputStream); } } return ASCIIEncoding.ASCII.GetString(sout.ToArray()); } }
/// <summary> /// Encrypt string using a PGP public key /// </summary> /// <param name="plain">plain text to encrypt</param> /// <param name="armoredPublicKey">public key in ASCII "-----BEGIN PGP PUBLIC KEY BLOCK----- .. -----END PGP PUBLIC KEY BLOCK-----" format</param> /// <returns>PGP message string</returns> public static string PGPEncrypt(string plain, string armoredPublicKey) { // encode data byte[] data = Encoding.UTF8.GetBytes(plain); // create the WinAuth public key PgpPublicKey publicKey = null; using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(armoredPublicKey))) { using (Stream dis = PgpUtilities.GetDecoderStream(ms)) { PgpPublicKeyRingBundle bundle = new PgpPublicKeyRingBundle(dis); foreach (PgpPublicKeyRing keyring in bundle.GetKeyRings()) { foreach (PgpPublicKey key in keyring.GetPublicKeys()) { if (key.IsEncryptionKey == true && key.IsRevoked() == false) { publicKey = key; break; } } } } } // encrypt the data using PGP using (MemoryStream encryptedStream = new MemoryStream()) { using (ArmoredOutputStream armored = new ArmoredOutputStream(encryptedStream)) { PgpEncryptedDataGenerator pedg = new PgpEncryptedDataGenerator(Org.BouncyCastle.Bcpg.SymmetricKeyAlgorithmTag.Cast5, true, new Org.BouncyCastle.Security.SecureRandom()); pedg.AddMethod(publicKey); using (Stream pedgStream = pedg.Open(armored, new byte[4096])) { PgpCompressedDataGenerator pcdg = new PgpCompressedDataGenerator(Org.BouncyCastle.Bcpg.CompressionAlgorithmTag.Zip); using (Stream pcdgStream = pcdg.Open(pedgStream)) { PgpLiteralDataGenerator pldg = new PgpLiteralDataGenerator(); using (Stream encrypter = pldg.Open(pcdgStream, PgpLiteralData.Binary, "", (long)data.Length, DateTime.Now)) { encrypter.Write(data, 0, data.Length); } } } } return Encoding.ASCII.GetString(encryptedStream.ToArray()); } }
/// <summary> /// Encrypts a file on disk. /// </summary> /// <param name="inputFile"></param> /// <param name="outputFile"></param> /// <param name="publicKeyStream">The public key to use for encryption.</param> /// <param name="withIntegrityCheck"></param> /// <param name="armor">ASCII armor (should be false unless text is needed for email or compatability).</param> /// <param name="compress">Use Zip compression</param> public static void EncryptAes256(string inputFile, string outputFile, Stream publicKeyStream, bool withIntegrityCheck, bool armor, bool compress, bool overwrite) { if (string.IsNullOrEmpty(inputFile)) { throw new ArgumentException("inputFile"); } if (!File.Exists(inputFile)) { throw new FileNotFoundException(string.Format("The file '{0}' could not be found.", inputFile)); } if (string.IsNullOrEmpty(outputFile)) { throw new ArgumentException("outputFile"); } if (File.Exists(outputFile) && !overwrite) { throw new InvalidOperationException(string.Format("The file '{0}' already exists and 'overwrite' is false.", inputFile)); } if (publicKeyStream == null) { throw new ArgumentNullException("publicKeyStream"); } 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(); var compressionAlg = CompressionAlgorithmTag.Uncompressed; if (compress) { compressionAlg = CompressionAlgorithmTag.Zip; } byte[] processedData; var fiOut = new FileInfo(outputFile); var fiIn = new FileInfo(inputFile); var inputData = File.ReadAllBytes(inputFile); processedData = Compress(inputData, fiIn.Name, compressionAlg); PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, withIntegrityCheck, new SecureRandom()); dataGenerator.AddMethod(pubKey); using (Stream outputStream = File.Create(outputFile)) { if (armor) { using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream)) { StreamHelper.WriteStream(dataGenerator.Open(armoredStream, processedData.Length), ref processedData); } } else { StreamHelper.WriteStream(dataGenerator.Open(outputStream, processedData.Length), ref processedData); } } } }
public static void SignAndEncryptFile(string actualFileName, string embeddedFileName, Stream privateKeyStream, string passPhrase, Stream publicKeyStream, bool armor, bool withIntegrityCheck, Stream outputStream) { const int BUFFER_SIZE = 1 << 16; // should always be power of 2 if (armor) outputStream = new ArmoredOutputStream(outputStream); PgpPublicKey pubKey = ReadPublicKey(publicKeyStream); // Init encrypted data generator PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); encryptedDataGenerator.AddMethod(pubKey); Stream encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]); // Init compression PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); Stream compressedOut = compressedDataGenerator.Open(encryptedOut); // Init signature PgpSecretKeyRingBundle pgpSecBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); var pgpSecKey = ReadSecretKey(pgpSecBundle); if (pgpSecKey == null) throw new ArgumentException(pubKey.KeyId.ToString("X") + " could not be found in specified key ring bundle.", "keyId"); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(passPhrase.ToCharArray()); PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); var userIds = pgpSecKey.PublicKey.GetUserIds(); string userId = null; foreach (string value in userIds) { // Just the first one! userId = value; break; } if (string.IsNullOrEmpty(userId)) { throw new ArgumentException(string.Format("Can't find userId in signing key. KeyId '{0}'.", pubKey.KeyId.ToString("X"))); } PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(spGen.Generate()); signatureGenerator.GenerateOnePassVersion(false).Encode(compressedOut); // Create the Literal Data generator output stream PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); // NOTE: Commented this out because it uses FileInfo to get stats on files and won't work properly FileInfo embeddedFile = new FileInfo(embeddedFileName); FileInfo actualFile = new FileInfo(actualFileName); if (!actualFile.Exists) { throw new FileNotFoundException(actualFile.FullName); } // TODO: Use lastwritetime from source file Stream literalOut = literalDataGenerator.Open(compressedOut, PgpLiteralData.Binary, embeddedFile.Name, actualFile.LastWriteTime, new byte[BUFFER_SIZE]); // Open the input file FileStream inputStream = actualFile.OpenRead(); byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buf, 0, buf.Length)) > 0) { literalOut.Write(buf, 0, len); signatureGenerator.Update(buf, 0, len); } literalOut.Close(); literalDataGenerator.Close(); signatureGenerator.Generate().Encode(compressedOut); compressedOut.Close(); compressedDataGenerator.Close(); encryptedOut.Close(); encryptedDataGenerator.Close(); inputStream.Close(); if (armor) outputStream.Close(); }
private static byte[] SignPublicKey( IPgpSecretKey secretKey, string secretKeyPass, IPgpPublicKey keyToBeSigned, string notationName, string notationValue, bool armor) { Stream os = new MemoryStream(); if (armor) { os = new ArmoredOutputStream(os); } IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey( secretKeyPass.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator( secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.DirectKey, pgpPrivKey); BcpgOutputStream bOut = new BcpgOutputStream(os); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); bool isHumanReadable = true; spGen.SetNotationData(true, isHumanReadable, notationName, notationValue); PgpSignatureSubpacketVector packetVector = spGen.Generate(); sGen.SetHashedSubpackets(packetVector); bOut.Flush(); if (armor) { os.Close(); } return PgpPublicKey.AddCertification(keyToBeSigned, sGen.Generate()).GetEncoded(); }
/// <summary> /// Signs then encrypts data using key and list of recipients. /// </summary> /// <param name="data">Data to encrypt</param> /// <param name="key">Signing key</param> /// <param name="recipients">List of keys to encrypt to</param> /// <returns>Returns ascii armored signed/encrypted data</returns> protected string SignAndEncrypt(byte[] data, string key, IList<string> recipients, Dictionary<string, string> headers, bool isBinary) { Context = new CryptoContext(Context); var senderKey = GetSecretKeyForEncryption(key); if (senderKey == null) throw new SecretKeyNotFoundException("Error, Unable to locate sender encryption key \"" + key + "\"."); var senderSignKey = GetSecretKeyForSigning(key); if (senderSignKey == null) throw new SecretKeyNotFoundException("Error, Unable to locate sender signing key \"" + key + "\"."); var compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib); var literalData = new PgpLiteralDataGenerator(); var cryptData = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom()); foreach (var recipient in recipients) { var recipientKey = GetPublicKeyForEncryption(recipient); if (recipientKey == null) throw new PublicKeyNotFoundException("Error, unable to find recipient key \"" + recipient + "\"."); cryptData.AddMethod(recipientKey); } // Setup signature stuff // var signatureData = new PgpSignatureGenerator( senderSignKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); signatureData.InitSign( isBinary ? PgpSignature.BinaryDocument : PgpSignature.CanonicalTextDocument, senderSignKey.ExtractPrivateKey(Context.Password)); foreach (string userId in senderKey.PublicKey.GetUserIds()) { var subPacketGenerator = new PgpSignatureSubpacketGenerator(); subPacketGenerator.SetSignerUserId(false, userId); signatureData.SetHashedSubpackets(subPacketGenerator.Generate()); // Just the first one! break; } // // using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { foreach (var header in headers) armoredOut.SetHeader(header.Key, header.Value); using (var clearOut = new MemoryStream()) { using (var compressedOut = compressedData.Open(clearOut)) { signatureData.GenerateOnePassVersion(false).Encode(compressedOut); using (var literalOut = literalData.Open( compressedOut, isBinary ? PgpLiteralData.Binary : PgpLiteralData.Text, "", data.Length, DateTime.UtcNow)) { literalOut.Write(data, 0, data.Length); signatureData.Update(data, 0, data.Length); } signatureData.Generate().Encode(compressedOut); } var clearData = clearOut.ToArray(); using (var encryptOut = cryptData.Open(armoredOut, clearData.Length)) { encryptOut.Write(clearData, 0, clearData.Length); } } } return ASCIIEncoding.ASCII.GetString(sout.ToArray()); } }
/// <summary> /// Sign data using key /// </summary> /// <param name="data">Data to sign</param> /// <param name="key">Email address of key</param> /// <returns>Returns ascii armored signature</returns> public string SignClear(string data, string key, Encoding encoding, Dictionary<string, string> headers) { Context = new CryptoContext(Context); var senderKey = GetSecretKeyForSigning(key); if (senderKey == null) throw new SecretKeyNotFoundException("Error, unable to locate signing key \"" + key + "\"."); // Setup signature stuff // var signatureData = new PgpSignatureGenerator(senderKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); signatureData.InitSign(PgpSignature.CanonicalTextDocument, senderKey.ExtractPrivateKey(Context.Password)); foreach (string userId in senderKey.PublicKey.GetUserIds()) { var subPacketGenerator = new PgpSignatureSubpacketGenerator(); subPacketGenerator.SetSignerUserId(false, userId); signatureData.SetHashedSubpackets(subPacketGenerator.Generate()); // Just the first one! break; } // // using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { foreach (var header in headers) armoredOut.SetHeader(header.Key, header.Value); armoredOut.BeginClearText(HashAlgorithmTag.Sha1); // Remove any extra trailing whitespace. // this should not include \r or \n. data = data.TrimEnd(null); using (var stringReader = new StringReader(data)) { do { var line = stringReader.ReadLine(); if (line == null) break; // Lines must have all white space removed line = line.TrimEnd(null); line = line.TrimEnd(new char[] {' ', '\t', '\r', '\n'}); line += "\r\n"; signatureData.Update(encoding.GetBytes(line)); armoredOut.Write(encoding.GetBytes(line)); } while (true); } // Write extra line before signature block. armoredOut.Write(encoding.GetBytes("\r\n")); armoredOut.EndClearText(); using (var outputStream = new BcpgOutputStream(armoredOut)) { signatureData.Generate().Encode(outputStream); } } return encoding.GetString(sout.ToArray()); } }
public string PublicKey(string email, Dictionary<string, string> headers) { Context = new CryptoContext(Context); var publicKeyRing = GetPublicKeyRing(email); using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { publicKeyRing.Encode(armoredOut); } return ASCIIEncoding.ASCII.GetString(sout.ToArray()); } }
/// <summary> /// Encrypt and sign the file pointed to by unencryptedFileInfo. /// </summary> /// <param name="inputFile">The input file.</param> /// <param name="outputFile">The output file.</param> /// <param name="publicKeyFile">The public key file.</param> /// <param name="privateKeyFile">The private key file.</param> /// <param name="passPhrase">The pass phrase.</param> /// <param name="armor">if set to <c>true</c> [armor].</param> /// <exception cref="System.IO.FileNotFoundException"> /// </exception> /// <exception cref="System.ArgumentNullException">Invalid Pass Phrase. /// or /// Encryption Key not found.</exception> public static void EncryptAndSign(string inputFile, string outputFile, string publicKeyFile, string privateKeyFile, string passPhrase, bool armor) { PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(publicKeyFile, privateKeyFile, passPhrase); if (!File.Exists(inputFile)) throw new FileNotFoundException(String.Format("Input file does not exist.: [{0}]", inputFile)); if (!File.Exists(publicKeyFile)) throw new FileNotFoundException(String.Format("Public Key file does not exist: [{0}]", publicKeyFile)); if (!File.Exists(privateKeyFile)) throw new FileNotFoundException(String.Format("Private Key file does not exist: [{0}]", privateKeyFile)); if (String.IsNullOrEmpty(passPhrase)) throw new ArgumentNullException("Invalid Pass Phrase."); if (encryptionKeys == null) throw new ArgumentNullException("Encryption Key not found."); using (Stream outputStream = File.Create(outputFile)) { if (armor) using (ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream)) { OutputEncrypted(inputFile, armoredOutputStream, encryptionKeys); } else OutputEncrypted(inputFile, outputStream, encryptionKeys); } }
/// <summary> /// Build a PGP key pair /// </summary> /// <param name="bits">number of bits in key, e.g. 2048</param> /// <param name="identifier">key identifier, e.g. "Your Name <*****@*****.**>" </param> /// <param name="password">key password or null</param> /// <param name="privateKey">returned ascii private key</param> /// <param name="publicKey">returned ascii public key</param> public static void PGPGenerateKey(int bits, string identifier, string password, out string privateKey, out string publicKey) { // generate a new RSA keypair RsaKeyPairGenerator gen = new RsaKeyPairGenerator(); gen.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x101), new Org.BouncyCastle.Security.SecureRandom(), bits, 80)); AsymmetricCipherKeyPair pair = gen.GenerateKeyPair(); // create PGP subpacket PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator(); hashedGen.SetKeyFlags(true, PgpKeyFlags.CanCertify | PgpKeyFlags.CanSign | PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage); hashedGen.SetPreferredCompressionAlgorithms(false, new int[] { (int)CompressionAlgorithmTag.Zip }); hashedGen.SetPreferredHashAlgorithms(false, new int[] { (int)HashAlgorithmTag.Sha1 }); hashedGen.SetPreferredSymmetricAlgorithms(false, new int[] { (int)SymmetricKeyAlgorithmTag.Cast5 }); PgpSignatureSubpacketVector sv = hashedGen.Generate(); PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator(); // create the PGP key PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, pair.Public, pair.Private, DateTime.Now, identifier, SymmetricKeyAlgorithmTag.Cast5, (password != null ? password.ToCharArray() : null), hashedGen.Generate(), unhashedGen.Generate(), new Org.BouncyCastle.Security.SecureRandom()); // extract the keys using (MemoryStream ms = new MemoryStream()) { using (ArmoredOutputStream ars = new ArmoredOutputStream(ms)) { secretKey.Encode(ars); } privateKey = Encoding.ASCII.GetString(ms.ToArray()); } using (MemoryStream ms = new MemoryStream()) { using (ArmoredOutputStream ars = new ArmoredOutputStream(ms)) { secretKey.PublicKey.Encode(ars); } publicKey = Encoding.ASCII.GetString(ms.ToArray()); } }
public override void WriteByte(byte b) { if (this.clearText) { this.outStream.WriteByte(b); if (this.newLine) { if (b != 10 || this.lastb != 13) { this.newLine = false; } if (b == 45) { this.outStream.WriteByte(32); this.outStream.WriteByte(45); } } if (b == 13 || (b == 10 && this.lastb != 13)) { this.newLine = true; } this.lastb = (int)b; return; } if (this.start) { bool flag = (b & 64) != 0; int num; if (flag) { num = (int)(b & 63); } else { num = (b & 63) >> 2; } switch (num) { case 2: this.type = "SIGNATURE"; goto IL_EF; case 5: this.type = "PRIVATE KEY BLOCK"; goto IL_EF; case 6: this.type = "PUBLIC KEY BLOCK"; goto IL_EF; } this.type = "MESSAGE"; IL_EF: this.DoWrite(ArmoredOutputStream.headerStart + this.type + ArmoredOutputStream.headerTail + ArmoredOutputStream.nl); this.WriteHeaderEntry("Version", (string)this.headers["Version"]); foreach (DictionaryEntry dictionaryEntry in this.headers) { string text = (string)dictionaryEntry.Key; if (text != "Version") { string v = (string)dictionaryEntry.Value; this.WriteHeaderEntry(text, v); } } this.DoWrite(ArmoredOutputStream.nl); this.start = false; } if (this.bufPtr == 3) { ArmoredOutputStream.Encode(this.outStream, this.buf, this.bufPtr); this.bufPtr = 0; if ((++this.chunkCount & 15) == 0) { this.DoWrite(ArmoredOutputStream.nl); } } this.crc.Update((int)b); this.buf[this.bufPtr++] = (int)(b & 255); }
/// <summary> /// Exports the specified public keys. /// </summary> /// <remarks> /// Exports the specified public keys. /// </remarks> /// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported public keys.</returns> /// <param name="keys">The keys.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="keys"/> is <c>null</c>. /// </exception> public MimePart Export (PgpPublicKeyRingBundle keys) { if (keys == null) throw new ArgumentNullException ("keys"); var content = new MemoryBlockStream (); using (var armored = new ArmoredOutputStream (content)) { keys.Encode (armored); armored.Flush (); } content.Position = 0; return new MimePart ("application", "pgp-keys") { ContentDisposition = new ContentDisposition ("attachment"), ContentObject = new ContentObject (content) }; }
/// <summary> /// Encrypt data to a set of recipients /// </summary> /// <param name="data">Data to encrypt</param> /// <param name="recipients">List of email addresses</param> /// <param name="recipients">Headers to add to ascii armor</param> /// <returns>Returns ascii armored encrypted data</returns> public string Encrypt(byte[] data, IList<string> recipients, Dictionary<string, string> headers) { Context = new CryptoContext(Context); var compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var literalData = new PgpLiteralDataGenerator(); var cryptData = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom()); foreach (var recipient in recipients) { var recipientKey = GetPublicKeyForEncryption(recipient); if (recipientKey == null) throw new PublicKeyNotFoundException("Error, unable to find recipient key \"" + recipient + "\"."); cryptData.AddMethod(recipientKey); } using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { foreach(var header in headers) armoredOut.SetHeader(header.Key, header.Value); using (var clearOut = new MemoryStream()) { using (var compressedOut = compressedData.Open(clearOut)) using (var literalOut = literalData.Open( compressedOut, PgpLiteralData.Binary, "email", data.Length, DateTime.UtcNow)) { literalOut.Write(data, 0, data.Length); } var clearData = clearOut.ToArray(); using (var encryptOut = cryptData.Open(armoredOut, clearData.Length)) { encryptOut.Write(clearData, 0, clearData.Length); } } } return ASCIIEncoding.ASCII.GetString(sout.ToArray()); } }
//public static void EncryptPgpFile(string inputFile, string outputFile) //{ // // use armor: yes, use integrity check? yes? // EncryptPgpFile(inputFile, outputFile, PublicKeyPath, true, true); //} 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)) { IoHelper.WriteStream(dataGenerator.Open(armoredStream, dataBytes.Length), ref dataBytes); } } else { IoHelper.WriteStream(dataGenerator.Open(outputStream, dataBytes.Length), ref dataBytes); } } } } }
public string PublicKey(string email, Dictionary<string, string> headers) { Context = new CryptoContext(Context); var publicKey = GetPublicKeyForEncryption(email); var sigKey = GetSecretKeyForSigning(email); var literalData = new PgpLiteralDataGenerator(); var data = publicKey.GetEncoded(); using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { foreach (var header in headers) armoredOut.SetHeader(header.Key, header.Value); //using (var literalOut = literalData.Open( // armoredOut, // PgpLiteralData.Binary, // "email", // data.Length, // DateTime.UtcNow)) //{ // literalOut.Write(data, 0, data.Length); //} armoredOut.Write(data); } return ASCIIEncoding.ASCII.GetString(sout.ToArray()); } }
/// <summary> /// Encrypts data using a PGP public key and returns a byte array. /// </summary> /// <param name="inputData">data to encrypt</param> /// <param name="outputName">Reference file name used for compression file name (not a fully qualified path)</param> /// <param name="publicKeyStream">The public key to use for encryption.</param> /// <param name="withIntegrityCheck"></param> /// <param name="armor">ASCII armor (should be false unless text is needed for email or compatability).</param> /// <param name="compress">Use Zip compression</param> /// <returns>The encrypted byte array</returns> public static byte[] EncryptAes256(byte[] inputData, string outputName, Stream publicKeyStream, bool withIntegrityCheck, bool armor, bool compress) { var pubKey = ReadPublicKey(publicKeyStream); var compressionAlg = CompressionAlgorithmTag.Uncompressed; if (compress) { compressionAlg = CompressionAlgorithmTag.Zip; } byte[] processedData = Compress(inputData, outputName, compressionAlg); MemoryStream bOut = new MemoryStream(); Stream output = bOut; if (armor) { output = new ArmoredOutputStream(output); } PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, withIntegrityCheck, new SecureRandom()); encGen.AddMethod(pubKey); Stream encOut = encGen.Open(output, processedData.Length); encOut.Write(processedData, 0, processedData.Length); encOut.Close(); if (armor) { output.Close(); } return bOut.ToArray(); }
static void GenerateKey(string pubring, string secring, string nameReal, string nameEmail, DateTime expireDate, string passphrase, bool use4096) { if (string.IsNullOrEmpty(pubring)) { Console.WriteLine("ERROR: 'pubring' is not a valid file path."); ReadKeyOrReturnAfterLapse(); return; } try { var fi = new FileInfo(pubring); if (fi.Exists) { Console.WriteLine("ERROR: 'pubring' file already exists."); ReadKeyOrReturnAfterLapse(); return; } if (!fi.Directory.Exists) { fi.Directory.Create(); } } catch { } if (string.IsNullOrEmpty(secring)) { Console.WriteLine("ERROR: 'secring' is not a valid file path."); ReadKeyOrReturnAfterLapse(); return; } try { var fi = new FileInfo(secring); if (fi.Exists) { Console.WriteLine("ERROR: 'secring' file already exists."); ReadKeyOrReturnAfterLapse(); return; } if (!fi.Directory.Exists) { fi.Directory.Create(); } } catch { } if (string.IsNullOrEmpty(nameReal)) { Console.WriteLine("ERROR: 'nameReal' is not valid."); ReadKeyOrReturnAfterLapse(); return; } if (string.IsNullOrEmpty(nameEmail) || !nameEmail.IsValidEmailAddress()) { Console.WriteLine("ERROR: 'nameEmail' is not valid."); ReadKeyOrReturnAfterLapse(); return; } if (!string.IsNullOrWhiteSpace(passphrase)) { if (passphrase.Length < 7) { Console.WriteLine("ERROR: 'passphrase' must be at least 7 characters long."); ReadKeyOrReturnAfterLapse(); return; } if (!passphrase.Any(c => char.IsDigit(c))) { Console.WriteLine("ERROR: 'passphrase' must contain at least 1 number."); ReadKeyOrReturnAfterLapse(); return; } } //string pubring, string secring, string nameReal, string nameEmail, DateTime expireDate, string passphrase, bool use4096 Console.WriteLine(); Console.WriteLine("Key parameters:"); Console.WriteLine(DIVIDER); Console.WriteLine("pubring: " + pubring); Console.WriteLine("secring: " + secring); Console.WriteLine("name-real: " + nameReal); Console.WriteLine("name-email: " + nameEmail); Console.WriteLine("expire-date: " + expireDate.ToString()); if (use4096) { Console.WriteLine("key-length: 4096"); } else { Console.WriteLine("key-length: 2048"); } if (string.IsNullOrWhiteSpace(passphrase)) { Console.WriteLine("WARNING * * * * * * * *"); Console.WriteLine("The private key does not have a passphrase."); Console.WriteLine("It is strongly recommended that you use a passphrase with your private key."); Console.WriteLine("* * * * * * * * * * * *"); } Console.WriteLine(DIVIDER); // check to execute if (!IsYforContinue()) { Console.WriteLine(); Console.WriteLine("Canceling key generation."); Console.WriteLine(); return; } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(DIVIDER); Console.WriteLine("Please wait while we generate your keys. Generating secure keys takes time..."); Console.WriteLine(DIVIDER); Console.WriteLine(); try { PgpKeyRingGenerator krgen = PgpKeyRingHelper.CreateKeyRingGenerator(nameReal + " <" + nameEmail + ">", expireDate, passphrase, use4096); // Generate public key ring, dump to file. PgpPublicKeyRing pkr = krgen.GeneratePublicKeyRing(); bool armorPublic = true; if (armorPublic) { using (ArmoredOutputStream pubout = new ArmoredOutputStream(new FileStream(pubring, System.IO.FileMode.Create))) { pkr.Encode(pubout); pubout.Close(); } } else { using (BufferedStream pubout = new BufferedStream(new FileStream(pubring, System.IO.FileMode.Create))) { pkr.Encode(pubout); pubout.Close(); } } bool armorPrivate = false; // Generate private key, dump to file. PgpSecretKeyRing skr = krgen.GenerateSecretKeyRing(); if (armorPrivate) { using (ArmoredOutputStream secout = new ArmoredOutputStream(new FileStream(secring, System.IO.FileMode.Create))) { skr.Encode(secout); secout.Close(); } } else { using (BufferedStream secout = new BufferedStream(new FileStream(secring, System.IO.FileMode.Create))) { skr.Encode(secout); secout.Close(); } } Console.WriteLine(); Console.WriteLine("PGP key pairs successfully generated."); Console.WriteLine(); ReadKeyOrReturnAfterLapse(); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Exception: " + ex.GetType().Name + " - " + ex.Message); Console.WriteLine(); ReadKeyOrReturnAfterLapse(); } }
public string encryptPgpString(string inputString, long receiverId, bool armor, bool withIntegrityCheck) { PgpPublicKey pubKey = ReadPublicKey(receiverId); using (MemoryStream outputBytes = getMemoryStreamFromString(inputString)) { PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, withIntegrityCheck, new SecureRandom()); dataGenerator.AddMethod(pubKey); byte[] dataBytes = outputBytes.ToArray(); using ( Stream outputStream = new MemoryStream() ) { if (armor) { using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream)) { Stream encryptedStream = writeStream(dataGenerator.Open(armoredStream, dataBytes.Length), ref dataBytes); string sOutputString = getStringFromStream (encryptedStream); return sOutputString; } } else { Stream encryptedStream = writeStream(dataGenerator.Open(outputStream, dataBytes.Length), ref dataBytes); string sOutputString = getStringFromStream (encryptedStream); return sOutputString; } } } }
/// <summary> /// Cryptographically signs and encrypts the specified content for the specified recipients. /// </summary> /// <remarks> /// Cryptographically signs and encrypts the specified content for the specified recipients. /// </remarks> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the encrypted data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="cipherAlgo">The encryption algorithm.</param> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="signer"/> cannot be used for signing.</para> /// <para>-or-</para> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// The specified encryption algorithm is not supported. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimePart SignAndEncrypt (PgpSecretKey signer, DigestAlgorithm digestAlgo, EncryptionAlgorithm cipherAlgo, IEnumerable<PgpPublicKey> recipients, Stream content) { // TODO: document the exceptions that can be thrown by BouncyCastle if (signer == null) throw new ArgumentNullException ("signer"); if (!signer.IsSigningKey) throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); var encrypter = new PgpEncryptedDataGenerator (GetSymmetricKeyAlgorithm (cipherAlgo), true); var hashAlgorithm = GetHashAlgorithm (digestAlgo); int count = 0; foreach (var recipient in recipients) { if (!recipient.IsEncryptionKey) throw new ArgumentException ("One or more of the recipient keys cannot be used for encrypting.", "recipients"); encrypter.AddMethod (recipient); count++; } if (count == 0) throw new ArgumentException ("No recipients specified.", "recipients"); var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib); using (var compressed = new MemoryBlockStream ()) { using (var signed = compresser.Open (compressed)) { var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm); signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer)); var subpacket = new PgpSignatureSubpacketGenerator (); foreach (string userId in signer.PublicKey.GetUserIds ()) { subpacket.SetSignerUserId (false, userId); break; } signatureGenerator.SetHashedSubpackets (subpacket.Generate ()); var onepass = signatureGenerator.GenerateOnePassVersion (false); onepass.Encode (signed); var literalGenerator = new PgpLiteralDataGenerator (); using (var literal = literalGenerator.Open (signed, 't', "mime.txt", content.Length, DateTime.Now)) { var buf = new byte[4096]; int nread; while ((nread = content.Read (buf, 0, buf.Length)) > 0) { signatureGenerator.Update (buf, 0, nread); literal.Write (buf, 0, nread); } literal.Flush (); } var signature = signatureGenerator.Generate (); signature.Encode (signed); signed.Flush (); } compressed.Position = 0; var memory = new MemoryBlockStream (); using (var armored = new ArmoredOutputStream (memory)) { using (var encrypted = encrypter.Open (armored, compressed.Length)) { compressed.CopyTo (encrypted, 4096); encrypted.Flush (); } armored.Flush (); } memory.Position = 0; return new MimePart ("application", "octet-stream") { ContentDisposition = new ContentDisposition ("attachment"), ContentObject = new ContentObject (memory) }; } }