Example #1
0
        /// <summary>
        /// Helper for creating a PgpSignatureGenerator from private key file and its password
        /// </summary>
        /// <param name="stream">Stream to use for signature initialization</param>
        /// <param name="input">Encryption task input</param>
        /// <returns>PgpSignatureGenerator to be used when signing a file</returns>
        internal static PgpSignatureGenerator InitPgpSignatureGenerator(Stream stream, PgpEncryptInput input)
        {
            HashAlgorithmTag hashAlgorithm = input.SigningSettings.SignatureHashAlgorithm.ConvertEnum <HashAlgorithmTag>();

            try
            {
                PgpSecretKey  secretKey  = ReadSecretKey(input.SigningSettings.PrivateKeyFile);
                PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(input.SigningSettings.PrivateKeyPassword.ToCharArray());

                var pgpSignatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, hashAlgorithm);
                pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);

                foreach (string userId in secretKey.PublicKey.GetUserIds())
                {
                    PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                    spGen.SetSignerUserId(false, userId);
                    pgpSignatureGenerator.SetHashedSubpackets(spGen.Generate());
                    // Just the first one!
                    break;
                }

                pgpSignatureGenerator.GenerateOnePassVersion(false).Encode(stream);
                return(pgpSignatureGenerator);
            }
            catch (PgpException e)
            {
                throw new Exception("Private key extraction failed, password might be incorrect", e);
            }
        }
Example #2
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();
            }
        }
Example #3
0
        private PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut)
        {
            const bool IsCritical = false;

            const bool IsNested = false;

            PublicKeyAlgorithmTag tag = m_encryptionKeys.SecretKey.PublicKey.Algorithm;

            PgpSignatureGenerator pgpSignatureGenerator =

                new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, m_encryptionKeys.PrivateKey);

            foreach (string userId in m_encryptionKeys.SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator subPacketGenerator =
                    new PgpSignatureSubpacketGenerator();

                subPacketGenerator.SetSignerUserId(IsCritical, userId);

                pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());

                // Just the first one!

                break;
            }

            pgpSignatureGenerator.GenerateOnePassVersion(IsNested).Encode(compressedOut);

            return(pgpSignatureGenerator);
        }
Example #4
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()));
            }
        }
        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);
        }
Example #6
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) {}
            }
        }
Example #7
0
 private void setHashedSubpackets(PgpSignatureGenerator signatureGenerator) 
 {
     IEnumerator<string> it = (IEnumerator<string>)key.PublicKey.GetUserIds().GetEnumerator();
     while (it.MoveNext())
     {
         PgpSignatureSubpacketGenerator generator = new PgpSignatureSubpacketGenerator();
         generator.SetSignerUserId(false, it.Current);
         signatureGenerator.SetHashedSubpackets(generator.Generate());
     }
 }
        /// <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);
                    }
                }
            }
        }
Example #9
0
        /// <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);
        }
Example #10
0
        private static string DoSigning(string input, Stream keyIn, Stream outputStream, char[] pass)
        {
            var digest             = HashAlgorithmTag.Sha256;
            var pgpSecretKey       = ReadSigningSecretKey(keyIn);
            var pgpPrivateKey      = pgpSecretKey.ExtractPrivateKey(pass);
            var signatureGenerator = new PgpSignatureGenerator(pgpSecretKey.PublicKey.Algorithm, digest);
            var subpacketGenerator = new PgpSignatureSubpacketGenerator();

            signatureGenerator.InitSign(PgpSignature.StandAlone, pgpPrivateKey);

            foreach (var userId in pgpSecretKey.PublicKey.GetUserIds())
            {
                subpacketGenerator.SetSignerUserId(false, userId.ToString());
                signatureGenerator.SetHashedSubpackets(subpacketGenerator.Generate());
            }

            Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(input));
            var    armoredOut  = new ArmoredOutputStream(outputStream);

            armoredOut.BeginClearText(digest);

            // note the last \n/\r/\r\n in the file is ignored
            var lineOut   = new MemoryStream();
            int lookAhead = ReadInputLine(lineOut, inputStream);

            ProcessLine(armoredOut, signatureGenerator, lineOut.ToArray());

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, inputStream);

                    signatureGenerator.Update((byte)'\n');

                    ProcessLine(armoredOut, signatureGenerator, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            inputStream.Close();

            armoredOut.EndClearText();

            var bcpgOutput = new BcpgOutputStream(armoredOut);

            signatureGenerator.Generate().Encode(bcpgOutput);

            armoredOut.Close();

            outputStream.Seek(0, 0);
            return(new StreamReader(outputStream).ReadToEnd());
        }
