public static PgpSecretKeyRingBundle AddSecretKeyRing(PgpSecretKeyRingBundle bundle, PgpSecretKeyRing secretKeyRing)
    {
        long keyId = secretKeyRing.GetPublicKey().KeyId;

        if (bundle.secretRings.Contains(keyId))
        {
            throw new ArgumentException("Collection already contains a key with a keyId for the passed in ring.");
        }
        IDictionary dictionary = Platform.CreateHashtable(bundle.secretRings);
        IList       list       = Platform.CreateArrayList(bundle.order);

        dictionary[keyId] = secretKeyRing;
        list.Add(keyId);
        return(new PgpSecretKeyRingBundle(dictionary, list));
    }
Beispiel #2
0
        public void ReadSecretKey()
        {
            // reading test extra data - key with edge condition for DSA key password.
            string passPhrase = "0123456789";

            var sKey       = new PgpSecretKeyRing(testPrivKey2);
            var pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase);

            // reading test - aes256 encrypted passphrase.
            sKey       = new PgpSecretKeyRing(aesSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            // reading test - twofish encrypted passphrase.
            sKey       = new PgpSecretKeyRing(twofishSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);
        }
Beispiel #3
0
        public void PerformTest()
        {
            // Read the public key
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);

            DoBasicKeyRingCheck(pubKeyRing);

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

            TestDecrypt(secretKeyRing);

            EncryptDecryptTest(ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256));

            EncryptDecryptTest(new X25519());
        }
 public PgpSecretKeyRingBundle(IEnumerable e)
 {
     secretRings = Platform.CreateHashtable();
     order       = Platform.CreateArrayList();
     foreach (object item in e)
     {
         PgpSecretKeyRing pgpSecretKeyRing = item as PgpSecretKeyRing;
         if (pgpSecretKeyRing == null)
         {
             throw new PgpException(Platform.GetTypeName(item) + " found where PgpSecretKeyRing expected");
         }
         long keyId = pgpSecretKeyRing.GetPublicKey().KeyId;
         secretRings.Add(keyId, pgpSecretKeyRing);
         order.Add(keyId);
     }
 }
        public static void p5_crypto_create_pgp_keypair(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves
            using (new Utilities.ArgsRemover(e.Args, true)) {
                // Retrieving identity (normally an email address) and password
                string identity = e.Args.GetExChildValue <string> ("identity", context);
                string password = e.Args.GetExChildValue <string> ("password", context);
                if (string.IsNullOrEmpty(identity) || string.IsNullOrEmpty(password))
                {
                    throw new LambdaException(
                              "Minimum [identity] and [password] needs to be supplied to create a PGP keypair",
                              e.Args,
                              context);
                }

                // Retrieving other parameters to PGP keypair creation
                DateTime expires        = e.Args.GetExChildValue("expires", context, DateTime.Now.AddYears(3));
                int      strength       = e.Args.GetExChildValue <int> ("strength", context, 4096);
                long     publicExponent = e.Args.GetExChildValue("public-exponent", context, 65537L);
                int      certainty      = e.Args.GetExChildValue("certainty", context, 5);

                // Generate public/secret keys
                PgpKeyRingGenerator generator = GetKeyRingGenerator(
                    context,
                    e.Args,
                    identity,
                    password,
                    expires,
                    strength,
                    publicExponent,
                    certainty);
                PgpPublicKeyRing publicRing = generator.GeneratePublicKeyRing();
                PgpSecretKeyRing secretRing = generator.GenerateSecretKeyRing();

                // Creating GnuPG context to let MimeKit import keys into GnuPG database
                using (var ctx = new GnuPrivacyContext()) {
                    // Saves public keyring
                    ctx.Import(publicRing);

                    // Saves private keyring
                    ctx.Import(secretRing);
                }

                // In case no [seed] was given, we remove the automatically generated seed ...
                e.Args ["seed"].UnTie();
            }
        }
Beispiel #6
0
        private PgpSecretKey FindSuitableKeyForEncryption()
        {
            var  pgpPub   = new PgpPublicKeyRing(testPubKeyRing);
            var  pubKey   = pgpPub.GetPublicKey();
            var  sKey     = new PgpSecretKeyRing(testPrivKeyRing);
            long pgpKeyID = 0;

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (pgpKey.IsEncryptionKey)
                {
                    pgpKeyID = pgpKey.KeyId;
                }
            }

            return(sKey.GetSecretKey(pgpKeyID));
        }
    public static PgpSecretKeyRing CopyWithNewPassword(PgpSecretKeyRing ring, char[] oldPassPhrase, char[] newPassPhrase, SymmetricKeyAlgorithmTag newEncAlgorithm, SecureRandom rand)
    {
        IList list = Platform.CreateArrayList(ring.keys.Count);

        foreach (PgpSecretKey secretKey in ring.GetSecretKeys())
        {
            if (secretKey.IsPrivateKeyEmpty)
            {
                list.Add(secretKey);
            }
            else
            {
                list.Add(PgpSecretKey.CopyWithNewPassword(secretKey, oldPassPhrase, newPassPhrase, newEncAlgorithm, rand));
            }
        }
        return(new PgpSecretKeyRing(list, ring.extraPubKeys));
    }
Beispiel #8
0
        public void StoreKeyPair(PgpSecretKeyRing privateKey, PgpPublicKeyRing publicKey)
        {
            KeyPair      keyPair = new KeyPair();
            MemoryStream stream  = new MemoryStream();

            privateKey.Encode(stream);
            stream.Flush();

            keyPair.PrivateKeyBlob = stream.ToArray();

            stream = new MemoryStream();
            publicKey.Encode(stream);
            stream.Flush();
            keyPair.PublicKeyBlob = stream.ToArray();

            keysdb.StoreKeyPair(keyPair);
        }
Beispiel #9
0
        /// <summary>
        ///     Reads and returns the PGP secret key from the specified input stream.
        /// </summary>
        /// <param name="input">The input stream containing the PGP secret key to be read.</param>
        /// <returns>The retrieved PGP secret key.</returns>
        private static PgpSecretKey ReadSecretKey(Stream input)
        {
            try {
                PgpSecretKeyRingBundle pgpSec       = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(input));
                PgpSecretKeyRing       pgpKeyRing   = pgpSec.GetKeyRings().OfType <PgpSecretKeyRing>().FirstOrDefault();
                PgpSecretKey           pgpSecretKey = pgpKeyRing.GetSecretKeys().OfType <PgpSecretKey>().FirstOrDefault();

                if (pgpSecretKey.IsSigningKey)
                {
                    return(pgpSecretKey);
                }
                else
                {
                    throw new Exception();
                }
            } catch (Exception) {
                throw new PgpKeyValidationException("Can't find a valid signing key in the specified key ring.");
            }
        }
        public HTTPNotificationSender(UsersAPI UsersAPI,
                                      HTTPHostname Hostname,
                                      IPPort?HTTPPort = null,
                                      TimeSpan?SendNotificationsEvery  = null,
                                      Boolean DisableSendNotifications = false,
                                      PgpPublicKeyRing PublicKeyRing   = null,
                                      PgpSecretKeyRing SecretKeyRing   = null,
                                      DNSClient DNSClient = null)

            : base(UsersAPI,
                   SendNotificationsEvery,
                   DisableSendNotifications,
                   PublicKeyRing,
                   SecretKeyRing,
                   DNSClient)

        {
            this.Hostname = Hostname;
            this.HTTPPort = HTTPPort ?? DefaultHTTPPort;
        }
    public static PgpSecretKeyRing RemoveSecretKey(PgpSecretKeyRing secRing, PgpSecretKey secKey)
    {
        IList list = Platform.CreateArrayList(secRing.keys);
        bool  flag = false;

        for (int i = 0; i < list.Count; i++)
        {
            PgpSecretKey pgpSecretKey = (PgpSecretKey)list[i];
            if (pgpSecretKey.KeyId == secKey.KeyId)
            {
                flag = true;
                list.RemoveAt(i);
            }
        }
        if (!flag)
        {
            return(null);
        }
        return(new PgpSecretKeyRing(list, secRing.extraPubKeys));
    }
Beispiel #12
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);

            DoBasicKeyRingCheck(pubKeyRing);

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

            TestDecrypt(secretKeyRing);

            EncryptDecryptTest();

            Generate();
        }
