示例#1
0
    private OpenPgpSignature Verify(ArraySegment <byte> data, PgpSignature signature)
    {
        var key = PublicBundle.GetPublicKey(signature.KeyId);

        if (key == null)
        {
            return(new MissingKeySignature(signature.KeyId));
        }
        else
        {
            signature.InitVerify(key);
            signature.Update(data.Array, data.Offset, data.Count);

            if (signature.Verify())
            {
                return(new ValidSignature(key.KeyId, key.GetFingerprint(), signature.CreationTime));
            }
            else
            {
                var badSig = new BadSignature(signature.KeyId);
                Log.Warn(badSig.ToString());
                return(badSig);
            }
        }
    }
示例#2
0
        /// <summary>
        /// Attempt to verify a PGP signed message using the matching public key.
        /// </summary>
        /// <param name="signedMessageStream">Stream containing the signed message.</param>
        /// <param name="signatureStream">Stream containing the signature.</param>
        /// <param name="publicKey">BouncyCastle public key to be used for verification.</param>
        /// <remarks>The message and signature should be passed in without ASCII Armor.</remarks>
        /// <returns>Whether the message's signature is verified.</returns>
        public static bool VerifySignature(Stream signedMessageStream, Stream signatureStream, PgpPublicKey publicKey)
        {
            // Decode from Base-64.
            using (Stream decoderStream = PgpUtilities.GetDecoderStream(signatureStream))
            {
                // Extract the signature list.
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);

                PgpObject pgpObject = pgpObjectFactory.NextPgpObject();
                if (pgpObject is PgpSignatureList)
                {
                    PgpSignatureList signatureList = pgpObject as PgpSignatureList;

                    // Hydrate the signature object with the message to be verified.
                    PgpSignature signature = signatureList[0];
                    signature.InitVerify(publicKey);
                    signedMessageStream.Seek(0, SeekOrigin.Begin);
                    for (int i = 0; i < signedMessageStream.Length; i++)
                    {
                        signature.Update((byte)signedMessageStream.ReadByte());
                    }

                    // Return the result.
                    return(signature.Verify());
                }
                else
                {
                    return(false);
                }
            }
        }
        /**
         * verify the signature in in against the file fileName.
         */
        private static bool VerifySignature(
            string OriginalMessage,
            string EncodedMessage,
            Stream keyIn)
        {
            byte[] bytes = Convert.FromBase64String(EncodedMessage);
            using (Stream inputStream = new MemoryStream(bytes))
            {
                PgpObjectFactory pgpFact = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                PgpSignatureList p3      = null;
                PgpObject        o       = pgpFact.NextPgpObject();
                if (o is PgpCompressedData)
                {
                    PgpCompressedData c1 = (PgpCompressedData)o;
                    pgpFact = new PgpObjectFactory(c1.GetDataStream());

                    p3 = (PgpSignatureList)pgpFact.NextPgpObject();
                }
                else
                {
                    p3 = (PgpSignatureList)o;
                }

                PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(
                    PgpUtilities.GetDecoderStream(keyIn));
                PgpSignature sig = p3[0];
                PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);
                sig.InitVerify(key);
                sig.Update(System.Text.Encoding.UTF8.GetBytes(OriginalMessage));

                return(sig.Verify());
            }
        }
示例#4
0
        private OpenPgpSignature Verify([NotNull] byte[] data, [NotNull] PgpSignature signature)
        {
            var key = PublicBundle.GetPublicKey(signature.KeyId);

            if (key == null)
            {
                return(new MissingKeySignature(signature.KeyId));
            }
            else
            {
                signature.InitVerify(key);
                signature.Update(data);

                if (signature.Verify())
                {
                    return(new ValidSignature(key.KeyId, key.GetFingerprint(), signature.CreationTime));
                }
                else
                {
                    var badSig = new BadSignature(signature.KeyId);
                    Log.Warn(badSig.ToString());
                    return(badSig);
                }
            }
        }
示例#5
0
        private static void VerifySignature(PgpOnePassSignatureList onePassSigList, PgpSignatureList signatureList, PgpPublicKey pubKey, byte[] original)
        {
            PgpOnePassSignature ops = onePassSigList[0];

            ops.InitVerify(pubKey);
            ops.Update(original);

            PgpSignatureList p3  = signatureList;
            PgpSignature     sig = p3[0];

            if (sig.KeyId != pubKey.KeyId)
            {
                throw new PgpException("key id mismatch in signature.");
            }

            if (!ops.Verify(sig))
            {
                throw new PgpException("Failed generated signature check.");
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i < original.Length; i++)
            {
                sig.Update(original[i]);
            }

            //sig.Update(original);

            if (!sig.Verify())
            {
                throw new PgpException("Failed generated signature check against original data.");
            }
        }
