Ejemplo n.º 1
0
 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);
             }
         }
     }));
 }
Ejemplo n.º 2
0
        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()));
        }
Ejemplo n.º 3
0
        /*.......................................................................數位簽章開始*/


        private static void SignFile(
            string fileName,     //欲作簽章的檔案名稱及位置
            Stream keyIn,        // Private key 的 File Stream
            Stream outputStream, //簽章後的檔案 File Stream
            char[] pass,         // private Key 的 password
            bool armor,          //用途不明?? 範例預設true
            bool compress        //用途不明?? 範例預設true
            )
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }
            PgpSecretKey          pgpSec     = PgpExampleUtilities.ReadSecretKey(keyIn);
            PgpPrivateKey         pgpPrivKey = pgpSec.ExtractPrivateKey(pass);
            PgpSignatureGenerator sGen       = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha256);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);
            foreach (string userId in pgpSec.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);
                sGen.SetHashedSubpackets(spGen.Generate());
                // Just the first one!
                break;
            }
            Stream cOut = outputStream;
            PgpCompressedDataGenerator cGen = null;

            if (compress)
            {
                cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
                cOut = cGen.Open(cOut);
            }
            BcpgOutputStream bOut = new BcpgOutputStream(cOut);

            sGen.GenerateOnePassVersion(false).Encode(bOut);
            FileInfo file = new FileInfo(fileName);
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream     lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);
            FileStream fIn  = file.OpenRead();
            int        ch   = 0;

            while ((ch = fIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }
            fIn.Close();
            lGen.Close();
            sGen.Generate().Encode(bOut);
            if (cGen != null)
            {
                cGen.Close();
            }
            if (armor)
            {
                outputStream.Close();
            }
        }
        private string EncryptPgpStringData(string inputFile, string publicKeyData, bool armor, bool withIntegrityCheck)
        {
            using (Stream publicKeyStream = IoHelper.GetStream(publicKeyData))
            {
                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(TempEncryptedPath))
                    {
                        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);
                        }
                    }
                    return(File.ReadAllText(TempEncryptedPath));
                }
            }
        }
Ejemplo n.º 5
0
        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);
        }
        private static void ExportKeyPair(
            Stream secretOut,
            Stream publicOut,
            IAsymmetricCipherKeyPair signingKey,
            IAsymmetricCipherKeyPair encryptionKey,
            string identity,
            char[] passPhrase,
            bool armor,
            ISecureRandom random)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

            var masterKey = new PgpKeyPair(PublicKeyAlgorithmTag.Ecdsa, signingKey, DateTime.UtcNow);
            var subKey = new PgpKeyPair(PublicKeyAlgorithmTag.Ecdh, encryptionKey, DateTime.UtcNow);
            var keyRingGenerator = new PgpKeyRingGenerator(
                PgpSignature.PositiveCertification, masterKey, identity,
                SymmetricKeyAlgorithmTag.Aes256, HashAlgorithmTag.Sha256, passPhrase, true, null, null, random);
            keyRingGenerator.AddSubKey(subKey);

            keyRingGenerator.GenerateSecretKeyRing().Encode(secretOut);

            if (armor)
            {
                secretOut.Close();
                publicOut = new ArmoredOutputStream(publicOut);
            }

            keyRingGenerator.GeneratePublicKeyRing().Encode(publicOut);
            {
                publicOut.Close();
            }
        }
Ejemplo n.º 7
0
        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());
                    }
                }
            }));
        }
Ejemplo n.º 8
0
        private static byte[] RevokePublicKey(PgpSecretKey sKey, char[] sPass, PgpPublicKey keyToSign, bool armour)
        {
            Stream os = new MemoryStream();

            if (armour)
            {
                os = new ArmoredOutputStream(os);
            }

            PgpPrivateKey         privKey = sKey.ExtractPrivateKey(sPass);
            PgpSignatureGenerator sGen    = new PgpSignatureGenerator(sKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.KeyRevocation, privKey);
            BcpgOutputStream bOut = new BcpgOutputStream(os);

            sGen.GenerateOnePassVersion(false).Encode(bOut);
            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            spGen.SetRevocable(false, true);
            DateTime baseDate = new DateTime(1970, 1, 1);
            TimeSpan tSpan    = DateTime.UtcNow - baseDate;

            spGen.SetSignatureExpirationTime(false, tSpan.Seconds);
            PgpSignatureSubpacketVector packetVector = spGen.Generate();

            sGen.SetHashedSubpackets(packetVector);
            bOut.Flush();

            if (armour)
            {
                os.Close();
            }

            return(PgpPublicKey.AddCertification(keyToSign, sGen.Generate()).GetEncoded());
        }
        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);
        }