Beispiel #13
0
        public void Generate25519()
        {
            // Generate a master key
            var ecdsa = new Ed25519();
            // Generate an encryption key
            var ecdh = new X25519();

            // Generate a key ring
            var passPhrase = "test";
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(ecdsa, "*****@*****.**", passPhrase);

            keyRingGen.AddSubKey(ecdh);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

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

            Assert.That(pubRing.GetEncoded(), Is.EqualTo(pubRingEnc.GetEncoded()), "public key ring encoding failed");

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

            Assert.That(secRing.GetEncoded(), Is.EqualTo(secRingEnc.GetEncoded()), "secret key ring encoding failed");

            // Extract back the ECDH key and verify the encoded values to ensure correct endianness
            PgpSecretKey  pgpSecretKey = secRing.GetSecretKey(pubRing.GetPublicKey().KeyId);
            PgpPrivateKey pgpPrivKey   = pgpSecretKey.ExtractPrivateKey(passPhrase);

            /*if (!Arrays.AreEqual(((X25519PrivateKeyParameters)kpEnc.Private).GetEncoded(), ((X25519PrivateKeyParameters)pgpPrivKey.Key).GetEncoded()))
             * {
             *  Fail("private key round trip failed");
             * }
             * if (!Arrays.AreEqual(((X25519PublicKeyParameters)kpEnc.Public).GetEncoded(), ((X25519PublicKeyParameters)pgpSecretKey.PublicKey.GetKey()).GetEncoded()))
             * {
             *  Fail("private key round trip failed");
             * }*/
        }
        public static void Main(string[] args)
        {
            PgpSecretKeyRing secRings;

            using (Stream fs = File.OpenRead(args[0]))
            {
                secRings = new PgpSecretKeyRing(PgpUtilities.GetDecoderStream(fs));
            }

            var first = true;

            foreach (PgpSecretKey pgpSec in secRings.GetSecretKeys())
            {
                try
                {
                    var privateKey = pgpSec.ExtractPrivateKey((args.Length > 1 ? args[1] : "").ToCharArray());
                    if (privateKey == null)
                    {
                        Console.Error.WriteLine("No private key detected.");
                    }
                }
                catch (PgpException e)
                {
                    Console.Error.WriteLine("Failed to extract private key: " + e.Message);
                }

                if (first)
                {
                    Console.WriteLine("Key ID: " + pgpSec.KeyId.ToString("X"));
                    first = false;
                }
                else
                {
                    Console.WriteLine("Key ID: " + pgpSec.KeyId.ToString("X") + " (subkey)");
                }


                Console.WriteLine("            Algorithm: " + GetAlgorithm(pgpSec.PublicKey.Algorithm));
                Console.WriteLine("            Fingerprint: " + Hex.ToHexString(pgpSec.PublicKey.GetFingerprint()));
            }
        }
 private static void p5_crypto_import_private_pgp_key(ApplicationContext context, ActiveEventArgs e)
 {
     // House cleaning
     using (new ArgsRemover(e.Args, true)) {
         // Creating new GnuPG context
         using (var ctx = new GnuPrivacyContext(true)) {
             // Looping through each public key (in ascii armored format) and importing into GnuPG database
             foreach (var idxKey in XUtil.Iterate <string> (context, e.Args))
             {
                 // Creating armored input stream to wrap key
                 using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(idxKey.Replace("\r\n", "\n")))) {
                     using (var armored = new ArmoredInputStream(memStream)) {
                         var key = new PgpSecretKeyRing(armored);
                         ctx.Import(key);
                         e.Args.Add(BitConverter.ToString(key.GetPublicKey().GetFingerprint()).Replace("-", ""));
                     }
                 }
             }
         }
     }
 }
Beispiel #16
0
        public override void PerformTest()
        {
            PgpSecretKeyRing pgpSecRing  = new PgpSecretKeyRing(pgpPrivateFull);
            PgpSecretKey     pgpSecKey   = pgpSecRing.GetSecretKey();
            bool             isFullEmpty = pgpSecKey.IsPrivateKeyEmpty;

            pgpSecRing = new PgpSecretKeyRing(pgpPrivateEmpty);
            pgpSecKey  = pgpSecRing.GetSecretKey();
            bool isEmptyEmpty = pgpSecKey.IsPrivateKeyEmpty;

            //
            // Check isPrivateKeyEmpty() is public
            //

            if (isFullEmpty || !isEmptyEmpty)
            {
                Fail("Empty private keys not detected correctly.");
            }

            //
            // Check copyWithNewPassword doesn't throw an exception for secret
            // keys without private keys (PGPException: unknown S2K type: 101).
            //

            SecureRandom rand = new SecureRandom();

            try
            {
                PgpSecretKey pgpChangedKey = PgpSecretKey.CopyWithNewPassword(pgpSecKey,
                                                                              pgpOldPass.ToCharArray(), pgpNewPass.ToCharArray(), pgpSecKey.KeyEncryptionAlgorithm, rand);
            }
            catch (PgpException e)
            {
                if (!e.Message.Equals("no private key in this SecretKey - public key present only."))
                {
                    Fail("wrong exception.");
                }
            }
        }
        protected ANotificationSender(UsersAPI UsersAPI,
                                      TimeSpan?SendNotificationsEvery  = null,
                                      Boolean DisableSendNotifications = false,
                                      PgpPublicKeyRing PublicKeyRing   = null,
                                      PgpSecretKeyRing SecretKeyRing   = null,
                                      DNSClient DNSClient = null)
        {
            this.UsersAPI = UsersAPI;
            this.DisableSendNotifications = DisableSendNotifications;

            this._SendNotificationsEvery = (UInt32)(SendNotificationsEvery.HasValue
                                                    ? SendNotificationsEvery.Value.TotalSeconds
                                                    : DefaultSendNotificationsEvery.TotalSeconds);

            this.SendNotificationsTimer = new Timer(SendNotifications,
                                                    null,
                                                    _SendNotificationsEvery,
                                                    _SendNotificationsEvery);

            this.LatestNotificationTimestamp = DateTime.MinValue;
            this.DNSClient = DNSClient;
        }
        static void p5_crypto_pgp_keys_private_import(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover(e.Args, true)) {
                // Creating new PGP context.
                using (var ctx = context.RaiseEvent(".p5.crypto.pgp-keys.context.create", new Node("", true)).Get <OpenPgpContext> (context)) {
                    // Looping through each private key (in ascii armored format) and importing into context.
                    foreach (var idxKey in XUtil.Iterate <string> (context, e.Args))
                    {
                        // Creating armored input stream to wrap key.
                        using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(idxKey.Replace("\r\n", "\n")))) {
                            using (var armored = new ArmoredInputStream(memStream)) {
                                var key = new PgpSecretKeyRing(armored);
                                ctx.Import(key);

                                // Returning fingerprint of key that was successfully imported to caller.
                                e.Args.Add(Fingerprint.FingerprintString(key.GetPublicKey().GetFingerprint()));
                            }
                        }
                    }
                }
            }
        }
    public static PgpSecretKeyRing InsertSecretKey(PgpSecretKeyRing secRing, PgpSecretKey secKey)
    {
        IList list  = Platform.CreateArrayList(secRing.keys);
        bool  flag  = false;
        bool  flag2 = false;

        for (int i = 0; i != list.Count; i++)
        {
            PgpSecretKey pgpSecretKey = (PgpSecretKey)list[i];
            if (pgpSecretKey.KeyId == secKey.KeyId)
            {
                flag    = true;
                list[i] = secKey;
            }
            if (pgpSecretKey.IsMasterKey)
            {
                flag2 = true;
            }
        }
        if (!flag)
        {
            if (secKey.IsMasterKey)
            {
                if (flag2)
                {
                    throw new ArgumentException("cannot add a master key to a ring that already has one");
                }
                list.Insert(0, secKey);
            }
            else
            {
                list.Add(secKey);
            }
        }
        return(new PgpSecretKeyRing(list, secRing.extraPubKeys));
    }
Beispiel #20
0
        private void DoTestKey(long keyId, string passphrase)
        {
            PgpSecretKeyRingBundle secretKeyRing = LoadSecretKeyCollection("secring.gpg");

            PgpSecretKeyRing secretKey = secretKeyRing.GetSecretKeyRing(keyId);

            Assert.NotNull(secretKey, "Could not locate secret keyring with Id=" + keyId);

            PgpSecretKey key = secretKey.GetSecretKey();

            Assert.NotNull(key, "Could not locate secret key!");

            try
            {
                PgpPrivateKey privateKey = key.ExtractPrivateKey(passphrase);
                Assert.IsTrue(privateKey.KeyId == keyId);
            }
            catch (PgpException e)
            {
                throw new PgpException("Password incorrect!", e);
            }

            // all fine!
        }
Beispiel #21
0
        public void GenerateAndSign()
        {
            var eddsa = new Ed25519Dsa();

            // generate a key ring
            var passPhrase = "test";
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(eddsa, "*****@*****.**", passPhrase);

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

            KeyTestHelper.SignAndVerifyTestMessage(secRing.GetSecretKey().ExtractPrivateKey(passPhrase), pubRing.GetPublicKey());

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

            Assert.That(pubRing.GetEncoded(), Is.EqualTo(pubRingEnc.GetEncoded()), "public key ring encoding failed");

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

            Assert.That(secRing.GetEncoded(), Is.EqualTo(secRingEnc.GetEncoded()), "secret key ring encoding failed");

            // try a signature using encoded key
            KeyTestHelper.SignAndVerifyTestMessage(secRing.GetSecretKey().ExtractPrivateKey(passPhrase), secRing.GetSecretKey());
        }
