예제 #1
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) {}
            }
        }
        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);
        }
예제 #3
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);
        }
예제 #4
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());
        }
예제 #5
0
        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>
        /// 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);
        }
		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);
		}
        /*
         * 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();
        }
예제 #9
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 SignClear(string data, string key, Encoding encoding, Dictionary <string, string> headers)
        {
            Context = new CryptoContext(Context);

            var senderKey = GetSecretKeyForSigning(key);

            if (senderKey == null)
            {
                throw new SecretKeyNotFoundException("Error, unable to locate signing key \"" + key + "\".");
            }

            // Setup signature stuff //
            var signatureData = new PgpSignatureGenerator(senderKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            signatureData.InitSign(PgpSignature.CanonicalTextDocument, senderKey.ExtractPrivateKey(Context.Password));

            foreach (string userId in senderKey.PublicKey.GetUserIds())
            {
                var subPacketGenerator = new PgpSignatureSubpacketGenerator();

                subPacketGenerator.SetSignerUserId(false, userId);
                signatureData.SetHashedSubpackets(subPacketGenerator.Generate());

                // Just the first one!
                break;
            }

            // //

            using (var sout = new MemoryStream())
            {
                using (var armoredOut = new ArmoredOutputStream(sout))
                {
                    foreach (var header in headers)
                    {
                        armoredOut.SetHeader(header.Key, header.Value);
                    }

                    armoredOut.BeginClearText(HashAlgorithmTag.Sha1);

                    // Remove any extra trailing whitespace.
                    // this should not include \r or \n.
                    data = data.TrimEnd(null);

                    using (var stringReader = new StringReader(data))
                    {
                        do
                        {
                            var line = stringReader.ReadLine();
                            if (line == null)
                            {
                                break;
                            }

                            // Lines must have all white space removed
                            line = line.TrimEnd(null);
                            line = line.TrimEnd(new char[] { ' ', '\t', '\r', '\n' });

                            line += "\r\n";

                            signatureData.Update(encoding.GetBytes(line));
                            armoredOut.Write(encoding.GetBytes(line));
                        }while (true);
                    }

                    // Write extra line before signature block.
                    armoredOut.Write(encoding.GetBytes("\r\n"));
                    armoredOut.EndClearText();

                    using (var outputStream = new BcpgOutputStream(armoredOut))
                    {
                        signatureData.Generate().Encode(outputStream);
                    }
                }

                return(encoding.GetString(sout.ToArray()));
            }
        }
        /*
        * 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();
        }
        /*
         * create a clear text signed file.
         */
        public static void SignFile(
            //string fileName,
            Stream fIn,
            PgpSecretKey pgpSecKey,
            Stream outputStream,
            char[] pass,
            string digestName,
            bool version = true
            )
        {
            HashAlgorithmTag digest;

            if (string.Equals(digestName, "Sha256", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha256;
            }
            else if (string.Equals(digestName, "Sha384", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (string.Equals(digestName, "Sha512", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else if (string.Equals(digestName, "MD5", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (string.Equals(digestName, "RipeMD160", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else
            {
                digest = HashAlgorithmTag.Sha512;
            }

            // Instanciate signature generator.
            var sGen  = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);
            var spGen = new PgpSignatureSubpacketGenerator();

            // Extract private key
            PgpPrivateKey pgpPrivKey;

            try
            {
                pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass);
                sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);
            }
            catch
            {
                throw new PgpException("Wrong Passphrase, could not extract private key.");
            }

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

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

            var aOut = new ArmoredOutputStream(outputStream);

            if (version)
            {
                aOut.SetHeader("Version", "Posh-OpenPGP");
            }

            aOut.BeginClearText(digest);

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

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

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, fIn);
                    sGen.Update((byte)'\r');
                    sGen.Update((byte)'\n');
                    ProcessLine(aOut, sGen, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            fIn.Close();
            aOut.EndClearText();
            var bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);
            aOut.Close();
        }
예제 #12
0
        /// <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 PgpClearTextSignatureResult ClearTextSignFile(PgpClearTextSignatureInput input)
        {
            HashAlgorithmTag digest;

            switch (input.HashFunction)
            {
            case PgpClearTextSignatureHashFunctionType.Md5:
                digest = HashAlgorithmTag.MD5;
                break;

            case PgpClearTextSignatureHashFunctionType.RipeMd160:
                digest = HashAlgorithmTag.RipeMD160;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha1:
                digest = HashAlgorithmTag.Sha1;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha224:
                digest = HashAlgorithmTag.Sha224;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha384:
                digest = HashAlgorithmTag.Sha384;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha512:
                digest = HashAlgorithmTag.Sha512;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha256:
                digest = HashAlgorithmTag.Sha256;
                break;

            default:
                digest = HashAlgorithmTag.Sha256;
                break;
            }

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

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

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

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

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

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

            var aOut = new ArmoredOutputStream(outputStream);

            aOut.BeginClearText(digest);

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

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

            while (lookAhead != -1)
            {
                lookAhead = PgpServices.ReadInputLine(lineOut, lookAhead, fIn);

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

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

            fIn.Close();

            aOut.EndClearText();

            var bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);

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

            var ret = new PgpClearTextSignatureResult
            {
                FilePath = input.OutputFile
            };

            return(ret);
        }