Ejemplo n.º 10
0
        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();
                }
            }));
        }
Ejemplo n.º 11
0
        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()));
            }
        }
Ejemplo n.º 12
0
 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());
     }
 }
Ejemplo n.º 13
0
    /**
     * Encrypt the data.
     *
     * @param inputData - byte array to encrypt
     * @param passPhrase - the password returned by "ReadPublicKey"
     * @param withIntegrityCheck - check the data for errors
     * @param armor - protect the data streams
     * @return - encrypted byte array
     */
    public static byte[] Encrypt(byte[] inputData, PgpPublicKey passPhrase, bool withIntegrityCheck, bool armor)
    {
        byte[] processedData = Compress(inputData, PgpLiteralData.Console, CompressionAlgorithmTag.Uncompressed);

        MemoryStream bOut   = new MemoryStream();
        Stream       output = bOut;

        if (armor)
        {
            output = new ArmoredOutputStream(output);
        }

        PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

        encGen.AddMethod(passPhrase);

        Stream encOut = encGen.Open(output, processedData.Length);

        encOut.Write(processedData, 0, processedData.Length);
        encOut.Close();

        if (armor)
        {
            output.Close();
        }

        return(bOut.ToArray());
    }
Ejemplo n.º 14
0
        private static void ExportKeyPair(
            Stream secretOut,
            Stream publicOut,
            AsymmetricKeyParameter publicKey,
            AsymmetricKeyParameter privateKey,
            string identity,
            char[] passPhrase,
            bool armor)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

            PgpSignatureSubpacketGenerator signHashGen = new PgpSignatureSubpacketGenerator();

            signHashGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify | PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);
            signHashGen.SetPreferredSymmetricAlgorithms(false, new int[] { (int)SymmetricKeyAlgorithmTag.Aes256,
                                                                           (int)SymmetricKeyAlgorithmTag.Aes192, (int)SymmetricKeyAlgorithmTag.Aes128, (int)SymmetricKeyAlgorithmTag.Blowfish });
            signHashGen.SetPreferredHashAlgorithms(false, new int[] { (int)HashAlgorithmTag.Sha512,
                                                                      (int)HashAlgorithmTag.Sha384, (int)HashAlgorithmTag.Sha256, (int)HashAlgorithmTag.Sha224,
                                                                      (int)HashAlgorithmTag.RipeMD160, (int)HashAlgorithmTag.Tiger192 });
            signHashGen.SetPreferredCompressionAlgorithms(false, new int[] { (int)CompressionAlgorithmTag.ZLib,
                                                                             (int)CompressionAlgorithmTag.BZip2, (int)CompressionAlgorithmTag.Zip });
            signHashGen.SetTrust(false, 8, 255);

            PgpSignatureSubpacketVector signSubpktVector = signHashGen.Generate();


            PgpSecretKey secretKey = new PgpSecretKey(
                PgpSignature.PositiveCertification,
                PublicKeyAlgorithmTag.RsaGeneral,
                publicKey,
                privateKey,
                DateTime.UtcNow,
                identity,
                SymmetricKeyAlgorithmTag.Aes256,
                passPhrase,
                signSubpktVector, //null,
                null,
                new SecureRandom()
                );

            secretKey.Encode(secretOut);

            if (armor)
            {
                secretOut.Close();
                publicOut = new ArmoredOutputStream(publicOut);
            }

            PgpPublicKey key = secretKey.PublicKey;

            key.Encode(publicOut);

            if (armor)
            {
                publicOut.Close();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Export the public keyring bundle.
        /// </summary>
        /// <remarks>
        /// Exports the public keyring bundle.
        /// </remarks>
        /// <param name="keys">The public keyring bundle to export.</param>
        /// <param name="stream">The output stream.</param>
        /// <param name="armor"><c>true</c> if the output should be armored; otherwise, <c>false</c>.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="keys"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public void Export(PgpPublicKeyRingBundle keys, Stream stream, bool armor)
        {
            if (keys == null)
            {
                throw new ArgumentNullException(nameof(keys));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (armor)
            {
                using (var armored = new ArmoredOutputStream(stream)) {
                    armored.SetHeader("Version", null);

                    keys.Encode(armored);
                    armored.Flush();
                }
            }
            else
            {
                keys.Encode(stream);
            }
        }
        /**
         * Encrypts given {@code message}. Output is written ot the {@code encryptedMessage} output stream.
         * Message is encrypted usign symmetric algorithm, default is {@link SymmetricKeyAlgorithmTags#TRIPLE_DES}.
         *
         * @param encryptedMessage
         * @param message
         * @param armor                  if output should be armored (BASE64 encoding of binary data)
         * @throws java.io.IOException
         * @throws java.security.NoSuchProviderException
         * @throws PgpException
         */
        public void encryptMessage(Stream encryptedMessage, string message, bool armor)
        {
            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();

            // we want to generate compressed data
            MemoryStream byteOut = new MemoryStream();

            writeClearDataToByteOut(compressedDataGenerator, literalDataGenerator, Encoding.ASCII.GetBytes(message), byteOut);

            compressedDataGenerator.Close();

            MemoryStream encryptedOut = new MemoryStream();

            Stream outStream = encryptedOut;
            if (armor) {
                // output will be BASE64 encoded
                outStream = new ArmoredOutputStream(outStream);
            }

            Stream encryptedDataOut = null;
            try {
                byte[] bytes = byteOut.ToArray();
                encryptedDataOut = createEncryptedDataGenerator().Open(outStream, bytes.Length);
                encryptedDataOut.Write(bytes, 0, bytes.Length);  // obtain the actual bytes from the compressed stream
            } finally {
                if (encryptedDataOut != null) {
                    encryptedDataOut.Close();
                }
                outStream.Close();
            }

            var encData = encryptedOut.ToArray();
            encryptedMessage.Write(encData, 0, encData.Length);
        }
Ejemplo n.º 17
0
Archivo: Key.cs Proyecto: AmnBAN/AmnRo
        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();
        }
Ejemplo n.º 18
0
        public void EncryptFileAndSign(string inputFilePath, string outputFilePath, string publicKeyFilePath,
                                       string privateKeyFilePath, string passPhrase, bool armor = true, bool withIntegrityCheck = true)
        {
            if (String.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException(nameof(inputFilePath));
            }
            if (String.IsNullOrEmpty(outputFilePath))
            {
                throw new ArgumentException(nameof(outputFilePath));
            }
            if (String.IsNullOrEmpty(publicKeyFilePath))
            {
                throw new ArgumentException(nameof(publicKeyFilePath));
            }
            if (String.IsNullOrEmpty(privateKeyFilePath))
            {
                throw new ArgumentException(nameof(privateKeyFilePath));
            }
            if (passPhrase == null)
            {
                passPhrase = String.Empty;
            }

            if (!File.Exists(inputFilePath))
            {
                throw new FileNotFoundException(String.Format("Input file [{0}] does not exist.", inputFilePath));
            }
            if (!File.Exists(publicKeyFilePath))
            {
                throw new FileNotFoundException(String.Format("Public Key file [{0}] does not exist.", publicKeyFilePath));
            }
            if (!File.Exists(privateKeyFilePath))
            {
                throw new FileNotFoundException(String.Format("Private Key file [{0}] does not exist.", privateKeyFilePath));
            }

            ChoPGPEncryptionKeys encryptionKeys = new ChoPGPEncryptionKeys(publicKeyFilePath, privateKeyFilePath, passPhrase);

            if (encryptionKeys == null)
            {
                throw new ArgumentNullException("Encryption Key not found.");
            }

            using (Stream outputStream = File.Create(outputFilePath))
            {
                if (armor)
                {
                    using (ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream))
                    {
                        OutputEncrypted(inputFilePath, armoredOutputStream, encryptionKeys, withIntegrityCheck);
                    }
                }
                else
                {
                    OutputEncrypted(inputFilePath, outputStream, encryptionKeys, withIntegrityCheck);
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// PGP Encrypt the file.
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputFilePath"></param>
        /// <param name="publicKeyFilePath"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        public void EncryptFileWithStreamKey(string inputFilePath, string outputFilePath, Stream publicKeyStream, bool armor = true, bool withIntegrityCheck = true)
        {
            if (string.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException("inputFilePath");
            }
            if (string.IsNullOrEmpty(outputFilePath))
            {
                throw new ArgumentException("inputFilePath");
            }

            if (!File.Exists(inputFilePath))
            {
                throw new FileNotFoundException(string.Format("Input file [{0}] does not exist.", inputFilePath));
            }

            using (Stream pkStream = publicKeyStream)
            {
                using (MemoryStream @out = new MemoryStream())
                {
                    if (CompressionAlgorithm != CompressionAlgorithm.Uncompressed)
                    {
                        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator((CompressionAlgorithmTag)(int)CompressionAlgorithm);
                        PgpUtilities.WriteFileToLiteralData(comData.Open(@out), FileTypeToChar(), new FileInfo(inputFilePath));
                        comData.Close();
                    }
                    else
                    {
                        PgpUtilities.WriteFileToLiteralData(@out, FileTypeToChar(), new FileInfo(inputFilePath));
                    }

                    PgpEncryptedDataGenerator pk = new PgpEncryptedDataGenerator((SymmetricKeyAlgorithmTag)(int)SymmetricKeyAlgorithm, withIntegrityCheck, new SecureRandom());
                    pk.AddMethod(PGPKeyHelper.ReadPublicKey(pkStream));

                    byte[] bytes = @out.ToArray();

                    using (Stream outStream = File.Create(outputFilePath))
                    {
                        if (armor)
                        {
                            using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outStream))
                            {
                                using (Stream armoredOutStream = pk.Open(armoredStream, bytes.Length))
                                {
                                    armoredOutStream.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                        else
                        {
                            using (Stream plainStream = pk.Open(outStream, bytes.Length))
                            {
                                plainStream.Write(bytes, 0, bytes.Length);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        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.WriteLine(e);

                Exception underlyingException = e.InnerException;

                if (underlyingException != null)
                {
                    Console.WriteLine(underlyingException.Message);

                    Console.WriteLine(underlyingException.StackTrace);
                }
            }
        }
Ejemplo n.º 21
0
        /// <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()));
            }
        }
Ejemplo n.º 22
0
        public String EncryptKeycode(String publicKeyStr, String unencryptedKeycode)
        {
            byte[] unencryptedByteArray = System.Text.Encoding.ASCII.GetBytes(unencryptedKeycode);
            byte[] decodedPublicKey     = System.Text.Encoding.ASCII.GetBytes(publicKeyStr);

            PgpPublicKey key = null;

            Stream decodedStream            = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPublicKey));
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(decodedStream);

            foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings())
            {
                foreach (PgpPublicKey publicKey in pgpPub.GetPublicKeys())
                {
                    if (publicKey.IsEncryptionKey)
                    {
                        key = publicKey;
                        break;
                    }
                }
            }

            if (key == null)
            {
                throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring.");
            }

            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true);

            cPk.AddMethod(key);

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

            // Write the data to a literal
            MemoryStream bOut;

            using (bOut = new MemoryStream())
            {
                using (Stream pOut = lData.Open(bOut, PgpLiteralData.Binary, PgpLiteralData.Console, unencryptedByteArray.Length, DateTime.Now))
                {
                    pOut.Write(unencryptedByteArray, 0, unencryptedByteArray.Length);
                }
            }
            lData.Close();

            byte[] bytes = bOut.ToArray();

            MemoryStream encOut = new MemoryStream();

            using (ArmoredOutputStream armoredOut = new ArmoredOutputStream(encOut))
            {
                using (Stream cOut = cPk.Open(armoredOut, bytes.Length))
                {
                    cOut.Write(bytes, 0, bytes.Length);
                }
            }

            return(System.Text.Encoding.Default.GetString(encOut.ToArray()));
        }
Ejemplo n.º 23
0
 /// <summary>
 /// PGP-encrypt all data from source to destination stream in ASCII-armored format
 /// </summary>
 /// <param name="publickeysource">Input stream containing public keyring bundle</param>
 /// <param name="publickeyuserid">UserID of key to be used within keyring bundle (if null/empty, first available key in ring will be used)</param>
 /// <param name="clearinput">Input stream containing source data to be encrypted</param>
 /// <param name="encryptedoutput">Output stream to receive ASCII-armored encrypted data</param>
 /// <remarks>
 /// - Source data will be read asynchronously
 /// - Destination data will be written asynchronously
 /// </remarks>
 public static async Task Encrypt(Stream publickeysource, string publickeyuserid, Stream clearinput, Stream encryptedoutput)
 {
     // Call raw encryption function with armored output stream wrapping destination:
     using (var armor = new ArmoredOutputStream(encryptedoutput))
     {
         await EncryptRaw(publickeysource, publickeyuserid, clearinput, armor);
     }
 }
        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);
        }