Beispiel #22
0
        public void GenerateAndSign()
        {
            var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);

            // generate a key ring
            string passPhrase = "test";
            var    keyRingGen = new PgpKeyRingGenerator(ecdsa, "*****@*****.**", passPhrase);

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

            KeyTestHelper.SignAndVerifyTestMessage(secRing.GetSecretKey().ExtractPrivateKey(passPhrase), pubRing.GetPublicKey());

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

            Assert.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded(), "public key ring encoding failed");

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

            Assert.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded(), "secret key ring encoding failed");

            // try a signature using encoded key
            KeyTestHelper.SignAndVerifyTestMessage(secRing.GetSecretKey().ExtractPrivateKey(passPhrase), secRing.GetSecretKey());
        }
        public static void Main(string[] args)
        {
            PgpSecretKeyRing secRings;
            using (Stream fs = File.OpenRead(args[0]))
            {
                secRings = new PgpSecretKeyRing(PgpUtilities.GetDecoderStream(fs));
            }

            var first = true;
            foreach (PgpSecretKey pgpSec in secRings.GetSecretKeys())
            {
                try
                {
                    var privateKey = pgpSec.ExtractPrivateKey((args.Length > 1 ? args[1] : "").ToCharArray());
                    if(privateKey == null)
                        Console.Error.WriteLine("No private key detected.");
                }
                catch (PgpException e)
                {
                    Console.Error.WriteLine("Failed to extract private key: " + e.Message);
                }

                if (first)
                {
                    Console.WriteLine("Key ID: " + pgpSec.KeyId.ToString("X"));
                    first = false;
                }
                else
                {
                    Console.WriteLine("Key ID: " + pgpSec.KeyId.ToString("X") + " (subkey)");
                }

                Console.WriteLine("            Algorithm: " + GetAlgorithm(pgpSec.PublicKey.Algorithm));
                Console.WriteLine("            Fingerprint: " + Hex.ToHexString(pgpSec.PublicKey.GetFingerprint()));
            }
        }
        public static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                Stream fis = File.OpenRead(args[0]);

                var ring = new PgpPublicKeyRing(
                    PgpUtilities.GetDecoderStream(fis));
                var key = ring.GetPublicKey();

                // iterate through all direct key signautures and look for NotationData subpackets
                foreach (PgpSignature sig in key.GetSignaturesOfType(PgpSignature.DirectKey))
                {
                    Console.WriteLine("Signature date is: "
                        + sig.GetHashedSubPackets().GetSignatureCreationTime());

                    var data = sig.GetHashedSubPackets().GetNotationDataOccurences();

                    for (int i = 0; i < data.Length; i++)
                    {
                        Console.WriteLine("Found Notaion named '" + data[i].GetNotationName()
                            +"' with content '" + data[i].GetNotationValue() + "'.");
                    }
                }

                fis.Close();
            }
            else if (args.Length == 5)
            {
                Stream secFis = File.OpenRead(args[0]);
                Stream pubFis = File.OpenRead(args[2]);

                // gather command line arguments
                PgpSecretKeyRing secRing = new PgpSecretKeyRing(
                    PgpUtilities.GetDecoderStream(secFis));
                String secretKeyPass = args[1];
                PgpPublicKeyRing ring = new PgpPublicKeyRing(
                    PgpUtilities.GetDecoderStream(pubFis));
                String notationName = args[3];
                String notationValue = args[4];

                // create the signed keyRing
                PgpPublicKeyRing sRing = null;
                sRing = new PgpPublicKeyRing(
                    new MemoryStream(
                        SignPublicKey(secRing.GetSecretKey(), secretKeyPass,
                            ring.GetPublicKey(), notationName, notationValue, true),
                        false));
                ring = sRing;

                secFis.Close();
                pubFis.Close();

                Stream fos = File.Create("SignedKey.asc");

                // write the created keyRing to file
                ArmoredOutputStream aOut = new ArmoredOutputStream(fos);
                sRing.Encode(aOut);
                aOut.Close();

                // Note: ArmoredOutputStream.Close() leaves underlying stream open
                fos.Close();
            }
            else
            {
                Console.Error.WriteLine("usage: DirectKeySignature secretKeyFile secretKeyPass publicKeyFile(key to be signed) NotationName NotationValue");
                Console.Error.WriteLine("or: DirectKeySignature signedPublicKeyFile");
            }
        }
Beispiel #25
0
        private void EmbeddedJpegTest()
        {
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);
            PgpSecretKeyRing pgpSec = new PgpSecretKeyRing(testPrivKey);

            PgpPublicKey pubKey = pgpPub.GetPublicKey();

            PgpUserAttributeSubpacketVectorGenerator vGen = new PgpUserAttributeSubpacketVectorGenerator();

            vGen.SetImageAttribute(ImageAttrib.Format.Jpeg, jpegImage);

            PgpUserAttributeSubpacketVector uVec = vGen.Generate();

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

            sGen.InitSign(PgpSignature.PositiveCertification, pgpSec.GetSecretKey().ExtractPrivateKey(pass));

            PgpSignature sig = sGen.GenerateCertification(uVec, pubKey);

            PgpPublicKey nKey = PgpPublicKey.AddCertification(pubKey, uVec, sig);

            int count = 0;
            foreach (PgpUserAttributeSubpacketVector attributes in nKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (PgpSignature s in nKey.GetSignaturesForUserAttribute(attributes))
                {
                    s.InitVerify(pubKey);

                    if (!s.VerifyCertification(attributes, pubKey))
                    {
                        Fail("added signature failed verification");
                    }

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed added user attributes signature check");
                }
                count++;
            }

            if (count != 1)
            {
                Fail("didn't find added user attributes");
            }

            nKey = PgpPublicKey.RemoveCertification(nKey, uVec);

            if (nKey.GetUserAttributes().GetEnumerator().MoveNext())
            {
                Fail("found attributes where none expected");
            }
        }
Beispiel #26
0
        public override void PerformTest()
        {
            PgpPublicKey pubKey = null;

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            pubKey = pgpPub.GetPublicKey();

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey       = new PgpSecretKeyRing(testPrivKey);
            PgpSecretKey     secretKey  = sKey.GetSecretKey();
            PgpPrivateKey    pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // test signature message
            //
            PgpObjectFactory  pgpFact = new PgpObjectFactory(sig1);
            PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();

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

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

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            //
            // signature generation
            //
            GenerateTest(sKey, pubKey, pgpPrivKey);

            //
            // signature generation - canonical text
            //
            const string data = "hello world!";

            byte[]                dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream          bOut      = new MemoryStream();
            MemoryStream          testIn    = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen      = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            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.Text,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            //
            // verify Generated signature - canconical text
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

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

            dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

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

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }

            //
            // Read the public key with user attributes
            //
            pgpPub = new PgpPublicKeyRing(testPubWithUserAttr);

            pubKey = pgpPub.GetPublicKey();

            int count = 0;

            foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes))
                {
                    if (sigs == null)
                    {
                        Fail("null signature found");
                    }

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed user attributes signature check");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes check");
            }

            byte[] pgpPubBytes = pgpPub.GetEncoded();
            pgpPub = new PgpPublicKeyRing(pgpPubBytes);
            pubKey = pgpPub.GetPublicKey();
            count  = 0;

            foreach (object ua in pubKey.GetUserAttributes())
            {
                if (ua == null)
                {
                    Fail("null user attribute found");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes reread");
            }

            //
            // reading test extra data - key with edge condition for DSA key password.
            //
            char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            sKey       = new PgpSecretKeyRing(testPrivKey2);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase);

            //
            // reading test - aes256 encrypted passphrase.
            //
            sKey       = new PgpSecretKeyRing(aesSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // reading test - twofish encrypted passphrase.
            //
            sKey       = new PgpSecretKeyRing(twofishSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // use of PgpKeyPair
            //
            DsaParametersGenerator pGen = new DsaParametersGenerator();

            pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay?
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters        kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA");

            kpg.Init(kgp);


            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa,
                                              kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
        public void PerformTest9()
        {
            PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec9);

            int count = 0;

            byte[] encRing = secretRings1.GetEncoded();

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;

                    PgpPrivateKey pKey = k.ExtractPrivateKey(sec9pass);
                    if (keyCount == 1 && pKey != null)
                    {
                        Fail("primary secret key found, null expected");
                    }
                }

                if (keyCount != 3)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }
        }
        public void PerformTest4()
        {
            PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec4);
            int count = 0;

            byte[] encRing = secretRings1.GetEncoded();

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    k.ExtractPrivateKey(sec3pass1);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }
        }
        public void PerformTest2()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub2);

            int count = 0;

            byte[] encRing = pubRings.GetEncoded();

            pubRings = new PgpPublicKeyRingBundle(encRing);

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey pk in pgpPub2.GetPublicKeys())
                {
                    byte[] pkBytes = pk.GetEncoded();

                    PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes);

                    keyCount++;
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 2)
            {
                Fail("wrong number of public keyrings");
            }

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec2);

            count = 0;

            encRing = secretRings2.GetEncoded();
            PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    PgpPublicKey pk = k.PublicKey;

                    if (pk.KeyId == -1413891222336124627L)
                    {
                        int sCount = 0;

                        foreach (PgpSignature pgpSignature in pk.GetSignaturesOfType(PgpSignature.SubkeyBinding))
                        {
                            int type = pgpSignature.SignatureType;
                            if (type != PgpSignature.SubkeyBinding)
                            {
                                Fail("failed to return correct signature type");
                            }
                            sCount++;
                        }

                        if (sCount != 1)
                        {
                            Fail("failed to find binding signature");
                        }
                    }

                    pk.GetSignatures();

                    if (k.KeyId == -4049084404703773049L
                        || k.KeyId == -1413891222336124627L)
                    {
                        k.ExtractPrivateKey(sec2pass1);
                    }
                    else if (k.KeyId == -6498553574938125416L
                        || k.KeyId == 59034765524361024L)
                    {
                        k.ExtractPrivateKey(sec2pass2);
                    }
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 2)
            {
                Fail("wrong number of secret keyrings");
            }
        }
        private void CheckEccKey(IPgpSecretKeyRing secretKeyRing)
        {
            var keyCount = 0;

            var bytes = secretKeyRing.GetEncoded();

            var pgpSec2 = new PgpSecretKeyRing(bytes);

            foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
            {
                keyCount++;
                var pk = k.PublicKey;

                pk.GetSignatures();

                var pkBytes = pk.GetEncoded();

                var pkR1 = new PgpPublicKeyRing(pkBytes);
                Assert.IsNotNull(pkR1);
                var pk1 = pkR1.GetPublicKey();

                AreEqual(pk1.GetFingerprint(), pk.GetFingerprint());

                var pkBytes1 = pkR1.GetEncoded();

                var pkR2 = new PgpPublicKeyRing(pkBytes1);
                Assert.IsNotNull(pkR2);

                var pkBytes2 = pkR2.GetEncoded();

                AreEqual(pkBytes1, pkBytes2);
            }

            if (keyCount != secretKeyRing.SecretKeyCount)
            {
                Fail("wrong number of secret keys");
            }
        }