示例#6
0
        private void verifySignature(
            byte[] encodedSig,
            HashAlgorithmTag hashAlgorithm,
            PgpPublicKey pubKey,
            byte[] original)
        {
            PgpObjectFactory        pgpFact = new PgpObjectFactory(encodedSig);
            PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops     = p1[0];
            PgpLiteralData          p2      = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            int ch;

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

            PgpSignatureList p3  = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig = p3[0];

            DateTime creationTime = sig.CreationTime;

            // Check creationTime is recent
            if (creationTime.CompareTo(DateTime.UtcNow) > 0 ||
                creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0)
            {
                Fail("bad creation time in signature: " + creationTime);
            }

            if (sig.KeyId != pubKey.KeyId)
            {
                Fail("key id mismatch in signature");
            }

            if (!ops.Verify(sig))
            {
                Fail("Failed generated signature check - " + hashAlgorithm);
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i != original.Length; i++)
            {
                sig.Update(original[i]);
            }

            sig.Update(original);

            if (!sig.Verify())
            {
                Fail("Failed generated signature check against original data");
            }
        }
示例#7
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);

            foreach (PgpSignature certification in pubKeyRing.GetPublicKey().GetSignatures())
            {
                certification.InitVerify(pubKeyRing.GetPublicKey());

                if (!certification.VerifyCertification((string)First(pubKeyRing.GetPublicKey().GetUserIds()), pubKeyRing.GetPublicKey()))
                {
                    Fail("self certification does not verify");
                }
            }

            if (pubKeyRing.GetPublicKey().BitStrength != 256)
            {
                Fail("incorrect bit strength returned");
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey);

            PgpPrivateKey privKey = secretKeyRing.GetSecretKey().ExtractPrivateKey(testPasswd);

            GenerateAndSign();

            //
            // sExpr
            //
            byte[] msg = Encoding.ASCII.GetBytes("hello world!");

            PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKey, false), "test".ToCharArray());

            PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);

            signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null));
            signGen.Update(msg);

            PgpSignature sig = signGen.Generate();

            sig.InitVerify(key.PublicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }
        }
        /**
         * verify the signature in in against the file fileName.
         */
        private static void VerifySignature(
            string fileName,
            Stream inputStream,
            Stream keyIn)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream);
            PgpSignatureList p3      = null;
            PgpObject        o       = pgpFact.NextPgpObject();

            if (o is PgpCompressedData)
            {
                PgpCompressedData c1 = (PgpCompressedData)o;
                pgpFact = new PgpObjectFactory(c1.GetDataStream());

                p3 = (PgpSignatureList)pgpFact.NextPgpObject();
            }
            else
            {
                p3 = (PgpSignatureList)o;
            }

            PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(
                PgpUtilities.GetDecoderStream(keyIn));
            Stream       dIn = File.OpenRead(fileName);
            PgpSignature sig = p3[0];
            PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);

            sig.InitVerify(key);

            int ch;

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

            dIn.Close();

            if (sig.Verify())
            {
                Console.WriteLine("signature verified.");
            }
            else
            {
                Console.WriteLine("signature verification failed.");
            }
        }
示例#9
0
        /// <summary>
        /// Verifies a PGP signature.
        /// </summary>
        /// <param name="signature">
        /// The PGP signature to verify.
        /// </param>
        /// <param name="key">
        /// The public key of the signer.
        /// </param>
        /// <param name="payload">
        /// The payload for which the signature was generated.
        /// </param>
        /// <returns>
        /// <see langword="true"/> if the signature is valid; otherwise, <see langword="false"/>.
        /// </returns>
        public static bool VerifySignature(PgpSignature signature, PgpPublicKey key, Stream payload)
        {
            signature.InitVerify(key);

            byte[] buffer = new byte[1024];

            int read;

            while ((read = payload.Read(buffer, 0, buffer.Length)) > 0)
            {
                signature.Update(buffer, 0, read);
            }

            return(signature.Verify());
        }