Example #11
0
        // http://stackoverflow.com/questions/20572737/sign-and-verify-xml-file-in-c-sharp



        public void SignFile(string hashAlgorithm, string fileName, System.IO.Stream privateKeyStream
                             , string privateKeyPassword, System.IO.Stream outStream)
        {
            PgpSecretKey  pgpSec     = ReadSigningSecretKey(privateKeyStream);
            PgpPrivateKey pgpPrivKey = null;

            pgpPrivKey = pgpSec.ExtractPrivateKey(privateKeyPassword.ToCharArray());



            PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, ParseHashAlgorithm(hashAlgorithm));

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            foreach (string userId in pgpSec.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

                spGen.SetSignerUserId(false, userId);
                sGen.SetHashedSubpackets(spGen.Generate());
            }

            CompressionAlgorithmTag    compression = PreferredCompression(pgpSec.PublicKey);
            PgpCompressedDataGenerator cGen        = new PgpCompressedDataGenerator(compression);

            BcpgOutputStream bOut = new BcpgOutputStream(cGen.Open(outStream));

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

            System.IO.FileInfo      file = new System.IO.FileInfo(fileName);
            System.IO.FileStream    fIn  = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            System.IO.Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);

            int ch = 0;

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

            fIn.Close();
            sGen.Generate().Encode(bOut);
            lGen.Close();
            cGen.Close();
            outStream.Close();
        }
Example #12
0
        private PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut, ChoPGPEncryptionKeys encryptionKeys)
        {
            PublicKeyAlgorithmTag tag = encryptionKeys.SecretKey.PublicKey.Algorithm;
            PgpSignatureGenerator pgpSignatureGenerator = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, encryptionKeys.PrivateKey);
            foreach (string userId in encryptionKeys.SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator subPacketGenerator = new PgpSignatureSubpacketGenerator();
                subPacketGenerator.SetSignerUserId(false, userId);
                pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());
                // Just the first one!
                break;
            }
            pgpSignatureGenerator.GenerateOnePassVersion(false).Encode(compressedOut);
            return(pgpSignatureGenerator);
        }
        private PgpSignatureGenerator createSignatureGenerator()
        {
            PgpPrivateKey         privateKey         = secretKey.ExtractPrivateKey(password);
            PgpPublicKey          internalPublicKey  = secretKey.PublicKey;
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(internalPublicKey.Algorithm, HashAlgorithmTag.Sha1);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);
            var userIds = internalPublicKey.GetUserIds();

            foreach (var userId in userIds)
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, (String)userId);
                signatureGenerator.SetHashedSubpackets(spGen.Generate());
                break;
            }
            return(signatureGenerator);
        }
        private PgpSignatureGenerator sigGen(Stream compressedOut)
        {
            const bool            Iscritical = false;
            const bool            IsNested   = false;
            PublicKeyAlgorithmTag tag        = _pgpKeys.PGPSecretKey.PublicKey.Algorithm;
            PgpSignatureGenerator pgpSigGen  = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSigGen.InitSign(PgpSignature.BinaryDocument, _pgpKeys.PGPPrivateKey);
            foreach (string userID in _pgpKeys.PGPSecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator subPackGen = new PgpSignatureSubpacketGenerator();
                subPackGen.SetSignerUserId(Iscritical, userID);
                pgpSigGen.SetHashedSubpackets(subPackGen.Generate());
                break;
            }
            pgpSigGen.GenerateOnePassVersion(IsNested).Encode(compressedOut);
            return(pgpSigGen);
        }
Example #15
0
        private PgpSignatureGenerator InitSigGen(Stream compressedO)
        {
            const bool            Crit      = false;
            const bool            Nestd     = false;
            PublicKeyAlgorithmTag tag       = mPgpKeys.SecretKey.PublicKey.Algorithm;
            PgpSignatureGenerator pgpSigGen = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSigGen.InitSign(PgpSignature.BinaryDocument, mPgpKeys.PrivateKey);
            foreach (string userId in mPgpKeys.SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator subpktGen = new PgpSignatureSubpacketGenerator();
                subpktGen.SetSignerUserId(Crit, userId);
                pgpSigGen.SetHashedSubpackets(subpktGen.Generate());
                break;
            }
            pgpSigGen.GenerateOnePassVersion(Nestd).Encode(compressedO);
            return(pgpSigGen);
        }
Example #16
0
        private static PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut, PgpEncryptionKeys encryptionKeys)
        {
            const bool isCritical = false;
            const bool isNested   = false;

            PublicKeyAlgorithmTag tag = encryptionKeys.SecretKey.PublicKey.Algorithm;
            var pgpSignatureGenerator = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, encryptionKeys.PrivateKey);

            string firstUserId = encryptionKeys.SecretKey.PublicKey.GetUserIds().Cast <string>().First();
            PgpSignatureSubpacketGenerator subPacketGenerator = new PgpSignatureSubpacketGenerator();

            subPacketGenerator.SetSignerUserId(isCritical, firstUserId);
            pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());

            pgpSignatureGenerator.GenerateOnePassVersion(isNested).Encode(compressedOut);
            return(pgpSignatureGenerator);
        }