Ejemplo n.º 25
0
        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) {}
            }
        }
Ejemplo n.º 26
0
        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());
        }
Ejemplo n.º 27
0
        /// <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);
                    }
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// PGP Encrypt the file.
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputFilePath"></param>
        /// <param name="publicKeyFilePath"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        public void Encrypt(Stream inputStream, Stream outputStream, Stream publicKeyStream,
                            bool armor = true, bool withIntegrityCheck = true)
        {
            if (inputStream == null)
            {
                throw new ArgumentException(nameof(inputStream));
            }
            if (outputStream == null)
            {
                throw new ArgumentException(nameof(outputStream));
            }
            if (publicKeyStream == null)
            {
                throw new ArgumentException(nameof(publicKeyStream));
            }

            Stream pkStream = publicKeyStream;

            using (MemoryStream @out = new MemoryStream())
            {
                if (CompressionAlgorithm != ChoCompressionAlgorithm.Uncompressed)
                {
                    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator((CompressionAlgorithmTag)(int)CompressionAlgorithm);
                    ChoPGPUtility.WriteStreamToLiteralData(comData.Open(@out), FileTypeToChar(), inputStream, GetFileName(inputStream));
                    comData.Close();
                }
                else
                {
                    ChoPGPUtility.WriteStreamToLiteralData(@out, FileTypeToChar(), inputStream, GetFileName(inputStream));
                }

                PgpEncryptedDataGenerator pk = new PgpEncryptedDataGenerator((SymmetricKeyAlgorithmTag)(int)SymmetricKeyAlgorithm, withIntegrityCheck, new SecureRandom());
                pk.AddMethod(ReadPublicKey(pkStream));

                byte[] bytes = @out.ToArray();

                if (armor)
                {
                    using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream))
                    {
                        using (Stream armoredOutStream = pk.Open(armoredStream, bytes.Length))
                        {
                            armoredOutStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                else
                {
                    using (Stream plainStream = pk.Open(outputStream, bytes.Length))
                    {
                        plainStream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        void EncryptFile()
        {
            try
            {
                var InStream  = InFile.OpenRead();
                var OutStream = OutFile.OpenWrite();

                PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, WithIntegrityCheck, new SecureRandom());

                foreach (var publicKey in PublicKeys)
                {
                    var encKey = ReadPublicKey(publicKey);
                    encGen.AddMethod(encKey);
                }

                MemoryStream bOut = new MemoryStream();
                if (Compress)
                {
                    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
                    WriteStreamToLiteralData(comData.Open(bOut), PgpLiteralData.Binary, InStream);
                    comData.Close();
                }
                else
                {
                    WriteStreamToLiteralData(bOut, PgpLiteralData.Binary, InStream);
                }

                byte[] bytes = bOut.ToArray();

                if (Armor)
                {
                    using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(OutStream))
                    {
                        using (Stream cOut = encGen.Open(armoredStream, bytes.Length))
                        {
                            cOut.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                else
                {
                    using (Stream cOut = encGen.Open(OutStream, bytes.Length))
                    {
                        cOut.Write(bytes, 0, bytes.Length);
                    }
                }

                OutStream.Close();
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        ///     Encrypts an input file stream given the provided Public Key File.
        /// </summary>
        /// <param name="outputFileStream">File Stream of the new encrypted output file.</param>
        /// <param name="inputFilePath">Path of existing unencrypted input file.</param>
        /// <param name="publicKey">PgpPublicKey that will be used to encrypt the file.</param>
        /// <param name="armor">Use ASCII Armor</param>
        /// <param name="withIntegrityCheck">Include Integrity Check</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        private static void EncryptFile(Stream outputFileStream, string inputFilePath, PgpPublicKey publicKey, bool armor = true, bool withIntegrityCheck = true)
        {
            // Parameter Checks
            if (String.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException("Input File Name Parameter is invalid.");
            }

            if (!File.Exists(inputFilePath))
            {
                throw new FileNotFoundException("Input File does not exist.");
            }

            if (armor)
            {
                outputFileStream = new ArmoredOutputStream(outputFileStream);
            }

            try
            {
                PgpEncryptedDataGenerator _encryptedDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

                _encryptedDataGen.AddMethod(publicKey);

                Stream _encryptedOutStream = _encryptedDataGen.Open(outputFileStream, new byte[1 << 16]);

                PgpCompressedDataGenerator _compressedDataGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

                FileInfo inputFile       = new FileInfo(inputFilePath);
                Stream   inputFileStream = File.OpenRead(inputFile.FullName);

                PgpCustomUtilities.WriteStreamToLiteralData(_compressedDataGen.Open(_encryptedOutStream), PgpLiteralData.Binary, inputFileStream, inputFile.Name);

                _compressedDataGen.Close();
                _encryptedOutStream.Dispose();
                inputFileStream.Dispose();

                if (armor)
                {
                    outputFileStream.Dispose();
                }
            }
            catch (PgpException ex)
            {
                Console.Error.WriteLine(ex);

                Exception underlyingException = ex.InnerException;
                if (underlyingException != null)
                {
                    Console.Error.WriteLine(underlyingException.Message);
                    Console.Error.WriteLine(underlyingException.StackTrace);
                }
            }
        }
Ejemplo n.º 31
0
        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);
        }
Ejemplo n.º 32
0
        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);
        }
Ejemplo n.º 33
0
		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.UtcNow,
                identity,
                SymmetricKeyAlgorithmTag.Cast5,
                passPhrase,
                null,
                null,
                new SecureRandom()
                );

            secretKey.Encode(secretOut);

			if (armor)
            {
				secretOut.Close();
				publicOut = new ArmoredOutputStream(publicOut);
            }

            PgpPublicKey key = secretKey.PublicKey;

            key.Encode(publicOut);

			if (armor)
			{
				publicOut.Close();
			}
        }
        private static void CreateSignature(
			string	fileName,
			Stream	keyIn,
			Stream	outputStream,
			char[]	pass,
			bool	armor)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            IPgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn);
            IPgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(
                pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            BcpgOutputStream bOut = new BcpgOutputStream(outputStream);

            Stream fIn = File.OpenRead(fileName);

            int ch;
            while ((ch = fIn.ReadByte()) >= 0)
            {
                sGen.Update((byte)ch);
            }

            fIn.Close();

            sGen.Generate().Encode(bOut);

            if (armor)
            {
                outputStream.Close();
            }
        }
		private static void ExportKeyPair(
            Stream					secretOut,
            Stream					publicOut,
            AsymmetricCipherKeyPair	dsaKp,
            AsymmetricCipherKeyPair	elgKp,
            string					identity,
            char[]					passPhrase,
            bool					armor)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

			PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow);
            PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow);

			PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair,
				identity, SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, new SecureRandom());

			keyRingGen.AddSubKey(elgKeyPair);

			keyRingGen.GenerateSecretKeyRing().Encode(secretOut);

			if (armor)
            {
				secretOut.Close();
				publicOut = new ArmoredOutputStream(publicOut);
            }

			keyRingGen.GeneratePublicKeyRing().Encode(publicOut);

			if (armor)
			{
				publicOut.Close();
			}
        }