示例#10
0
        private static void Main()
        {
            if (!File.Exists("MANIFEST.json.asc"))
            {
                return;
            }

            Stream inputStream = File.OpenRead("MANIFEST.json.asc");
            Stream keyIn       = File.OpenRead("gpg");

            // https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/openpgp/examples/DetachedSignatureProcessor.cs

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream);
            PgpSignatureList p3;
            PgpObject        o = pgpFact.NextPgpObject();

            if (o is PgpCompressedData c1)
            {
                pgpFact = new PgpObjectFactory(c1.GetDataStream());

                p3 = (PgpSignatureList)pgpFact.NextPgpObject();
            }
            else
            {
                p3 = (PgpSignatureList)o;
            }

            PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
            Stream       dIn = File.OpenRead("MANIFEST.json");
            PgpSignature sig = p3[0];
            PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);

            sig.InitVerify(key);

            int ch;

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

            dIn.Close();

            Console.WriteLine(sig.Verify() ? "signature verified." : "signature verification failed.");
        }
示例#11
0
        public static bool VerifyDetachedSignature(string filePath, Stream signatureStream, Stream publicKeyStream)
        {
            signatureStream = PgpUtilities.GetDecoderStream(signatureStream);

            PgpObjectFactory pgpFactory = new PgpObjectFactory(signatureStream);
            PgpObject        pgpObject  = pgpFactory.NextPgpObject();
            PgpSignatureList signatureList;

            if (pgpObject is PgpCompressedData pgpCompressedData)
            {
                PgpCompressedData compressedData = pgpCompressedData;
                pgpFactory = new PgpObjectFactory(compressedData.GetDataStream());

                signatureList = (PgpSignatureList)pgpFactory.NextPgpObject();
            }
            else
            {
                signatureList = (PgpSignatureList)pgpObject;
            }

            PgpPublicKeyRingBundle keyRingBundle = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream));

            using (Stream inputFileStream = File.OpenRead(filePath))
            {
                PgpSignature signature = signatureList[0];
                PgpPublicKey publicKey = keyRingBundle.GetPublicKey(signature.KeyId);

                signature.InitVerify(publicKey);

                int ch;
                while ((ch = inputFileStream.ReadByte()) >= 0)
                {
                    signature.Update((byte)ch);
                }

                return(signature.Verify());
            }
        }
示例#12
0
        private void DoTestMasterKey()
        {
            PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeyMaster, false),
                                                                    "test".ToCharArray());

            byte[] msg = Encoding.UTF8.GetBytes("hello world!");

            PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);

            signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null));
            signGen.Update(msg);
            PgpSignature sig = signGen.Generate();

            PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey();

            sig.InitVerify(publicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }
        }
        /*
         * verify a clear text signed file
         */
        private static void VerifyFile(
            Stream inputStream,
            Stream keyIn,
            string resultName)
        {
            ArmoredInputStream aIn    = new ArmoredInputStream(inputStream);
            Stream             outStr = File.Create(resultName);

            //
            // write out signed section using the local line separator.
            // note: trailing white space needs to be removed from the end of
            // each line RFC 4880 Section 7.1
            //
            MemoryStream lineOut   = new MemoryStream();
            int          lookAhead = ReadInputLine(lineOut, aIn);

            byte[] lineSep = LineSeparator;

            if (lookAhead != -1 && aIn.IsClearText())
            {
                byte[] line = lineOut.ToArray();
                outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                outStr.Write(lineSep, 0, lineSep.Length);

                while (lookAhead != -1 && aIn.IsClearText())
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, aIn);

                    line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }
            else
            {
                // a single line file
                if (lookAhead != -1)
                {
                    byte[] line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }

            outStr.Close();

            PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(keyIn);

            PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
            PgpSignatureList p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig     = p3[0];

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

            //
            // read the input, making sure we ignore the last newline.
            //
            Stream sigIn = File.OpenRead(resultName);

            lookAhead = ReadInputLine(lineOut, sigIn);

            ProcessLine(sig, lineOut.ToArray());

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

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

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

            sigIn.Close();

            if (sig.Verify())
            {
                Console.WriteLine("signature verified.");
            }
            else
            {
                Console.WriteLine("signature verification failed.");
            }
        }
示例#14
0
 private static bool VerifySignature(PgpPublicKey publicKey, string payload, PgpSignature signature)
 {
     signature.InitVerify(publicKey);
     signature.Update(Encoding.UTF8.GetBytes(payload));
     return(signature.Verify());
 }
示例#15
0
 private static bool IsGoodUidSignature(PgpSignature sig, PgpPublicKey masterpk, string uid)
 {
     sig.InitVerify(masterpk);
     return sig.VerifyCertification(uid, masterpk);
 }
示例#16
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();
        }