Example #17
0
        public static string Sign(string hash, string keyFile, string keyPass)
        {
            var outStream     = new MemoryStream();
            var armoredStream = new ArmoredOutputStream(outStream);

            var secretKey  = ReadSigningKey(keyFile);
            var privateKey = secretKey.ExtractPrivateKey(keyPass.ToCharArray());
            var sigGen     = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha384);

            sigGen.InitSign(PgpSignature.BinaryDocument, privateKey);
            foreach (string userId in secretKey.PublicKey.GetUserIds())
            {
                var subpacketGenerator = new PgpSignatureSubpacketGenerator();
                subpacketGenerator.SetSignerUserId(false, userId);
                sigGen.SetHashedSubpackets(subpacketGenerator.Generate());
                break;
            }
            var signedStream = new BcpgOutputStream(armoredStream);

            sigGen.GenerateOnePassVersion(false).Encode(signedStream);

            var inStream = new MemoryStream(Encoding.ASCII.GetBytes(hash));

            var literalGenerator = new PgpLiteralDataGenerator();
            var literalOut       = literalGenerator.Open(signedStream, PgpLiteralData.Binary, "hash", hash.Length, DateTime.Now);

            int ch;

            while ((ch = inStream.ReadByte()) >= 0)
            {
                literalOut.WriteByte((byte)ch);
                sigGen.Update((byte)ch);
            }

            inStream.Dispose();
            literalGenerator.Close();

            sigGen.Generate().Encode(signedStream);

            armoredStream.Dispose();

            return(Encoding.ASCII.GetString(outStream.ToArray()));
        }