Ejemplo n.º 36
0
		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();
		}
        /**
         * Generates an encapsulated signed file.
         */
        public void signMessage(Stream unsignedContent, Stream signedContent, bool armor)
        {
            if (armor) {
                // output will be BASE64 encoded
                signedContent = new ArmoredOutputStream(signedContent);
            }

            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            try {
                BcpgOutputStream bcpgSignedContentOut = new BcpgOutputStream(compressedDataGenerator.Open(signedContent));

                PgpPrivateKey pgpPrivateKey = secretKeyForSigning.ExtractPrivateKey(secretKeyPassword);
                PgpSignatureGenerator signatureGenerator = createSignatureGenerator(pgpPrivateKey);

                signatureGenerator.GenerateOnePassVersion(false).Encode(bcpgSignedContentOut);

                Stream literalDataOut = literalDataGenerator.Open(bcpgSignedContentOut, PgpLiteralData.Binary, "_CONSOLE", unsignedContent.Length, DateTime.Now);

                updateSignatureGeneratorWithInputBytes(unsignedContent, signatureGenerator, literalDataOut);
                signatureGenerator.Generate().Encode(bcpgSignedContentOut);
            } finally {
                literalDataGenerator.Close();
                compressedDataGenerator.Close();
                signedContent.Close();
            }
        }