示例#17
0
        public static void AddSignature(PgpPublicKey key, KeyStoreDB keyDb, string keyExportName, PgpSecretKey secKey, char[] passPhrase,
                                        SignatureOperation op, DateTime expiryDate, PgpSignature certLevel = null, string userId = "")
        {
            string fileData = string.Empty;
            bool   useTemp  = true;

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (keyDb == null)
            {
                throw new ArgumentNullException("keyDb");
            }
            if (!Enum.IsDefined(typeof(SignatureOperation), op))
            {
                throw new ArgumentOutOfRangeException(string.Format("op: {0}", op));
            }

            AlgorithmAgreement algorithms = new AlgorithmAgreement(new List <PgpPublicKey>()
            {
                key
            });
            PgpPrivateKey         privateKey = secKey.ExtractPrivateKey(passPhrase);
            PgpSignatureGenerator sigGen     = new PgpSignatureGenerator(key.Algorithm, algorithms.AgreedHashAlgorithm);

            switch (op)
            {
            case SignatureOperation.AddUserId:
                break;

            case SignatureOperation.RevokeKey:
                MemoryStream mStream = new MemoryStream();
                using (ArmoredOutputStream outArmour = new ArmoredOutputStream(mStream)) {
                    outArmour.SetHeader("Version", "Lynx Privacy");
                    sigGen.InitSign(PgpSignature.KeyRevocation, privateKey);
                    PgpSignature sig = sigGen.GenerateCertification(secKey.PublicKey);
                    PgpPublicKey.AddCertification(secKey.PublicKey, sig);
                    sig.InitVerify(secKey.PublicKey);
                    if (!sig.VerifyCertification(secKey.PublicKey))
                    {
                        throw new PgpException("revocation verification failed.");
                    }
                    sig.Encode(outArmour);
                    outArmour.Close();
                }
                mStream.Position = 0;
                StreamReader srdr   = new StreamReader(mStream);
                string       armour = srdr.ReadToEnd();
                string       outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK")
                                      .Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK");
                mStream.Close();
                if (string.IsNullOrEmpty(keyExportName))
                {
                    useTemp = true;
                    string tempPath = Path.GetTempPath();
                    keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp");
                }
                File.WriteAllText(keyExportName, outstr);
                keyExportName = "";
                //Debug.Assert(secKey.PublicKey.IsRevoked() == true);
                break;

            case SignatureOperation.SetKeyExpiry:
                break;

            case SignatureOperation.CertifyKey:
                break;

            default:
                break;
            }


            if (secKey.PublicKey != null)
            {
                if (string.IsNullOrEmpty(keyExportName))
                {
                    useTemp = true;
                    string tempPath = Path.GetTempPath();
                    keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp");
                }
                ExportKey expKey = new ExportKey(keyDb);
                expKey.UpdateDbSecretKey(secKey, keyExportName);
                if (useTemp)
                {
                    //File.Delete(keyExportName);
                }
            }
        }
        private void messageTest(
            string message,
            string type)
        {
            ArmoredInputStream aIn = new ArmoredInputStream(
                new MemoryStream(Encoding.ASCII.GetBytes(message)));

            string[] headers = aIn.GetArmorHeaders();

            if (headers == null || headers.Length != 1)
            {
                Fail("wrong number of headers found");
            }

            if (!"Hash: SHA256".Equals(headers[0]))
            {
                Fail("header value wrong: " + headers[0]);
            }

            //
            // read the input, making sure we ingore the last newline.
            //
            MemoryStream bOut = new MemoryStream();
            int          ch;

            while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText())
            {
                bOut.WriteByte((byte)ch);
            }

            PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey);

            PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
            PgpSignatureList p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig     = p3[0];

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

            MemoryStream lineOut   = new MemoryStream();
            Stream       sigIn     = new MemoryStream(bOut.ToArray(), false);
            int          lookAhead = ReadInputLine(lineOut, sigIn);

            ProcessLine(sig, lineOut.ToArray());

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

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

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

            if (!sig.Verify())
            {
                Fail("signature failed to verify m_in " + type);
            }
        }