Example #18
0
        private PgpSignatureGenerator InitSignature(Stream outputStream)
        {
            if (PrivateKey == null)
            {
                return(null);
            }

            var signatureGenerator = new PgpSignatureGenerator(PrivateKey.GetPublicKey().Algorithm, HashAlgorithm);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, PrivateKey.GetSecretKey().ExtractPrivateKey(_password.ToCharArray()));

            var userId             = PrivateKey.GetPublicKey().GetUserIds().OfType <string>().FirstOrDefault();
            var subpacketGenerator = new PgpSignatureSubpacketGenerator();

            subpacketGenerator.SetSignerUserId(false, userId);
            signatureGenerator.SetHashedSubpackets(subpacketGenerator.Generate());
            signatureGenerator.GenerateOnePassVersion(false).Encode(outputStream);
            return(signatureGenerator);
        }
        public static void SignFile(Stream input, Stream outputStream, Stream keyIn, char[] pass)
        {
            var hashAlgorithm = HashAlgorithmTag.Sha512;

            var secretKey  = ReadSecretKey(keyIn);
            var privateKey = secretKey.ExtractPrivateKey(pass);

            var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, hashAlgorithm);
            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(hashAlgorithm);

                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>
        /// Initialise the signature generator.
        /// </summary>
        /// <param name="compressedOutputStream">
        /// The compressed output.
        /// </param>
        /// <param name="encryptionKeys">
        /// The PGP encryption key container.
        /// </param>
        /// <returns>
        /// The <see cref="PgpSignatureGenerator"/>.
        /// </returns>
        private static PgpSignatureGenerator InitSignatureGenerator(
            Stream compressedOutputStream,
            PgpKeyContainer encryptionKeys)
        {
            const bool IsCritical = false;
            const bool IsNested   = false;

            var tag = encryptionKeys.SecretKey.PublicKey.Algorithm;
            var pgpSignatureGenerator = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha256);

            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, encryptionKeys.PrivateKey);

            foreach (string userId in encryptionKeys.SecretKey.PublicKey.GetUserIds())
            {
                var subPacketGenerator = new PgpSignatureSubpacketGenerator();
                subPacketGenerator.SetSignerUserId(IsCritical, userId);
                pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());
                break;
            }

            pgpSignatureGenerator.GenerateOnePassVersion(IsNested).Encode(compressedOutputStream);
            return(pgpSignatureGenerator);
        }
        /// <summary>
        /// Sign public key with secret key. To access the private key from the
        /// secret container a password needs to be provided.
        /// </summary>
        /// <param name="secretKey">
        /// The secret key containing the private key for signing the public
        /// key.
        /// </param>
        /// <param name="password">
        /// The password of the secret key.
        /// </param>
        /// <param name="keyToBeSigned">
        /// The public key to be signed.
        /// </param>
        /// <param name="certain">
        /// Flag indicating whether or not the certification is positive or just
        /// casual.
        /// </param>
        /// <returns>
        /// Returns the <see cref="PgpPublicKey"/> adorned with a signature by the
        /// private key passed in.
        /// </returns>
        public static PgpPublicKey SignPublicKey(
            PgpSecretKey secretKey,
            string password,
            PgpPublicKey keyToBeSigned,
            bool certain)
        {
            var id = keyToBeSigned.GetUserIds().Cast <string>().FirstOrDefault();

            // Extracting private key, and getting ready to create a signature.
            var privateKey         = secretKey.ExtractPrivateKey(password.ToCharArray());
            var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256);

            signatureGenerator.InitSign(
                certain ? PgpSignature.PositiveCertification : PgpSignature.CasualCertification,
                privateKey);

            // Creating a stream to wrap the results of operation.
            var outputStream       = new MemoryStream();
            var packetOutputStream = new BcpgOutputStream(outputStream);

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

            // Creating a generator.
            var subpacketSignatureGenerator = new PgpSignatureSubpacketGenerator();

            subpacketSignatureGenerator.SetSignerUserId(false, id);
            var packetVector = subpacketSignatureGenerator.Generate();

            signatureGenerator.SetHashedSubpackets(packetVector);
            packetOutputStream.Flush();

            // Returning the signed public key.
            return(PgpPublicKey.AddCertification(
                       keyToBeSigned,
                       id,
                       signatureGenerator.GenerateCertification(id, keyToBeSigned)));
        }
        private static PgpSignatureSubpacketVector GenerateSignatureSubpackets(string identity)
        {
            var hashedSubkeysGenerator = new PgpSignatureSubpacketGenerator();

            hashedSubkeysGenerator.SetSignerUserId(false, identity);

            return hashedSubkeysGenerator.Generate();
        }
        public override void PerformTest()
        {
            //
            // RSA tests
            //
            PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(rsaKeyRing);
            IPgpSecretKey secretKey = pgpPriv.GetSecretKey();
            IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass);

            try
            {
                doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("RSA wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            try
            {
                doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("RSA V3 wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            //
            // certifications
            //
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey);

            PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey);

            sig.InitVerify(secretKey.PublicKey);

            if (!sig.VerifyCertification(secretKey.PublicKey))
            {
                Fail("revocation verification failed.");
            }

            PgpSecretKeyRing pgpDSAPriv = new PgpSecretKeyRing(dsaKeyRing);
            IPgpSecretKey secretDSAKey = pgpDSAPriv.GetSecretKey();
            IPgpPrivateKey pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass);

            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            PgpSignatureSubpacketGenerator    unhashedGen = new PgpSignatureSubpacketGenerator();
            PgpSignatureSubpacketGenerator    hashedGen = new PgpSignatureSubpacketGenerator();

            hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME);
            hashedGen.SetSignerUserId(true, TEST_USER_ID);
            hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS);
            hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS);
            hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS);

            sGen.SetHashedSubpackets(hashedGen.Generate());
            sGen.SetUnhashedSubpackets(unhashedGen.Generate());

            sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey);

            byte[] sigBytes = sig.GetEncoded();

            PgpObjectFactory f = new PgpObjectFactory(sigBytes);

            sig = ((PgpSignatureList) f.NextPgpObject())[0];

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            var hashedPcks = sig.GetHashedSubPackets();
            var unhashedPcks = sig.GetUnhashedSubPackets();

            if (hashedPcks.Count != 6)
            {
                Fail("wrong number of hashed packets found.");
            }

            if (unhashedPcks.Count != 1)
            {
                Fail("wrong number of unhashed packets found.");
            }

            if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID))
            {
                Fail("test userid not matching");
            }

            if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME)
            {
                Fail("test signature expiration time not matching");
            }

            if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId)
            {
                Fail("wrong issuer key ID found in certification");
            }

            int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms();
            preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredHashAlgorithms();
            preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms();
            preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs);

            SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags();

            if (criticalHashed.Length != 1)
            {
                Fail("wrong number of critical packets found.");
            }

            if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId)
            {
                Fail("wrong critical packet found in tag list.");
            }

            //
            // no packets passed
            //
            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            sGen.SetHashedSubpackets(null);
            sGen.SetUnhashedSubpackets(null);

            sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey);

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            hashedPcks = sig.GetHashedSubPackets();

            if (hashedPcks.Count != 1)
            {
                Fail("found wrong number of hashed packets");
            }

            unhashedPcks = sig.GetUnhashedSubPackets();

            if (unhashedPcks.Count != 1)
            {
                Fail("found wrong number of unhashed packets");
            }

            try
            {
                sig.VerifyCertification(secretKey.PublicKey);

                Fail("failed to detect non-key signature.");
            }
            catch (InvalidOperationException)
            {
                // expected
            }

            //
            // override hash packets
            //
            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            hashedGen = new PgpSignatureSubpacketGenerator();

            DateTime creationTime = new DateTime(1973, 7, 27);
            hashedGen.SetSignatureCreationTime(false, creationTime);

            sGen.SetHashedSubpackets(hashedGen.Generate());

            sGen.SetUnhashedSubpackets(null);

            sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey);

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            hashedPcks = sig.GetHashedSubPackets();

            if (hashedPcks.Count != 1)
            {
                Fail("found wrong number of hashed packets in override test");
            }

            if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime))
            {
                Fail("hasSubpacket test for creation time failed");
            }

            DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime();
            if (!sigCreationTime.Equals(creationTime))
            {
                Fail("creation of overridden date failed.");
            }

            prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms();
            preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredHashAlgorithms();
            preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms();
            preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs);

            if (hashedPcks.GetKeyExpirationTime() != 0)
            {
                Fail("unexpected key expiration time found");
            }

            if (hashedPcks.GetSignatureExpirationTime() != 0)
            {
                Fail("unexpected signature expiration time found");
            }

            if (hashedPcks.GetSignerUserId() != null)
            {
                Fail("unexpected signer user ID found");
            }

            criticalHashed = hashedPcks.GetCriticalTags();

            if (criticalHashed.Length != 0)
            {
                Fail("critical packets found when none expected");
            }

            unhashedPcks = sig.GetUnhashedSubPackets();

            if (unhashedPcks.Count != 1)
            {
                Fail("found wrong number of unhashed packets in override test");
            }

            //
            // general signatures
            //
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey);
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey);
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey);
            doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

            //
            // DSA Tests
            //
            pgpPriv = new PgpSecretKeyRing(dsaKeyRing);
            secretKey = pgpPriv.GetSecretKey();
            pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass);

            try
            {
                doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("DSA wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            try
            {
                doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("DSA V3 wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

            // special cases
            //
            doTestMissingSubpackets(nullPacketsSubKeyBinding);

            doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1));

            // keyflags
            doTestKeyFlagsValues();
        }
        /// <summary>
        /// Create a file with PGP clear text signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpClearTextSignature Returns: Object {string FilePath}
        /// </summary>
        public static Result PGPClearTextSignFile(Input input)
        {
            HashAlgorithmTag digest;

            if (input.HashFunction == HashFunctionType.MD5)
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (input.HashFunction == HashFunctionType.RipeMD160)
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else if (input.HashFunction == HashFunctionType.Sha1)
            {
                digest = HashAlgorithmTag.Sha1;
            }
            else if (input.HashFunction == HashFunctionType.Sha224)
            {
                digest = HashAlgorithmTag.Sha224;
            }
            else if (input.HashFunction == HashFunctionType.Sha384)
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (input.HashFunction == HashFunctionType.Sha512)
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else
            {
                digest = HashAlgorithmTag.Sha256;
            }

            Stream privateKeyStream = File.OpenRead(input.PrivateKeyFile);

            PgpSecretKey                   pgpSecKey  = ReadSecretKey(privateKeyStream);
            PgpPrivateKey                  pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray());
            PgpSignatureGenerator          sGen       = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);
            PgpSignatureSubpacketGenerator spGen      = new PgpSignatureSubpacketGenerator();

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator();

            if (enumerator.MoveNext())
            {
                spGen.SetSignerUserId(false, (string)enumerator.Current);
                sGen.SetHashedSubpackets(spGen.Generate());
            }

            Stream fIn          = File.OpenRead(input.InputFile);
            Stream outputStream = File.Create(input.OutputFile);

            ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream);

            aOut.BeginClearText(digest);

            //
            // note the last \n/\r/\r\n in the file is ignored
            //
            MemoryStream lineOut   = new MemoryStream();
            int          lookAhead = ReadInputLine(lineOut, fIn);

            ProcessLine(aOut, sGen, lineOut.ToArray());

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, fIn);

                    sGen.Update((byte)'\r');
                    sGen.Update((byte)'\n');

                    ProcessLine(aOut, sGen, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            fIn.Close();

            aOut.EndClearText();

            BcpgOutputStream bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);

            aOut.Close();
            outputStream.Close();

            Result ret = new Result
            {
                FilePath = input.OutputFile
            };

            return(ret);
        }
        /**
        * Generated signature test
        *
        * @param sKey
        * @param pgpPrivKey
        * @return test result
        */
        public void GenerateTest(
            PgpSecretKeyRing sKey,
            IPgpPublicKey     pgpPubKey,
            IPgpPrivateKey    pgpPrivKey)
        {
            string data = "hello world!";
            MemoryStream bOut = new MemoryStream();

            byte[] dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream testIn = new MemoryStream(dataBytes, false);

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            string primaryUserId = (string) enumerator.Current;

            spGen.SetSignerUserId(true, primaryUserId);

            sGen.SetHashedSubpackets(spGen.Generate());

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

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

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray());
            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData) pgpFact.NextPgpObject();
            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pgpPubKey);

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte) ch);
            }

            PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }
        }