Beispiel #31
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!");
            }
        }
Beispiel #32
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!");
            }
        }
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            var pubKey = pgpPub.GetPublicKey();

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey);
            IPgpSecretKey secretKey = sKey.GetSecretKey();
            IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // test signature message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(sig1);
            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();
            pgpFact = new PgpObjectFactory(c1.GetDataStream());

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

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            //
            // signature generation
            //
            GenerateTest(sKey, pubKey, pgpPrivKey);

            //
            // signature generation - canonical text
            //
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream bOut = new MemoryStream();
            MemoryStream testIn = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            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.Text,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            //
            // verify Generated signature - canconical text
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData) pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList) pgpFact.NextPgpObject();

            ops = p1[0];

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

            dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

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

            p3 = (PgpSignatureList) pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }

            //
            // Read the public key with user attributes
            //
            pgpPub = new PgpPublicKeyRing(testPubWithUserAttr);

            pubKey = pgpPub.GetPublicKey();

            int count = 0;
            foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes))
                {
                    if (sigs == null)
                        Fail("null signature found");

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed user attributes signature check");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes check");
            }

            byte[]  pgpPubBytes = pgpPub.GetEncoded();
            pgpPub = new PgpPublicKeyRing(pgpPubBytes);
            pubKey = pgpPub.GetPublicKey();
            count = 0;

            foreach (object ua in pubKey.GetUserAttributes())
            {
                if (ua == null)
                    Fail("null user attribute found");

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes reread");
            }

            //
            // reading test extra data - key with edge condition for DSA key password.
            //
            char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            sKey = new PgpSecretKeyRing(testPrivKey2);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase);

            //
            // reading test - aes256 encrypted passphrase.
            //
            sKey = new PgpSecretKeyRing(aesSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // reading test - twofish encrypted passphrase.
            //
            sKey = new PgpSecretKeyRing(twofishSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // use of PgpKeyPair
            //
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay?
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpg.Init(kgp);

            IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa,
                kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
        public void PerformTest1()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub1);

            int count = 0;

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;
                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey pubKey in pgpPub2.GetPublicKeys())
                {
                    keyCount++;

                    foreach (PgpSignature sig in pubKey.GetSignatures())
                    {
                        if (sig == null)
                            Fail("null signature found");
                    }
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings");
            }

            //
            // exact match
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub3 in pubRings.GetKeyRings("test (Test key) <*****@*****.**>"))
            {
                if (pgpPub3 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings on exact match");
            }

            //
            // partial match 1 expected
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub4 in pubRings.GetKeyRings("test", true))
            {
                if (pgpPub4 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings on partial match 1");
            }

            //
            // partial match 0 expected
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub5 in pubRings.GetKeyRings("XXX", true))
            {
                if (pgpPub5 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 0)
            {
                Fail("wrong number of public keyrings on partial match 0");
            }

            //
            // case-insensitive partial match
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub6 in pubRings.GetKeyRings("*****@*****.**", true, true))
            {
                if (pgpPub6 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings on case-insensitive partial match");
            }

            PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(sec1);
            count = 0;

            foreach (PgpSecretKeyRing pgpSec1 in secretRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    PgpPublicKey pk = k.PublicKey;

                    pk.GetSignatures();

                    byte[] pkBytes = pk.GetEncoded();

                    PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }

            //
            // exact match
            //
            count = 0;
            foreach (PgpSecretKeyRing o1 in secretRings.GetKeyRings("test (Test key) <*****@*****.**>"))
            {
                if (o1 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings on exact match");
            }

            //
            // partial match 1 expected
            //
            count = 0;
            foreach (PgpSecretKeyRing o2 in secretRings.GetKeyRings("test", true))
            {
                if (o2 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings on partial match 1");
            }

            //
            // exact match 0 expected
            //
            count = 0;
            foreach (PgpSecretKeyRing o3 in secretRings.GetKeyRings("test", false))
            {
                if (o3 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 0)
            {
                Fail("wrong number of secret keyrings on partial match 0");
            }

            //
            // case-insensitive partial match
            //
            count = 0;
            foreach (PgpSecretKeyRing o4 in secretRings.GetKeyRings("*****@*****.**", true, true))
            {
                if (o4 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings on case-insensitive partial match");
            }
        }
        public void PerformTest10()
        {
            PgpSecretKeyRing secretRing = new PgpSecretKeyRing(sec10);

            foreach (PgpSecretKey secretKey in secretRing.GetSecretKeys())
            {
                PgpPublicKey pubKey = secretKey.PublicKey;

                if (pubKey.ValidDays != 28)
                {
                    Fail("days wrong on secret key ring");
                }

                if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60)
                {
                    Fail("seconds wrong on secret key ring");
                }
            }

            PgpPublicKeyRing publicRing = new PgpPublicKeyRing(pub10);

            foreach (PgpPublicKey pubKey in publicRing.GetPublicKeys())
            {
                if (pubKey.ValidDays != 28)
                {
                    Fail("days wrong on public key ring");
                }

                if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60)
                {
                    Fail("seconds wrong on public key ring");
                }
            }
        }
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
            PgpPublicKeyRing pgpPub  = (PgpPublicKeyRing)pgpFact.NextPgpObject();

            var pubKey = pgpPub.GetPublicKey();

            if (pubKey.BitStrength != 1024)
            {
                Fail("failed - key strength reported incorrectly.");
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey       = new PgpSecretKeyRing(testPrivKeyRing);
            IPgpSecretKey    secretKey  = sKey.GetSecretKey();
            IPgpPrivateKey   pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // signature generation
            //
            const string data = "hello world!";

            byte[]                dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream          bOut      = new MemoryStream();
            MemoryStream          testIn    = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen      = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa,
                                                                        HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

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

            //
            // verify Generated signature
            //
            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(pubKey);

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

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

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed Generated signature check");
            }

            //
            // test encryption
            //

            //
            // find a key sutiable for encryption
            //
            long pgpKeyID = 0;
            IAsymmetricKeyParameter pKey = null;

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt ||
                    pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral)
                {
                    pKey     = pgpKey.GetKey();
                    pgpKeyID = pgpKey.KeyId;
                    if (pgpKey.BitStrength != 1024)
                    {
                        Fail("failed - key strength reported incorrectly.");
                    }

                    //
                    // verify the key
                    //
                }
            }

            IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding");

            c.Init(true, pKey);

            byte[] inBytes  = Encoding.ASCII.GetBytes("hello world");
            byte[] outBytes = c.DoFinal(inBytes);

            pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

            c.Init(false, pgpPrivKey.Key);

            outBytes = c.DoFinal(outBytes);

            if (!Arrays.AreEqual(inBytes, outBytes))
            {
                Fail("decryption failed.");
            }

            //
            // encrypted message
            //
            byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o',
                            (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l',(byte)'d',  (byte)'!', (byte)'\n' };

            PgpObjectFactory pgpF = new PgpObjectFactory(encMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

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

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            Stream inLd = ld.GetDataStream();

            byte[] bytes = Streams.ReadAll(inLd);

            if (!Arrays.AreEqual(bytes, text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // signed and encrypted message
            //
            pgpF = new PgpObjectFactory(signedAndEncMessage);

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

            ld = (PgpLiteralData)pgpFact.NextPgpObject();

            bOut = new MemoryStream();

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            inLd = ld.GetDataStream();

            //
            // note: we use the DSA public key here.
            //
            ops.InitVerify(pgpPub.GetPublicKey());

            while ((ch = inLd.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
                bOut.WriteByte((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            if (!Arrays.AreEqual(bOut.ToArray(), text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // encrypt
            //
            MemoryStream cbOut            = new MemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.TripleDes, random);
            IPgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey;

            cPk.AddMethod(puK);

            Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length);

            cOut.Write(text, 0, text.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

            clear    = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, text))
            {
                Fail("wrong plain text in Generated packet");
            }

            //
            // use of PgpKeyPair
            //
            IBigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            IBigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            ElGamalParameters elParams = new ElGamalParameters(p, g);

            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");

            kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));

            IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral,
                                              kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;



            // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
            for (int pSize = 257; pSize < 264; ++pSize)
            {
                // Generate some parameters of the given size
                ElGamalParametersGenerator epg = new ElGamalParametersGenerator();
                epg.Init(pSize, 2, random);

                elParams = epg.GenerateParameters();

                kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
                kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));


                // Run a short encrypt/decrypt test with random key for the given parameters
                kp = kpg.GenerateKeyPair();

                PgpKeyPair elGamalKeyPair = new PgpKeyPair(
                    PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow);

                cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);

                puK = elGamalKeyPair.PublicKey;

                cPk.AddMethod(puK);

                cbOut = new MemoryStream();

                cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);

                cOut.Write(text, 0, text.Length);

                cOut.Close();

                pgpF = new PgpObjectFactory(cbOut.ToArray());

                encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

                encP = (PgpPublicKeyEncryptedData)encList[0];

                pgpPrivKey = elGamalKeyPair.PrivateKey;

                // Note: This is where an exception would be expected if the P size causes problems
                clear = encP.GetDataStream(pgpPrivKey);
                byte[] decText = Streams.ReadAll(clear);

                if (!Arrays.AreEqual(text, decText))
                {
                    Fail("decrypted message incorrect");
                }
            }


            // check sub key encoding

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (!pgpKey.IsMasterKey)
                {
                    byte[] kEnc = pgpKey.GetEncoded();

                    PgpObjectFactory objF = new PgpObjectFactory(kEnc);

                    // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing
//					PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject();
//
//					pKey = k.GetKey();
//					pgpKeyID = k.KeyId;
//					if (k.BitStrength != 1024)
//					{
//						Fail("failed - key strength reported incorrectly.");
//					}
//
//					if (objF.NextPgpObject() != null)
//					{
//						Fail("failed - stream not fully parsed.");
//					}
                }
            }
        }
        public void PerformTest3()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub3);

            int count = 0;

            byte[] encRing = pubRings.GetEncoded();

            pubRings = new PgpPublicKeyRingBundle(encRing);

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey pubK in pgpPub2.GetPublicKeys())
                {
                    keyCount++;
                    pubK.GetSignatures();
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings");
            }

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec3);

            count = 0;

            encRing = secretRings2.GetEncoded();

            PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    k.ExtractPrivateKey(sec3pass1);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }
        }
        /**
        * 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");
            }
        }
        public void PerformTest8()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub8);

            int count = 0;

            byte[] encRing = pubRings.GetEncoded();

            pubRings = new PgpPublicKeyRingBundle(encRing);

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey o in pgpPub2.GetPublicKeys())
                {
                    if (o == null)
                        Fail("null key found");

                    keyCount++;
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 2)
            {
                Fail("wrong number of public keyrings");
            }

            PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec8);

            count = 0;

            encRing = secretRings1.GetEncoded();

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    k.ExtractPrivateKey(sec8pass);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }
        }
Beispiel #40
0
        private void TestDecrypt(PgpSecretKeyRing secretKeyRing)
        {
            PgpObjectFactory pgpF = new PgpObjectFactory(testMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpSecretKey secretKey = secretKeyRing.GetSecretKey(); // secretKeyRing.GetSecretKey(encP.KeyId);

    //        PgpPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyEncryptorBuilder());

    //        clear = encP.getDataStream(pgpPrivKey, "BC");
    //
    //        bOut.reset();
    //
    //        while ((ch = clear.read()) >= 0)
    //        {
    //            bOut.write(ch);
    //        }
    //
    //        out = bOut.toByteArray();
    //
    //        if (!AreEqual(out, text))
    //        {
    //            fail("wrong plain text in Generated packet");
    //        }
        }
Beispiel #41
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");
            }
        }
Beispiel #42
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();
        }
Beispiel #43
0
 public void PrivateKeyDecode()
 {
     // Read the private key
     PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey);
     PgpPrivateKey    privKey       = secretKeyRing.GetSecretKey().ExtractPrivateKey(testPasswd);
 }
Beispiel #44
0
		public override void PerformTest()
		{
			PgpPublicKey pubKey = null;

			//
			// Read the public key
			//
			PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
			PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject();

			pubKey = pgpPub.GetPublicKey();

			if (pubKey.BitStrength != 1024)
			{
				Fail("failed - key strength reported incorrectly.");
			}

			//
			// Read the private key
			//
			PgpSecretKeyRing	sKey = new PgpSecretKeyRing(testPrivKeyRing);
			PgpSecretKey		secretKey = sKey.GetSecretKey();
			PgpPrivateKey		pgpPrivKey = secretKey.ExtractPrivateKey(pass);

			//
			// signature generation
			//
			const string data = "hello world!";
			byte[] dataBytes = Encoding.ASCII.GetBytes(data);
			MemoryStream bOut = new MemoryStream();
			MemoryStream testIn = new MemoryStream(dataBytes, false);
			PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa,
				HashAlgorithmTag.Sha1);

			sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

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

			//
			// verify Generated signature
			//
			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(pubKey);

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

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

			if (!ops.Verify(p3[0]))
			{
				Fail("Failed Generated signature check");
			}

			//
			// test encryption
			//

			//
			// find a key sutiable for encryption
			//
			long pgpKeyID = 0;
			AsymmetricKeyParameter pKey = null;

			foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
			{
				if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt
					|| pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral)
				{
					pKey = pgpKey.GetKey();
					pgpKeyID = pgpKey.KeyId;
					if (pgpKey.BitStrength != 1024)
					{
						Fail("failed - key strength reported incorrectly.");
					}

					//
					// verify the key
					//

				}
			}

			IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding");

			c.Init(true, pKey);

			byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
			byte[] outBytes = c.DoFinal(inBytes);

			pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

			c.Init(false, pgpPrivKey.Key);

			outBytes = c.DoFinal(outBytes);

			if (!Arrays.AreEqual(inBytes, outBytes))
			{
				Fail("decryption failed.");
			}

			//
			// encrypted message
			//
			byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o',
								(byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' };

			PgpObjectFactory pgpF = new PgpObjectFactory(encMessage);

			PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

			PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

			Stream clear = encP.GetDataStream(pgpPrivKey);

			pgpFact = new PgpObjectFactory(clear);

			c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

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

			if (!ld.FileName.Equals("test.txt"))
			{
				throw new Exception("wrong filename in packet");
			}

			Stream inLd = ld.GetDataStream();
			byte[] bytes = Streams.ReadAll(inLd);

			if (!Arrays.AreEqual(bytes, text))
			{
				Fail("wrong plain text in decrypted packet");
			}

			//
			// signed and encrypted message
			//
			pgpF = new PgpObjectFactory(signedAndEncMessage);

			encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

			encP = (PgpPublicKeyEncryptedData)encList[0];

			clear = encP.GetDataStream(pgpPrivKey);

			pgpFact = new PgpObjectFactory(clear);

			c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

			p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

			ops = p1[0];

			ld = (PgpLiteralData)pgpFact.NextPgpObject();

			bOut = new MemoryStream();

			if (!ld.FileName.Equals("test.txt"))
			{
				throw new Exception("wrong filename in packet");
			}

			inLd = ld.GetDataStream();

			//
			// note: we use the DSA public key here.
			//
			ops.InitVerify(pgpPub.GetPublicKey());

			while ((ch = inLd.ReadByte()) >= 0)
			{
				ops.Update((byte) ch);
				bOut.WriteByte((byte) ch);
			}

			p3 = (PgpSignatureList)pgpFact.NextPgpObject();

			if (!ops.Verify(p3[0]))
			{
				Fail("Failed signature check");
			}

			if (!Arrays.AreEqual(bOut.ToArray(), text))
			{
				Fail("wrong plain text in decrypted packet");
			}

			//
			// encrypt
			//
			MemoryStream cbOut = new MemoryStream();
			PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.TripleDes, random);
			PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey;

			cPk.AddMethod(puK);

			Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length);

			cOut.Write(text, 0, text.Length);

			cOut.Close();

			pgpF = new PgpObjectFactory(cbOut.ToArray());

			encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

			encP = (PgpPublicKeyEncryptedData)encList[0];

			pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

			clear = encP.GetDataStream(pgpPrivKey);
			outBytes = Streams.ReadAll(clear);

			if (!Arrays.AreEqual(outBytes, text))
			{
				Fail("wrong plain text in Generated packet");
			}

			//
			// use of PgpKeyPair
			//
			BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
			BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

			ElGamalParameters elParams = new ElGamalParameters(p, g);

			IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
			kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));

			AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

			PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral ,
				kp.Public, kp.Private, DateTime.UtcNow);

			PgpPublicKey k1 = pgpKp.PublicKey;
			PgpPrivateKey k2 = pgpKp.PrivateKey;





			// Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
			for (int pSize = 257; pSize < 264; ++pSize)
			{
				// Generate some parameters of the given size
				ElGamalParametersGenerator epg = new ElGamalParametersGenerator();
				epg.Init(pSize, 2, random);

				elParams = epg.GenerateParameters();

				kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
				kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));


				// Run a short encrypt/decrypt test with random key for the given parameters
				kp = kpg.GenerateKeyPair();

				PgpKeyPair elGamalKeyPair = new PgpKeyPair(
					PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow);

				cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);

				puK = elGamalKeyPair.PublicKey;

				cPk.AddMethod(puK);

				cbOut = new MemoryStream();

				cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);

				cOut.Write(text, 0, text.Length);

				cOut.Close();

				pgpF = new PgpObjectFactory(cbOut.ToArray());

				encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

				encP = (PgpPublicKeyEncryptedData)encList[0];

				pgpPrivKey = elGamalKeyPair.PrivateKey;

				// Note: This is where an exception would be expected if the P size causes problems
				clear = encP.GetDataStream(pgpPrivKey);
				byte[] decText = Streams.ReadAll(clear);

				if (!Arrays.AreEqual(text, decText))
				{
					Fail("decrypted message incorrect");
				}
			}


			// check sub key encoding

			foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
			{
				if (!pgpKey.IsMasterKey)
				{
					byte[] kEnc = pgpKey.GetEncoded();

					PgpObjectFactory objF = new PgpObjectFactory(kEnc);

					// TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing
//					PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject();
//
//					pKey = k.GetKey();
//					pgpKeyID = k.KeyId;
//					if (k.BitStrength != 1024)
//					{
//						Fail("failed - key strength reported incorrectly.");
//					}
//
//					if (objF.NextPgpObject() != null)
//					{
//						Fail("failed - stream not fully parsed.");
//					}
                }
            }
		}
Beispiel #45
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);

            DoBasicKeyRingCheck(pubKeyRing);

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

            TestDecrypt(secretKeyRing);

            EncryptDecryptTest();

            Generate();
        }
Beispiel #46
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            AsymmetricKeyParameter pubKey = pgpPub.GetPublicKey().GetKey();

            IEnumerator enumerator = pgpPub.GetPublicKey().GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            string uid = (string) enumerator.Current;


            enumerator = pgpPub.GetPublicKey().GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            PgpSignature sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(pgpPub.GetPublicKey());

            if (!sig.VerifyCertification(uid, pgpPub.GetPublicKey()))
            {
                Fail("failed to verify certification");
            }

            //
            // write a public key
            //
            MemoryStream bOut = new UncloseableMemoryStream();
            BcpgOutputStream pOut = new BcpgOutputStream(bOut);

            pgpPub.Encode(pOut);

            if (!Arrays.AreEqual(bOut.ToArray(), testPubKey))
            {
                Fail("public key rewrite failed");
            }

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3);
            AsymmetricKeyParameter pubKeyV3 = pgpPub.GetPublicKey().GetKey();

            //
            // write a V3 public key
            //
            bOut = new UncloseableMemoryStream();
            pOut = new BcpgOutputStream(bOut);

            pgpPubV3.Encode(pOut);

            //
            // Read a v3 private key
            //
            char[] passP = "FIXCITY_QA".ToCharArray();

            {
                PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3);
                PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey();
                PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP);

                //
                // write a v3 private key
                //
                bOut = new UncloseableMemoryStream();
                pOut = new BcpgOutputStream(bOut);

                pgpPriv2.Encode(pOut);

                byte[] result = bOut.ToArray();
                if (!Arrays.AreEqual(result, testPrivKeyV3))
                {
                    Fail("private key V3 rewrite failed");
                }
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey);
            PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass);

            //
            // write a private key
            //
            bOut = new UncloseableMemoryStream();
            pOut = new BcpgOutputStream(bOut);

            pgpPriv.Encode(pOut);

            if (!Arrays.AreEqual(bOut.ToArray(), testPrivKey))
            {
                Fail("private key rewrite failed");
            }

            //
            // test encryption
            //
            IBufferedCipher c = CipherUtilities.GetCipher("RSA");

//                c.Init(Cipher.ENCRYPT_MODE, pubKey);
            c.Init(true, pubKey);

            byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
            byte[] outBytes = c.DoFinal(inBytes);

//                c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey());
            c.Init(false, pgpPrivKey.Key);

            outBytes = c.DoFinal(outBytes);

            if (!Arrays.AreEqual(inBytes, outBytes))
            {
                Fail("decryption failed.");
            }

            //
            // test signature message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(sig1);

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            PgpOnePassSignature ops = p1[0];

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

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pgpPub.GetPublicKey(ops.KeyId));

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

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

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            //
            // encrypted message - read subkey
            //
            pgpPriv = new PgpSecretKeyRing(subKey);

            //
            // encrypted message
            //
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            PgpObjectFactory pgpF = new PgpObjectFactory(enc1);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            Stream clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

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

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            Stream inLd = ld.GetDataStream();
            byte[] bytes = Streams.ReadAll(inLd);

            if (!Arrays.AreEqual(bytes, text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // encrypt - short message
            //
            byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };

            MemoryStream cbOut = new UncloseableMemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
            PgpPublicKey puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey;

            cPk.AddMethod(puK);

            Stream cOut = cPk.Open(new UncloseableStream(cbOut), shortText.Length);

            cOut.Write(shortText, 0, shortText.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            if (encP.GetSymmetricAlgorithm(pgpPrivKey) != SymmetricKeyAlgorithmTag.Cast5)
            {
                Fail("symmetric algorithm mismatch");
            }

            clear = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, shortText))
            {
                Fail("wrong plain text in generated short text packet");
            }

            //
            // encrypt
            //
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
            puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey;

            cPk.AddMethod(puK);

            cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);

            cOut.Write(text, 0, text.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            clear = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, text))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // read public key with sub key.
            //
            pgpF = new PgpObjectFactory(subPubKey);
            object o;
            while ((o = pgpFact.NextPgpObject()) != null)
            {
                // TODO Should something be tested here?
                // Console.WriteLine(o);
            }

            //
            // key pair generation - CAST5 encryption
            //
            char[] passPhrase = "hello".ToCharArray();
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25);

            kpg.Init(genParam);


            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpSecretKey secretKey = new PgpSecretKey(
                PgpSignature.DefaultCertification,
                PublicKeyAlgorithmTag.RsaGeneral,
                kp.Public,
                kp.Private,
                DateTime.UtcNow,
                "fred",
                SymmetricKeyAlgorithmTag.Cast5,
                passPhrase,
                null,
                null,
                new SecureRandom()
                );

            PgpPublicKey key = secretKey.PublicKey;


            enumerator = key.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            uid = (string) enumerator.Current;


            enumerator = key.GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(uid, key))
            {
                Fail("failed to verify certification");
            }

            pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase);

            key = PgpPublicKey.RemoveCertification(key, uid, sig);

            if (key == null)
            {
                Fail("failed certification removal");
            }

            byte[] keyEnc = key.GetEncoded();

            key = PgpPublicKey.AddCertification(key, uid, sig);

            keyEnc = key.GetEncoded();

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

            sGen.InitSign(PgpSignature.KeyRevocation, secretKey.ExtractPrivateKey(passPhrase));

            sig = sGen.GenerateCertification(key);

            key = PgpPublicKey.AddCertification(key, sig);

            keyEnc = key.GetEncoded();

            PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc);

            key = tmpRing.GetPublicKey();

            IEnumerator sgEnum = key.GetSignaturesOfType(PgpSignature.KeyRevocation).GetEnumerator();
            sgEnum.MoveNext();
            sig = (PgpSignature) sgEnum.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(key))
            {
                Fail("failed to verify revocation certification");
            }

            //
            // use of PgpKeyPair
            //
            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral,
                kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;

            k1.GetEncoded();

            MixedTest(k2, k1);

            //
            // key pair generation - AES_256 encryption.
            //
            kp = kpg.GenerateKeyPair();

            secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom());

            secretKey.ExtractPrivateKey(passPhrase);

            secretKey.Encode(new UncloseableMemoryStream());

            //
            // secret key password changing.
            //
            const string newPass = "******";

            secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass.ToCharArray(), secretKey.KeyEncryptionAlgorithm, new SecureRandom());

            secretKey.ExtractPrivateKey(newPass.ToCharArray());

            secretKey.Encode(new UncloseableMemoryStream());

            key = secretKey.PublicKey;

            key.Encode(new UncloseableMemoryStream());


            enumerator = key.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            uid = (string) enumerator.Current;


            enumerator = key.GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(uid, key))
            {
                Fail("failed to verify certification");
            }

            pgpPrivKey = secretKey.ExtractPrivateKey(newPass.ToCharArray());

            //
            // signature generation
            //
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);

            bOut = new UncloseableMemoryStream();

            MemoryStream testIn = new MemoryStream(dataBytes, false);

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

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

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

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

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

            dIn = p2.GetInputStream();

            ops.InitVerify(secretKey.PublicKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }

            //
            // signature generation - version 3
            //
            bOut = new UncloseableMemoryStream();

            testIn = new MemoryStream(dataBytes);
            PgpV3SignatureGenerator sGenV3 = new PgpV3SignatureGenerator(
                PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

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

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

            lGen = new PgpLiteralDataGenerator();
            lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte) ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

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

            dIn = p2.GetInputStream();

            ops.InitVerify(secretKey.PublicKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed v3 generated signature check");
            }

            //
            // extract PGP 8 private key
            //
            pgpPriv = new PgpSecretKeyRing(pgp8Key);

            secretKey = pgpPriv.GetSecretKey();

            pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass);

            //
            // other sig tests
            //
            PerformTestSig(HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey);
            PerformTestSig(HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey);
            PerformTestSig(HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey);
            FingerPrintTest();
            ExistingEmbeddedJpegTest();
            EmbeddedJpegTest();
        }
Beispiel #47
0
        private void Generate()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            //
            // Generate a master key
            //
            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);

            //
            // Generate an encryption key
            //
            keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

            PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow);

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

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

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

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
Beispiel #48
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!");
            }
        }
Beispiel #49
0
        public void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            var firstUserId = pgpPub.GetPublicKey().GetUserIds().FirstOrDefault();

            Assert.NotNull(firstUserId);
            Assert.AreEqual(1, firstUserId.SelfCertifications.Count);
            Assert.IsTrue(firstUserId.SelfCertifications[0].Verify());

            //
            // write a public key
            //
            MemoryStream bOut = new MemoryStream();

            pgpPub.Encode(bOut);
            Assert.AreEqual(testPubKey, bOut.ToArray());

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3);

            //
            // write a V3 public key
            //
            bOut = new MemoryStream();

            pgpPubV3.Encode(bOut);

            //
            // Read a v3 private key
            //
            var passP = "FIXCITY_QA";

            {
                PgpSecretKeyRing pgpPriv2         = new PgpSecretKeyRing(testPrivKeyV3);
                PgpSecretKey     pgpPrivSecretKey = pgpPriv2.GetSecretKey();
                PgpPrivateKey    pgpPrivKey2      = pgpPrivSecretKey.ExtractPrivateKey(passP);

                //
                // write a v3 private key
                //
                bOut = new MemoryStream();
                pgpPriv2.Encode(bOut);
                byte[] result = bOut.ToArray();
                Assert.AreEqual(testPrivKeyV3, result);
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing pgpPriv    = new PgpSecretKeyRing(testPrivKey);
            PgpPrivateKey    pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass);

            //
            // write a private key
            //
            bOut = new MemoryStream();
            pgpPriv.Encode(bOut);
            Assert.AreEqual(testPrivKey, bOut.ToArray());

            //
            // test encryption
            //

            /*var c = pubKey;
             *
             * //                c.Init(Cipher.ENCRYPT_MODE, pubKey);
             *
             * byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
             * byte[] outBytes = c.DoFinal(inBytes);
             *
             * //                c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey());
             * c.Init(false, pgpPrivKey.Key);
             *
             * outBytes = c.DoFinal(outBytes);
             *
             * if (!Arrays.AreEqual(inBytes, outBytes))
             * {
             *  Fail("decryption failed.");
             * }*/

            //
            // test signature message
            //
            var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(sig1);
            var signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            var literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();

            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.True(signedMessage.Verify(pgpPub.GetPublicKey(signedMessage.KeyId)));

            //
            // encrypted message - read subkey
            //
            pgpPriv = new PgpSecretKeyRing(subKey);

            //
            // encrypted message
            //
            byte[] text             = Encoding.ASCII.GetBytes("hello world!\n");
            var    encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(enc1);

            var encKeyId = encryptedMessage.KeyIds.First();

            pgpPrivKey        = pgpPriv.GetSecretKey(encKeyId).ExtractPrivateKey(pass);
            compressedMessage = (PgpCompressedMessage)encryptedMessage.DecryptMessage(pgpPrivKey);
            literalMessage    = (PgpLiteralMessage)compressedMessage.ReadMessage();
            Assert.AreEqual("test.txt", literalMessage.FileName);
            byte[] bytes = Streams.ReadAll(literalMessage.GetStream());
            Assert.AreEqual(text, bytes);

            //
            // encrypt - short message
            //
            byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };

            MemoryStream cbOut = new MemoryStream();

            var messageGenerator = new PgpMessageGenerator(cbOut);

            using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5))
            {
                encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId));
                using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow))
                {
                    literalStream.Write(shortText);
                }
            }

            cbOut.Position   = 0;
            encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut);
            pgpPrivKey       = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass);
            //Assert.AreEqual(SymmetricKeyAlgorithmTag.Cast5, ((PgpPublicKeyEncryptedData)encryptedMessage.Methods[0]).GetSymmetricAlgorithm(pgpPrivKey));
            literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey);
            Assert.AreEqual("", literalMessage.FileName);
            bytes = Streams.ReadAll(literalMessage.GetStream());
            Assert.AreEqual(shortText, bytes);

            //
            // encrypt
            //
            cbOut = new MemoryStream();

            messageGenerator = new PgpMessageGenerator(cbOut);
            using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5))
            {
                encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId));
                using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow))
                {
                    literalStream.Write(text);
                }
            }

            cbOut.Position   = 0;
            encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut);
            pgpPrivKey       = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass);
            literalMessage   = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey);
            bytes            = Streams.ReadAll(literalMessage.GetStream());
            Assert.AreEqual(text, bytes);

            //
            // read public key with sub key.
            //

            /*pgpF = new PgpObjectFactory(subPubKey);
             * object o;
             * while ((o = pgpFact.NextPgpObject()) != null)
             * {
             *  // TODO Should something be tested here?
             *  // Console.WriteLine(o);
             * }*/

            //
            // key pair generation - CAST5 encryption
            //
            var passPhrase = "hello";
            var rsa        = RSA.Create(1024);

            var keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase);

            var secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey();

            PgpPublicKey key = new PgpPublicKey(secretKey);

            firstUserId = key.GetUserIds().FirstOrDefault();
            Assert.NotNull(firstUserId);
            Assert.AreEqual(1, firstUserId.SelfCertifications.Count);
            Assert.IsTrue(firstUserId.SelfCertifications[0].Verify());

            pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase);

            key = PgpPublicKey.RemoveCertification(key, firstUserId, firstUserId.SelfCertifications[0]);
            Assert.NotNull(key);

            byte[] keyEnc = key.GetEncoded();

            key = PgpPublicKey.AddCertification(key, firstUserId.UserId, firstUserId.SelfCertifications[0]);

            keyEnc = key.GetEncoded();

            var revocation = PgpCertification.GenerateKeyRevocation(
                secretKey,
                secretKey.ExtractPrivateKey(passPhrase),
                key);

            key = PgpPublicKey.AddCertification(key, revocation);

            keyEnc = key.GetEncoded();

            PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc);

            key = tmpRing.GetPublicKey();

            revocation = key.KeyCertifications.Where(c => c.SignatureType == PgpSignatureType.KeyRevocation).FirstOrDefault();
            Assert.NotNull(revocation);
            Assert.IsTrue(revocation.Verify(key));

            //
            // use of PgpKeyPair
            //
            PgpKeyPair pgpKp = new PgpKeyPair(rsa, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;

            k1.GetEncoded();

            MixedTest(k2, k1);

            //
            // key pair generation - AES_256 encryption. -- XXX
            //
            //kp = kpg.GenerateKeyPair();
            rsa = RSA.Create(1024);

            keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase /*, encAlgorithm: PgpSymmetricKeyAlgorithm.Aes256*/);

            secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey();

            secretKey.ExtractPrivateKey(passPhrase);

            secretKey.Encode(new MemoryStream());

            //
            // secret key password changing.
            //
            const string newPass = "******";

            secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass);

            secretKey.ExtractPrivateKey(newPass);

            secretKey.Encode(new MemoryStream());

            key = new PgpPublicKey(secretKey);

            key.Encode(new MemoryStream());

            firstUserId = key.GetUserIds().FirstOrDefault();
            Assert.NotNull(firstUserId);
            Assert.AreEqual(1, firstUserId.SelfCertifications.Count);
            Assert.IsTrue(firstUserId.SelfCertifications[0].Verify());

            pgpPrivKey = secretKey.ExtractPrivateKey(newPass);

            //
            // signature generation
            //
            const string data = "hello world!";

            byte[]   dataBytes    = Encoding.ASCII.GetBytes(data);
            DateTime testDateTime = new DateTime(1973, 7, 27);

            bOut             = new MemoryStream();
            messageGenerator = new PgpMessageGenerator(bOut);
            using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip))
                using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1))
                    using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime))
                    {
                        literalStream.Write(dataBytes);
                    }

            //
            // verify generated signature
            //
            bOut.Position     = 0;
            compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut);
            signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();
            Assert.AreEqual(testDateTime, literalMessage.ModificationTime);
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(secretKey));

            //
            // signature generation - version 3
            //
            bOut             = new MemoryStream();
            messageGenerator = new PgpMessageGenerator(bOut);
            using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip))
                using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1, version: 3))
                    using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime))
                    {
                        literalStream.Write(dataBytes);
                    }

            //
            // verify generated signature
            //
            bOut.Position     = 0;
            compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut);
            signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();
            Assert.AreEqual(testDateTime, literalMessage.ModificationTime);
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(secretKey));

            //
            // extract PGP 8 private key
            //
            pgpPriv = new PgpSecretKeyRing(pgp8Key);

            secretKey = pgpPriv.GetSecretKey();

            pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass);

            //
            // other sig tests
            //
            PerformTestSig(PgpHashAlgorithm.Sha256, secretKey, pgpPrivKey);
            PerformTestSig(PgpHashAlgorithm.Sha384, secretKey, pgpPrivKey);
            PerformTestSig(PgpHashAlgorithm.Sha512, secretKey, pgpPrivKey);
        }