Ejemplo n.º 38
0
        private static void EncryptFile(
            Stream	outputStream,
            string	fileName,
            char[]	passPhrase,
            bool	armor,
            bool	withIntegrityCheck)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

			try
            {
				byte[] compressedData = PgpExampleUtilities.CompressFile(fileName, CompressionAlgorithmTag.Zip);

				PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(
					SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
				encGen.AddMethod(passPhrase);

				Stream encOut = encGen.Open(outputStream, compressedData.Length);

	            encOut.Write(compressedData, 0, compressedData.Length);
				encOut.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);
                }
            }
        }
        /*
        * 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();
        }
Ejemplo n.º 40
0
        /**
        * Simple PGP encryptor between byte[].
        *
        * @param clearData  The test to be encrypted
        * @param passPhrase The pass phrase (key).  This method assumes that the
        *                   key is a simple pass phrase, and does not yet support
        *                   RSA or more sophisiticated keying.
        * @param fileName   File name. This is used in the Literal Data Packet (tag 11)
        *                   which is really inly important if the data is to be
        *                   related to a file to be recovered later.  Because this
        *                   routine does not know the source of the information, the
        *                   caller can set something here for file name use that
        *                   will be carried.  If this routine is being used to
        *                   encrypt SOAP MIME bodies, for example, use the file name from the
        *                   MIME type, if applicable. Or anything else appropriate.
        *
        * @param armor
        *
        * @return encrypted data.
        * @exception IOException
        * @exception PgpException
        */
        public static byte[] Encrypt(
            byte[]						clearData,
            char[]						passPhrase,
            string						fileName,
            SymmetricKeyAlgorithmTag	algorithm,
            bool						armor)
        {
            if (fileName == null)
            {
                fileName = PgpLiteralData.Console;
            }

			byte[] compressedData = Compress(clearData, fileName, CompressionAlgorithmTag.Zip);

			MemoryStream bOut = new MemoryStream();

			Stream output = bOut;
			if (armor)
			{
				output = new ArmoredOutputStream(output);
			}

			PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(algorithm, new SecureRandom());
            encGen.AddMethod(passPhrase);

			Stream encOut = encGen.Open(output, compressedData.Length);

			encOut.Write(compressedData, 0, compressedData.Length);
			encOut.Close();
			
			if (armor)
			{
				output.Close();
			}

			return bOut.ToArray();
        }