Example #26
0
        public override void PerformTest()
        {
            //
            // RSA tests
            //
            PgpSecretKeyRing pgpPriv    = new PgpSecretKeyRing(rsaKeyRing);
            PgpSecretKey     secretKey  = pgpPriv.GetSecretKey();
            PgpPrivateKey    pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass);

            try
            {
                doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("RSA wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            try
            {
                doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("RSA V3 wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            //
            // certifications
            //
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey);

            PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey);

            sig.InitVerify(secretKey.PublicKey);

            if (!sig.VerifyCertification(secretKey.PublicKey))
            {
                Fail("revocation verification failed.");
            }

            PgpSecretKeyRing pgpDSAPriv    = new PgpSecretKeyRing(dsaKeyRing);
            PgpSecretKey     secretDSAKey  = pgpDSAPriv.GetSecretKey();
            PgpPrivateKey    pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass);

            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator();
            PgpSignatureSubpacketGenerator hashedGen   = new PgpSignatureSubpacketGenerator();

            hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME);
            hashedGen.SetSignerUserId(true, TEST_USER_ID);
            hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS);
            hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS);
            hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS);

            sGen.SetHashedSubpackets(hashedGen.Generate());
            sGen.SetUnhashedSubpackets(unhashedGen.Generate());

            sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey);

            byte[] sigBytes = sig.GetEncoded();

            PgpObjectFactory f = new PgpObjectFactory(sigBytes);

            sig = ((PgpSignatureList)f.NextPgpObject())[0];

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            PgpSignatureSubpacketVector hashedPcks   = sig.GetHashedSubPackets();
            PgpSignatureSubpacketVector unhashedPcks = sig.GetUnhashedSubPackets();

            if (hashedPcks.Count != 6)
            {
                Fail("wrong number of hashed packets found.");
            }

            if (unhashedPcks.Count != 1)
            {
                Fail("wrong number of unhashed packets found.");
            }

            if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID))
            {
                Fail("test userid not matching");
            }

            if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME)
            {
                Fail("test signature expiration time not matching");
            }

            if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId)
            {
                Fail("wrong issuer key ID found in certification");
            }

            int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms();
            preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredHashAlgorithms();
            preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms();
            preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs);

            SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags();

            if (criticalHashed.Length != 1)
            {
                Fail("wrong number of critical packets found.");
            }

            if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId)
            {
                Fail("wrong critical packet found in tag list.");
            }

            //
            // no packets passed
            //
            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            sGen.SetHashedSubpackets(null);
            sGen.SetUnhashedSubpackets(null);

            sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey);

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            hashedPcks = sig.GetHashedSubPackets();

            if (hashedPcks.Count != 1)
            {
                Fail("found wrong number of hashed packets");
            }

            unhashedPcks = sig.GetUnhashedSubPackets();

            if (unhashedPcks.Count != 1)
            {
                Fail("found wrong number of unhashed packets");
            }

            try
            {
                sig.VerifyCertification(secretKey.PublicKey);

                Fail("failed to detect non-key signature.");
            }
            catch (InvalidOperationException)
            {
                // expected
            }

            //
            // override hash packets
            //
            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            hashedGen = new PgpSignatureSubpacketGenerator();

            DateTime creationTime = new DateTime(1973, 7, 27);

            hashedGen.SetSignatureCreationTime(false, creationTime);

            sGen.SetHashedSubpackets(hashedGen.Generate());

            sGen.SetUnhashedSubpackets(null);

            sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey);

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            hashedPcks = sig.GetHashedSubPackets();

            if (hashedPcks.Count != 1)
            {
                Fail("found wrong number of hashed packets in override test");
            }

            if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime))
            {
                Fail("hasSubpacket test for creation time failed");
            }

            DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime();

            if (!sigCreationTime.Equals(creationTime))
            {
                Fail("creation of overridden date failed.");
            }

            prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms();
            preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredHashAlgorithms();
            preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms();
            preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs);

            if (hashedPcks.GetKeyExpirationTime() != 0)
            {
                Fail("unexpected key expiration time found");
            }

            if (hashedPcks.GetSignatureExpirationTime() != 0)
            {
                Fail("unexpected signature expiration time found");
            }

            if (hashedPcks.GetSignerUserId() != null)
            {
                Fail("unexpected signer user ID found");
            }

            criticalHashed = hashedPcks.GetCriticalTags();

            if (criticalHashed.Length != 0)
            {
                Fail("critical packets found when none expected");
            }

            unhashedPcks = sig.GetUnhashedSubPackets();

            if (unhashedPcks.Count != 1)
            {
                Fail("found wrong number of unhashed packets in override test");
            }

            //
            // general signatures
            //
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey);
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey);
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey);
            doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

            //
            // DSA Tests
            //
            pgpPriv    = new PgpSecretKeyRing(dsaKeyRing);
            secretKey  = pgpPriv.GetSecretKey();
            pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass);

            try
            {
                doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("DSA wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            try
            {
                doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("DSA V3 wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

            // special cases
            //
            doTestMissingSubpackets(nullPacketsSubKeyBinding);

            doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1));

            // keyflags
            doTestKeyFlagsValues();
        }
Example #27
0
        public void SignAndEncryptFile(string strActualFileName, string strEmbeddedFileName,
                                       System.IO.Stream strmKeyIn, long lngKeyId, System.IO.Stream strmOutputStream,
                                       char[] szPassword, bool bArmor, bool bWithIntegrityCheck, PgpPublicKey PGP_PublicKey)
        {
            const int iBUFFER_SIZE = 1 << 16; // should always be power of 2

            if (bArmor)
            {
                strmOutputStream = new ArmoredOutputStream(strmOutputStream);
            }

            // Init encrypted data generator
            PgpEncryptedDataGenerator PGP_EncryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, bWithIntegrityCheck, new SecureRandom());

            PGP_EncryptedDataGenerator.AddMethod(PGP_PublicKey);
            System.IO.Stream strmEncryptedOut = PGP_EncryptedDataGenerator.Open(strmOutputStream, new byte[iBUFFER_SIZE]);

            // Init compression
            PgpCompressedDataGenerator PGP_CompressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

            System.IO.Stream strmCompressedOut = PGP_CompressedDataGenerator.Open(strmEncryptedOut);

            // Init signature
            PgpSecretKeyRingBundle PGP_SecretKeyBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(strmKeyIn));
            PgpSecretKey           PGP_SecretKey       = PGP_SecretKeyBundle.GetSecretKey(lngKeyId);

            if (PGP_SecretKey == null)
            {
                throw new System.ArgumentException(lngKeyId.ToString("X") + " could not be found in specified key ring bundle.", "keyId");
            }

            PgpPrivateKey         PGP_PrivateKey         = PGP_SecretKey.ExtractPrivateKey(szPassword);
            PgpSignatureGenerator PGP_SignatureGenerator = new PgpSignatureGenerator(PGP_SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            PGP_SignatureGenerator.InitSign(PgpSignature.BinaryDocument, PGP_PrivateKey);

            foreach (string strUserId in PGP_SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator PGP_SignatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
                PGP_SignatureSubpacketGenerator.SetSignerUserId(false, strUserId);
                PGP_SignatureGenerator.SetHashedSubpackets(PGP_SignatureSubpacketGenerator.Generate());
                // Just the first one!
                break;
            }
            PGP_SignatureGenerator.GenerateOnePassVersion(false).Encode(strmCompressedOut);

            // Create the Literal Data generator output stream
            PgpLiteralDataGenerator PGP_LiteralDataGenerator = new PgpLiteralDataGenerator();

            System.IO.FileInfo fiEmbeddedFile = new System.IO.FileInfo(strEmbeddedFileName);
            System.IO.FileInfo fiActualFile   = new System.IO.FileInfo(strActualFileName);
            // TODO: Use lastwritetime from source file
            System.IO.Stream strmLiteralOut = PGP_LiteralDataGenerator.Open(strmCompressedOut, PgpLiteralData.Binary,
                                                                            fiEmbeddedFile.Name, fiActualFile.LastWriteTime, new byte[iBUFFER_SIZE]);

            // Open the input file
            System.IO.FileStream strmInputStream = fiActualFile.OpenRead();

            byte[] baBuffer = new byte[iBUFFER_SIZE];
            int    iReadLength;

            while ((iReadLength = strmInputStream.Read(baBuffer, 0, baBuffer.Length)) > 0)
            {
                strmLiteralOut.Write(baBuffer, 0, iReadLength);
                PGP_SignatureGenerator.Update(baBuffer, 0, iReadLength);
            }

            strmLiteralOut.Close();
            PGP_LiteralDataGenerator.Close();
            PGP_SignatureGenerator.Generate().Encode(strmCompressedOut);
            strmCompressedOut.Close();
            PGP_CompressedDataGenerator.Close();
            strmEncryptedOut.Close();
            PGP_EncryptedDataGenerator.Close();
            strmInputStream.Close();

            if (bArmor)
            {
                strmOutputStream.Close();
            }
        }