Beispiel #50
0
        public void TestMethod1()
        {
            string secretKeyFile = @"-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: BCPG C# v1.7.4137.9688

lQc0BFTbeXUBEACgRx6VZYo0M8Vhv7D+ukhEPAIQHmbv41oae3vCINyEk+qdlkRQ
qa+prxLyM3wvHi2WyUQUG67TgEhOKGiu5iRT3SDf7/o2+GyzkcJxVf4SsauvPNM9
chRtayHhtgNbkz+qS3G+zGgO52ck/W9J4EvxzeMaV+hN9TJm4nurZ52ZxqjxXDX2
9/loc639n/OCQTx3BKNPwt8TE3vaHUi7QScfL3Yj/zL3FDR8ct2Ymh4xWM2GjTb6
3mPWAt0pOfFOS0wxWpWYg9gl3p6iw8Sl7O5cqlxNlpA3b1b4mdF1v96kNfxkT4MI
lNhfeNQ6e9cUZbMSJxt/gzY29xERa7kYpVC5QOgI57VZg/hsO8Uoh55H7LgKQ8Zw
y4IQ/BZxBvMgBMVjYOHyhfC1rx81btPZbMHN6rwQFlXgXc+pbKTSzxmsCh00lc9z
Ib653ByqHLeF4H++T6aU7L15C+8xOuFctF1wYLGjnr6ZX5tZINuyOqq2ifQ0wkkk
xu7Ev/AIhE9oOYmn8HfwbUZOb28FbSqYssxzI76QTaPzOULJ+q/M94Z6WCTyXxHV
uTFbhhlOn6FMK4AbUAseLO34w8rxYuwL50XdUlapW6yCxbtJILa118KxuC3CLxc5
Scfi//yDmlfqc+fYDLQu2173G5+PsSaTAs9xr6tedhRzpuWg63VyOnA3BQARAQAB
/wkDAplemXfJ8EImYBVeK6Wpxj7yffXhSTElCFoRzQYDW1fv6RDytlxLPLHtpAG3
TQJTttt49uctJg6dpOhxS3jsTTST1YCZ5LTAoIbdFtK9gjfjpe9Eb8VCchzoQZxD
wJDggdT3NKSDupbIeqAcCHfdCP33OAdhpi/xDPDmxQ1dpgsOCKGI60YXF1kMfHRF
933oLCq+NwUtv5+hlR+4JQSIrUPwrlJNfzgRZY7lc0YIEuVNgAIpDrwR5xHX2+Bc
5Zamj4ib7A0oXEjgXYw6HehQ4/CSFQ9TZxcUoHDW9LBojGNrRRLs/4rXip5ICdD8
nakeNu9H4OmU1DlD7Y9oeqTabTsVD5cqOzCoJoZUGrsP/BTaNKzbuM4A2c4ZO4vQ
gNegJCD99JxcU4zPJew3gCfhbdWwn98Sq/LdCAsdg2n6+3l82DnKyyA2+iSPg9eA
8rR9/Ui59w/C0GVDNgXw/yljpsmJw/bIVFvzRU1+/wBhQLy+JCIeFSpo4+DHXQS4
B9mQ3tT9ky7mOvyaPMxWXFhsDKqegTi+AX9nlyskXa4ymSIJz8kvo71JRHxnv96E
chHKFrJN1x6StO4O3TqNa8/aTLPU7WJ6AyRJHz/VPSn0jpWJay4W9PJU5enuaMIg
eyzs7Ybm+QIVkuekkfkwhzp4OkGLn5MQJpN5C9+GBwz436Ybsr9FNDzs4nnD/K1f
20B/emJa5qL0NpeGWlBzvhyCyI67pPIgzeFh3gsTDWSuYOYzwcrHSOvePJdjOnDD
fkKm1DPcjcPrLAo/enNET644u6BjY528mA7Wk23C00Vz4KS6sTtReiJZQLnUUrqz
Zbkto8OlGvBrIn+v8auexJdxaYUBwYs21cKzOhqwBhuk9TLgDpxoI5EqVGzVhd3j
GZ37iaWg4irH7R6zXBKpEKWvaqCe6C1O58iyrU6uHnS0Wtd6FkgCBFzHk7uQxULP
E0Otp7dW1FGTi0e3gzHGpIntAieQ+sigA0UQb/Xh/p3DFGGfm+zGBa/pneVeWE7Z
DLfGi51WyoN/+p9MKAIJG9RFYnu0ojzCp2R7POclq0BS1GM00QCsWEnVoD3DY5PW
9qzxXnL9c8SU91V0PD73TxzTK5ntaqeKroKUyoKd3IKuxiYLyQZPv+SP5WqqH57i
+h56hYfbboBo2ktBwxMBULjw7WFX+en99LO5zj8GKQgRMXZCbbF4f+Ho2bjJKREL
6SsL2veNXOdkSIO0vGNaU15lE4FaySaseDrTJsDm+mOeRatL0MYiFLsFTG+u0O28
/rVBQQJsM87wpGfEdjRTsWK4XNMovglMMGlyAKhlQxer77PnKLHjRQLMQBsKElR8
KTTrvs+JrcuzwPAdNLA2krj6PzZVvtmFIzs+uzBCqhOBFMjFxvICDa1de90mfym8
67pdQGwDVBIXAFPO2fkuZ/AktFd8NBLGxzAC3TXQMzCnWRwHqtFkMbfmnBDEJId2
iVwC/bmPJqapM9rn8nFF28pdlbUL1hvbIM7fkVFWc7wkCHgv6DHq8evh6JL5lH/b
+5+It0/eNJoue7tvU/Vk00GzV76dFJ7QHMeJ3OwgVIZDPhGk4YeO6y8fOZDpiI8M
HB5pA+Kb+ha84h1rleauSxkfWkmplBBPFASlDC1jMaFm9lGJ7/du1zYng9tMIouH
OE81netTtzuDRmp6unCOnXdbRWh0qocbUio2qqAguYRDgBhTLHMc9csDzRIlVd7h
uS5Qs8HKajksmagAoDQRsunwJrkDbsm0IlRlc3QgVXNlcjEgPHRlc3R1c2VyMUBl
eGFtcGxlLmNvbT6JAjYEEwECACAFAlTbeXUCGw8FCwkIBwQHFQoJCAsDBgQWAgMB
AwUI/wAKCRBXqPV8Gs4F6i1CD/0WIbuM28s2Pu6isBFLhQmzaWoIvYM0S6S5Hqlv
ubkX3eY4K2oF+hMl5Y0Tlurwdio0kTK12VzeOVaypxGx3dzcP0Ry5xskaDhPFzp0
MdbpPZ4CLQ+NJodfp9az7gbhPlD8gx7ZDdAB9bMOQ6ZgIzeyz3H8MkrO03TJJ2ZQ
/zw8KKfzGzE89hO7z7cX+0UNODY++AbS21+0Cc7eN/DAehe0bjedYg8PPJ/xJ7uL
A+GoSqVuY2ilY2E3A5fw+x57Of8FibUlCx1lyYFaAyQ87kivNSsD9S/PyZ2q516h
GIrQTgk34Pda4qZ/PtWGcJoT6mwHTz85HqBp0NO4/NvJG+ySw5kqVaR0W8yJ7Jat
mqcuSIOyrw9X69uzoIzMNv2vmzN3F3czg5VGRcQVcDU0GVhq8VFUBBhQLUGiNFJM
QO8KIwcFabhhu5ymAGTnyBBfetDr+0pqOLol0WKDFz4IF9DeLnESRqcl00Evx7/o
viUOB7IZCHwFa3yRoyM8ZC2/p3phK8dreV2xPaPyyNbkl0768Spoa7s+59D9MoXC
TP0+SvCeBf8jJpJ6/O/xUAvyPRvyk75+H6kOu0+4G7erK0AABb1WQvmYah1wPzD3
1ptfooPAKf193dtiOC2AoJdGu/oFmffgh0WhcbPCKlHv0zecx0DTGDkAQWAe9L+i
BQ7R6w==
=Z4JC
-----END PGP PRIVATE KEY BLOCK-----";

            File.WriteAllText(Path.Combine(@"C:\Users\John\BcPGP", "testuser1@example_com_secret.asc"), secretKeyFile);
            MemoryStream     msSec   = new MemoryStream(Encoding.UTF8.GetBytes(secretKeyFile));
            PgpSecretKeyRing secRing = new PgpSecretKeyRing(PgpUtilities.GetDecoderStream(msSec));

            char[]           passPhrase = new char[] { 't', 'e', 's', 't', 'u', 's', 'e', 'r' };
            PgpPublicKeyRing pubRing    = new PgpPublicKeyRing(secRing.GetPublicKey().GetEncoded());

            PgpPublicKeyRing newRing = new PgpPublicKeyRing(
                new MemoryStream(RevokePublicKey(secRing.GetSecretKey(), passPhrase, pubRing.GetPublicKey(), true)));

            msSec.Close();
            Assert.IsTrue(newRing.GetPublicKey().IsRevoked());

            Stream fos = File.Create(@"C:\Users\John\BcPGP\RevokedKey.asc");
            ArmoredOutputStream aOut = new ArmoredOutputStream(fos);

            newRing.Encode(aOut);
            aOut.Close();
            fos.Close();

            PgpSecretKey        newSecret = PgpSecretKey.ReplacePublicKey(secRing.GetSecretKey(), newRing.GetPublicKey());
            Stream              foSec     = File.Create(@"C:\Users\John\BcPGP\SecretRevokedKey.asc");
            ArmoredOutputStream sOut      = new ArmoredOutputStream(foSec);

            newSecret.Encode(sOut);
            sOut.Close();
            foSec.Close();
            Assert.IsTrue(newSecret.PublicKey.IsRevoked());
        }
        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();
        }
        public override void PerformTest()
        {
            PgpSecretKeyRing pgpSecRing = new PgpSecretKeyRing(pgpPrivateFull);
            PgpSecretKey pgpSecKey = pgpSecRing.GetSecretKey();
            bool isFullEmpty = pgpSecKey.IsPrivateKeyEmpty;

            pgpSecRing = new PgpSecretKeyRing(pgpPrivateEmpty);
            pgpSecKey = pgpSecRing.GetSecretKey();
            bool isEmptyEmpty = pgpSecKey.IsPrivateKeyEmpty;

            //
            // Check isPrivateKeyEmpty() is public
            //

            if (isFullEmpty || !isEmptyEmpty)
            {
                Fail("Empty private keys not detected correctly.");
            }

            //
            // Check copyWithNewPassword doesn't throw an exception for secret
            // keys without private keys (PGPException: unknown S2K type: 101).
            //

            SecureRandom rand = new SecureRandom();

            try
            {
                PgpSecretKey pgpChangedKey = PgpSecretKey.CopyWithNewPassword(pgpSecKey,
                    pgpOldPass.ToCharArray(), pgpNewPass.ToCharArray(), pgpSecKey.KeyEncryptionAlgorithm, rand);
            }
            catch (PgpException e)
            {
                if (!e.Message.Equals("no private key in this SecretKey - public key present only."))
                {
                    Fail("wrong exception.");
                }
            }
        }