示例#19
0
        /// <summary>
        /// Verifies clear text PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifyClearTextSignature Returns: Object {string FilePath, Boolean Verified}
        /// </summary>
        public static Result PGPVerifyClearTextSignFile(Input input)
        {
            Stream             inStr  = File.OpenRead(input.InputFile);
            ArmoredInputStream aIn    = new ArmoredInputStream(inStr);
            Stream             outStr = File.Create(input.OutputFile);

            //
            // write out signed section using the local line separator.
            // note: trailing white space needs to be removed from the end of
            // each line RFC 4880 Section 7.1
            //
            MemoryStream lineOut   = new MemoryStream();
            int          lookAhead = ReadInputLine(lineOut, aIn);

            byte[] lineSep = Encoding.ASCII.GetBytes(Environment.NewLine);;


            if (lookAhead != -1 && aIn.IsClearText())
            {
                byte[] line = lineOut.ToArray();
                outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                outStr.Write(lineSep, 0, lineSep.Length);

                while (lookAhead != -1 && aIn.IsClearText())
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, aIn);

                    line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }
            else
            {
                // a single line file
                if (lookAhead != -1)
                {
                    byte[] line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }
            outStr.Close();

            PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile)));

            PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
            PgpSignatureList p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig     = p3[0];

            inStr.Close();

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));
            // read the input, making sure we ignore the last newline.
            Stream sigIn = File.OpenRead(input.OutputFile);

            lookAhead = ReadInputLine(lineOut, sigIn);
            ProcessLine(sig, lineOut.ToArray());
            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

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

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

            bool verified = sig.Verify();

            sigIn.Close();
            Result ret = new Result
            {
                FilePath = input.OutputFile,
                Verified = verified
            };

            return(ret);
        }
示例#20
0
        private void GenerateAndSign()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

            PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow);

            byte[] msg = Encoding.ASCII.GetBytes("hello world!");

            //
            // try a signature
            //
            PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);

            signGen.InitSign(PgpSignature.BinaryDocument, ecdsaKeyPair.PrivateKey);

            signGen.Update(msg);

            PgpSignature sig = signGen.Generate();

            sig.InitVerify(ecdsaKeyPair.PublicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }

            //
            // generate a key ring
            //
            char[] passPhrase = "test".ToCharArray();
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair,
                                                                     "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();
            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());

            if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded()))
            {
                Fail("public key ring encoding failed");
            }

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());

            if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded()))
            {
                Fail("secret key ring encoding failed");
            }


            //
            // try a signature using encoded key
            //
            signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);
            signGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey(passPhrase));
            signGen.Update(msg);

            sig = signGen.Generate();
            sig.InitVerify(secRing.GetSecretKey().PublicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("re-encoded signature failed to verify!");
            }
        }
示例#21
0
        public static bool VerifySig(byte[] asc, string sig, out string message)
        {
            try
            {
                foreach (PgpPublicKey pubkey in new PgpPublicKeyRing(GetStream(asc)).GetPublicKeys().OfType <PgpPublicKey>()) //java madness
                {
                    //AGAIN MADNESS THIS MAKE PERFECT SENSE !
                    ArmoredInputStream sigInput = new ArmoredInputStream(new MemoryStream(Encoding.UTF8.GetBytes(sig)));

                    //
                    // read the input, making sure we ingore the last newline.
                    //
                    int          ch;
                    string       newLine = null;
                    MemoryStream bOut    = new MemoryStream();

                    while ((ch = sigInput.ReadByte()) >= 0 && sigInput.IsClearText())
                    {
                        if (newLine != null)
                        {
                            foreach (var c in newLine)
                            {
                                bOut.WriteByte((byte)c);
                            }
                            newLine = null;
                        }
                        if (ch == '\r')
                        {
                            ch = sigInput.ReadByte();
                            if (ch == '\n')
                            {
                                newLine = "\r\n";
                                continue;
                            }
                        }
                        if (ch == '\n')
                        {
                            newLine = "\n";
                            continue;
                        }

                        bOut.WriteByte((byte)ch);
                    }

                    var toSign = bOut.ToArray();
                    message = Encoding.UTF8.GetString(toSign);

                    PgpObjectFactory pgpObjFactory = new PgpObjectFactory(sigInput);
                    var          list   = (PgpSignatureList)pgpObjFactory.NextPgpObject();
                    PgpSignature pgpSig = list[0];
                    pgpSig.InitVerify(pubkey);
                    pgpSig.Update(toSign);
                    var result = pgpSig.Verify();
                    if (result)
                    {
                        return(result);
                    }
                    Regex endofline = new Regex("[ ]+?(\r?)\n");
                    message = endofline.Replace(message, "$1\n");
                    toSign  = Encoding.UTF8.GetBytes(message);
                    pgpSig.InitVerify(pubkey);
                    pgpSig.Update(toSign);
                    result = pgpSig.Verify();
                    if (result)
                    {
                        return(result);
                    }
                }
            }
            catch //Don't do it at home kids
            {
            }
            message = null;
            return(false);
        }
示例#22
0
 private void InitSignatureVerification(PgpSignature sig) => sig.InitVerify(GetPublicKey(sig.KeyId));