Example #28
0
        /*
         * 文章 -> hash -> 私鑰(自己)簽章 -> 簽章後的hash值
         * 文章 - - - - - - - - - - - - - -> 文章
         */


        /*.......................................................................數位簽章開始*/


        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);            //匯出位置、headers、雜湊表
            }
            PgpSecretKey  pgpSec     = PgpExampleUtilities.ReadSecretKey(keyIn); //PgpSecretKey包含私鑰及公鑰整個物件
            PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass);           //需輸入私鑰密碼才能取出私鑰

            /*
             * SHA是由美國國家安全局制定,主要應用於數字簽名標準裡面的數字簽名算法( DSA : Digital Signature Algorithm ),
             * SHA家族中以SHA1和SHA256最為廣泛使用。SHA1的雜湊值長度為160bit、SHA256則為256bit,長度越長碰撞的機會就越低也越安全,
             * 但同時計算的時間複雜度也隨著增高。
             */

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha256); //PublicKey.Algorithm即原始公鑰

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);                                                      //若沒私鑰重新生產一個

            foreach (string userId in pgpSec.PublicKey.GetUserIds())                                                     //ExportKeyPair 的 identity (MarkWu)
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);       //數位簽章的使用者
                sGen.SetHashedSubpackets(spGen.Generate()); //將 SignatureSubpacket 陣列化再回傳
                // 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);  //hash 加密

            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();
            }
        }