Ejemplo n.º 41
0
        /**
        * Generate an encapsulated signed file.
        *
        * @param fileName
        * @param keyIn
        * @param outputStream
        * @param pass
        * @param armor
        */
        private static void SignFile(
            string	fileName,
            Stream	keyIn,
            Stream	outputStream,
            char[]	pass,
            bool	armor,
			bool	compress)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            PgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn);
            PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);
            foreach (string userId in pgpSec.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);
                sGen.SetHashedSubpackets(spGen.Generate());
                // Just the first one!
                break;
            }

            Stream cOut = outputStream;
			PgpCompressedDataGenerator cGen = null;
			if (compress)
			{
				cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);

				cOut = cGen.Open(cOut);
			}

			BcpgOutputStream bOut = new BcpgOutputStream(cOut);

            sGen.GenerateOnePassVersion(false).Encode(bOut);

            FileInfo					file = new FileInfo(fileName);
            PgpLiteralDataGenerator     lGen = new PgpLiteralDataGenerator();
            Stream						lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);
            FileStream					fIn = file.OpenRead();
            int                         ch = 0;

			while ((ch = fIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte) ch);
                sGen.Update((byte)ch);
            }

			fIn.Close();
			lGen.Close();

			sGen.Generate().Encode(bOut);

			if (cGen != null)
			{
				cGen.Close();
			}

			if (armor)
			{
				outputStream.Close();
			}
        }
        private static void EncryptFile(
            Stream			outputStream,
            string			fileName,
            PgpPublicKey	encKey,
            bool			armor,
            bool			withIntegrityCheck)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            try
            {
                PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

                cPk.AddMethod(encKey);

                Stream cOut = cPk.Open(outputStream, new byte[1 << 16]);

                PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
					CompressionAlgorithmTag.Zip);

				PgpUtilities.WriteFileToLiteralData(
					comData.Open(cOut),
					PgpLiteralData.Binary,
					new FileInfo(fileName),
					new byte[1 << 16]);

				comData.Close();

				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);
                }
            }
        }
		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);
		}