Example #29
0
        /// <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);
        }
Example #30
0
        void SignAndEncryptFile()
        {
            const int BUFFER_SIZE = 1 << 16; // should always be power of 2

            var OutStream = OutFile.OpenWrite();

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

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

            Stream outputStream = OutStream;

            if (Armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            Stream encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]);

            if (Compress)
            {
                // Init compression
                PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                encryptedOut = compressedDataGenerator.Open(encryptedOut);
            }

            //signing
            List <PgpSignatureGenerator> pgpSignatureGenerators = new List <PgpSignatureGenerator>();

            foreach (var privateKeyInfo in PrivateKeys)
            {
                PgpSecretKey  pgpSecKey  = ReadSecretKey(privateKeyInfo.PrivateKeyStream);
                PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(privateKeyInfo.PrivateKeyPassword == null ? null : privateKeyInfo.PrivateKeyPassword.ToCharArray());

                PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
                signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

                foreach (string userId in pgpSecKey.PublicKey.GetUserIds())
                {
                    PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                    spGen.SetSignerUserId(false, userId);
                    signatureGenerator.SetHashedSubpackets(spGen.Generate());
                    // Just the first one!
                    break;
                }

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

                pgpSignatureGenerators.Add(signatureGenerator);
            }
            // Create the Literal Data generator output stream
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            Stream literalOut = literalDataGenerator.Open(encryptedOut, PgpLiteralData.Binary, InFile.Name, InFile.LastWriteTime, new byte[BUFFER_SIZE]);

            // Open the input file
            FileStream inputStream = InFile.OpenRead();

            byte[] buf = new byte[BUFFER_SIZE];
            int    len;

            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, len);
                foreach (var signatureGenerator in pgpSignatureGenerators)
                {
                    signatureGenerator.Update(buf, 0, len);
                }
            }

            literalOut.Close();
            literalDataGenerator.Close();
            foreach (var signatureGenerator in pgpSignatureGenerators)
            {
                signatureGenerator.Generate().Encode(encryptedOut);
            }
            encryptedOut.Close();
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            inputStream.Close();


            if (Armor)
            {
                outputStream.Close();
            }

            OutStream.Close();
        }
		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);
		}
Example #32
0
        /**
         * Generated signature test
         *
         * @param sKey
         * @param pgpPrivKey
         * @return test result
         */
        public void GenerateTest(
            PgpSecretKeyRing sKey,
            PgpPublicKey pgpPubKey,
            PgpPrivateKey pgpPrivKey)
        {
            string       data = "hello world!";
            MemoryStream bOut = new MemoryStream();

            byte[]       dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream testIn    = new MemoryStream(dataBytes, false);

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator();

            enumerator.MoveNext();
            string primaryUserId = (string)enumerator.Current;

            spGen.SetSignerUserId(true, primaryUserId);

            sGen.SetHashedSubpackets(spGen.Generate());

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

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

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream   lOut         = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            int ch;

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            PgpObjectFactory  pgpFact = new PgpObjectFactory(bOut.ToArray());
            PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pgpPubKey);

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }
        }
Example #33
0
        private byte[] GetEncryptedData(byte[] data)
        {
            var baos   = new MemoryStream();
            var outStr = new ArmoredOutputStream(baos);

            PgpPublicKey publicKey   = null;
            var          inputStream = PgpUtilities.GetDecoderStream(new MemoryStream(_encryptionKey));
            var          pgpPub      = new PgpPublicKeyRingBundle(inputStream);

            for (var i = pgpPub.GetKeyRings().GetEnumerator(); i.MoveNext();)
            {
                var pgpPublicKeyRing = (PgpPublicKeyRing)i.Current;
                if (pgpPublicKeyRing != null)
                {
                    for (var j = pgpPublicKeyRing.GetPublicKeys().GetEnumerator();
                         publicKey == null && j.MoveNext();)
                    {
                        var k = (PgpPublicKey)j.Current;
                        if (k != null && k.IsEncryptionKey)
                        {
                            publicKey = k;
                        }
                    }
                }
            }
            if (publicKey == null)
            {
                throw new Exception("Can't find encryption key in key ring.");
            }

            var           pgpSec     = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(new MemoryStream(_signingKey)));
            PgpPrivateKey privateKey = null;
            PgpSecretKey  secretKey  = null;

            for (var i = pgpSec.GetKeyRings().GetEnumerator(); privateKey == null && i.MoveNext();)
            {
                var keyRing = (PgpSecretKeyRing)i.Current;
                if (keyRing != null)
                {
                    for (var j = keyRing.GetSecretKeys().GetEnumerator(); j.MoveNext();)
                    {
                        secretKey = (PgpSecretKey)j.Current;
                        if (secretKey != null)
                        {
                            privateKey = secretKey.ExtractPrivateKey(_password);
                        }
                        break;
                    }
                }
            }
            if (secretKey == null)
            {
                throw new Exception("Can't find signature key in key ring.");
            }
            var cb = new MemoryStream();
            var compressedGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            var compressedOut       = compressedGenerator.Open(cb);
            var signatureGenerator  = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm,
                                                                HashAlgorithmTag.Sha512);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);
            for (var i = secretKey.PublicKey.GetUserIds().GetEnumerator(); i.MoveNext();)
            {
                var spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, (String)i.Current);
                signatureGenerator.SetHashedSubpackets(spGen.Generate());
            }
            signatureGenerator.GenerateOnePassVersion(true).Encode(compressedOut);
            var lgen     = new PgpLiteralDataGenerator();
            var finalOut = lgen.Open(compressedOut, PgpLiteralData.Binary, "", DateTime.Now, new byte[4096]);

            finalOut.Write(data, 0, data.Length);
            signatureGenerator.Update(data);
            finalOut.Close();
            lgen.Close();
            signatureGenerator.Generate().Encode(compressedOut);
            compressedGenerator.Close();
            compressedOut.Close();
            var compressedData         = cb.ToArray();
            var encryptedDataGenerator =
                new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true,
                                              new SecureRandom());

            encryptedDataGenerator.AddMethod(publicKey);
            var encryptedOut = encryptedDataGenerator.Open(outStr, compressedData.Length);

            encryptedOut.Write(compressedData, 0, compressedData.Length);
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            outStr.Close();
            return(baos.ToArray());
        }
        /*
         * 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();
        }