private static void ExportKeyPair(
            Stream secretOut,
            Stream publicOut,
            IAsymmetricCipherKeyPair signingKey,
            IAsymmetricCipherKeyPair encryptionKey,
            string identity,
            char[] passPhrase,
            bool armor,
            ISecureRandom random)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

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

            keyRingGenerator.GenerateSecretKeyRing().Encode(secretOut);

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

            keyRingGenerator.GeneratePublicKeyRing().Encode(publicOut);
            {
                publicOut.Close();
            }
        }
Пример #2
0
        public void Generate()
        {
            // Master/Signing key
            var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            // Encryption key
            var ecdh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);

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

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
        /// <summary>
        /// Create master signing key.
        /// </summary>
        /// <param name="keyRingGen">
        /// Key ring generator.
        /// </param>
        /// <param name="identity">
        /// Identity of the key.
        /// </param>
        /// <param name="password">
        /// Password to protect the secret key.
        /// </param>
        /// <param name="expires">
        /// Key expiry; null means never expires.
        /// </param>
        /// <param name="encryptKeyLength">
        /// Length of the encryption key.
        /// </param>
        /// <param name="encryptGenerator">
        /// Generator for the encryption key.
        /// </param>
        /// <param name="encryptionAlgorithm">
        /// Encryption algorithm.
        /// </param>
        /// <param name="symmetricAlgorithm">
        /// Symmetric algorithm.
        /// </param>
        /// <returns>
        /// Returns the <see cref="PgpKeyRingGenerator"/> with the keyring properties
        /// thus far.
        /// </returns>
        public static PgpKeyRingGenerator CreateEncryptionSubkey(
            PgpKeyRingGenerator keyRingGen,
            string identity,
            string password,
            DateTime?expires,
            int encryptKeyLength    = 2048,
            string encryptGenerator = "RSA",
            PublicKeyAlgorithmTag encryptionAlgorithm   = PublicKeyAlgorithmTag.RsaEncrypt,
            SymmetricKeyAlgorithmTag symmetricAlgorithm = SymmetricKeyAlgorithmTag.Aes256)
        {
            var keyringParameters = new KeyRingParameters(encryptKeyLength, encryptGenerator)
            {
                Password = password,
                Identity = identity,
                PrivateKeyEncryptionAlgorithm = symmetricAlgorithm,
                SymmetricAlgorithms           = new[]
                {
                    SymmetricKeyAlgorithmTag.Aes256,
                    SymmetricKeyAlgorithmTag.Aes192,
                    SymmetricKeyAlgorithmTag.Aes128
                },
                HashAlgorithms = new[]
                {
                    HashAlgorithmTag.Sha256,
                    HashAlgorithmTag.Sha1,
                    HashAlgorithmTag.Sha384,
                    HashAlgorithmTag.Sha512,
                    HashAlgorithmTag.Sha224,
                }
            };

            // encryption key
            var generator = GeneratorUtilities.GetKeyPairGenerator(encryptGenerator);

            generator.Init(keyringParameters.KeyParams);
            var encKeyPair = new PgpKeyPair(encryptionAlgorithm, generator.GenerateKeyPair(), DateTime.UtcNow);

            var symmetricAlgorithms = (from a in keyringParameters.SymmetricAlgorithms
                                       select(int) a).ToArray();
            var hashAlgorithms = (from a in keyringParameters.HashAlgorithms
                                  select(int) a).ToArray();

            Debug.WriteLine("Generated encryption key with ID " + encKeyPair.KeyId.ToString("X"));
            var encSubpckGen = new PgpSignatureSubpacketGenerator();

            encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);
            encSubpckGen.SetPreferredSymmetricAlgorithms(false, symmetricAlgorithms);
            encSubpckGen.SetPreferredHashAlgorithms(false, hashAlgorithms);
            if (expires != null)
            {
                encSubpckGen.SetKeyExpirationTime(false, (long)((DateTime)expires - DateTime.Now).TotalSeconds);
            }

            // add encryption subkey to keyring
            keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null);
            return(keyRingGen);
        }
Пример #4
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);
        }
Пример #5
0
        public static void GenerateKeyPair(string userid, string password, out PgpPublicKeyRing pkr, out PgpSecretKeyRing skr)
        {
            PgpKeyRingGenerator krgen = PGP.generateKeyRingGenerator(userid, password);

            // Generate public key ring, dump to file.
            pkr = krgen.GeneratePublicKeyRing();

            // Generate private key, dump to file.
            skr = krgen.GenerateSecretKeyRing();
        }
Пример #6
0
        PgpKeyRingGenerator CreateKeyRingGenerator(MailboxAddress mailbox, EncryptionAlgorithm algorithm, long expirationTime, string password, DateTime now, SecureRandom random)
        {
            var enabledEncryptionAlgorithms = EnabledEncryptionAlgorithms;
            var enabledDigestAlgorithms     = EnabledDigestAlgorithms;
            var encryptionAlgorithms        = new int[enabledEncryptionAlgorithms.Length];
            var digestAlgorithms            = new int[enabledDigestAlgorithms.Length];

            for (int i = 0; i < enabledEncryptionAlgorithms.Length; i++)
            {
                encryptionAlgorithms[i] = (int)enabledEncryptionAlgorithms[i];
            }
            for (int i = 0; i < enabledDigestAlgorithms.Length; i++)
            {
                digestAlgorithms[i] = (int)enabledDigestAlgorithms[i];
            }

            var parameters       = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), random, 2048, 12);
            var signingAlgorithm = PublicKeyAlgorithmTag.RsaSign;

            var keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            keyPairGenerator.Init(parameters);

            var signingKeyPair = new PgpKeyPair(signingAlgorithm, keyPairGenerator.GenerateKeyPair(), now);

            var subpacketGenerator = new PgpSignatureSubpacketGenerator();

            subpacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify);
            subpacketGenerator.SetPreferredSymmetricAlgorithms(false, encryptionAlgorithms);
            subpacketGenerator.SetPreferredHashAlgorithms(false, digestAlgorithms);

            if (expirationTime > 0)
            {
                subpacketGenerator.SetKeyExpirationTime(false, expirationTime);
                subpacketGenerator.SetSignatureExpirationTime(false, expirationTime);
            }

            subpacketGenerator.SetFeature(false, Org.BouncyCastle.Bcpg.Sig.Features.FEATURE_MODIFICATION_DETECTION);

            var keyRingGenerator = new PgpKeyRingGenerator(
                PgpSignature.PositiveCertification,
                signingKeyPair,
                mailbox.ToString(false),
                GetSymmetricKeyAlgorithm(algorithm),
                CharsetUtils.UTF8.GetBytes(password),
                true,
                subpacketGenerator.Generate(),
                null,
                random);

            // Add the (optional) encryption subkey.
            AddEncryptionKeyPair(keyRingGenerator, parameters, PublicKeyAlgorithmTag.RsaGeneral, now, expirationTime, encryptionAlgorithms, digestAlgorithms);

            return(keyRingGenerator);
        }
Пример #7
0
        public static void p5_crypto_pgp_keys_create(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves.
            using (new ArgsRemover(e.Args, true)) {
                // Retrieving identity (normally a name + email address), in addition to 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, giving them sane defaults if not supplied.
                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);

                // Creating our key generator.
                PgpKeyRingGenerator generator = GetKeyRingGenerator(
                    context,
                    identity,
                    password,
                    expires,
                    strength,
                    publicExponent,
                    certainty);

                // Generating public keyrign.
                PgpPublicKeyRing publicRing = generator.GeneratePublicKeyRing();

                // Generating secret keyring. "Secret key" is BC's name for private key.
                PgpSecretKeyRing secretRing = generator.GenerateSecretKeyRing();

                /*
                 * Retrieving PGP context to let MimeKit import keys into PGP storage.
                 * Making sure we retrieve it in "write mode".
                 */
                using (var ctx = context.RaiseEvent(".p5.crypto.pgp-keys.context.create", new Node("", true)).Get <OpenPgpContext> (context)) {
                    // Saves public keyring.
                    ctx.Import(publicRing);

                    // Saves secret keyring (private key, BC uses different naming convention).
                    ctx.Import(secretRing);
                }

                // Returning fingerprint and key-id to caller.
                e.Args.Add("fingerprint", Fingerprint.FingerprintString(publicRing.GetPublicKey().GetFingerprint()));
                e.Args.Add("key-id", ((int)publicRing.GetPublicKey().KeyId).ToString("X"));
            }
        }
Пример #8
0
        private static PgpKeyRingGenerator GeneratePgpRingKeys(string identity, string password)
        {
            var keyRingParams = new KeyRingParams
            {
                Password = password,
                Identity = identity,
                PrivateKeyEncryptionAlgorithm = SymmetricKeyAlgorithmTag.Aes128,
                SymmetricAlgorithms           = new SymmetricKeyAlgorithmTag[]
                {
                    SymmetricKeyAlgorithmTag.Aes256,
                    SymmetricKeyAlgorithmTag.Aes192,
                    SymmetricKeyAlgorithmTag.Aes128
                },
                HashAlgorithms = new HashAlgorithmTag[]
                {
                    HashAlgorithmTag.Sha256,
                    HashAlgorithmTag.Sha1,
                    HashAlgorithmTag.Sha384,
                    HashAlgorithmTag.Sha512,
                    HashAlgorithmTag.Sha224,
                }
            };

            var generator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(keyRingParams.RsaParams);

            var masterKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.RsaSign, generator.GenerateKeyPair(), DateTime.UtcNow);

            Debug.WriteLine("Generated master key with Id {0}", masterKeyPair.KeyId.ToString("x"));

            var masterSubpckGen = new PgpSignatureSubpacketGenerator();

            masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify);
            masterSubpckGen.SetPreferredSymmetricAlgorithms(false, (from a in keyRingParams.SymmetricAlgorithms select(int) a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false, (from a in keyRingParams.HashAlgorithms select(int) a).ToArray());

            var encKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.UtcNow);

            Debug.WriteLine("Generated encryption key with Id {0}", encKeyPair.KeyId.ToString("x"));

            var encSubpckGen = new PgpSignatureSubpacketGenerator();

            encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);

            masterSubpckGen.SetPreferredSymmetricAlgorithms(false, (from a in keyRingParams.SymmetricAlgorithms select(int) a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false, (from a in keyRingParams.HashAlgorithms select(int) a).ToArray());
            var keyRingGen = new PgpKeyRingGenerator(PgpSignature.DefaultCertification, masterKeyPair, keyRingParams.Identity, keyRingParams.PrivateKeyEncryptionAlgorithm.Value, keyRingParams.GetPassword(), true, masterSubpckGen.Generate(), null, new SecureRandom());

            keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null);

            return(keyRingGen);
        }
Пример #9
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);
        }
Пример #10
0
        public static PgpKeyRingGenerator GenerateKeyRing(String id, byte[] pass, RSAKeySize keysize)
        {
            RsaKeyPairGenerator kpg = new RsaKeyPairGenerator();

            kpg.Init(new KeyGenerationParameters(new SecureRandom(), 4096));

            AsymmetricCipherKeyPair rsakeys = kpg.GenerateKeyPair();

            PgpKeyPair rsakp_sign = new PgpKeyPair(PublicKeyAlgorithmTag.RsaSign, rsakeys, DateTime.UtcNow);
            PgpKeyPair rsakp_enc  = new PgpKeyPair(PublicKeyAlgorithmTag.RsaEncrypt, rsakeys, DateTime.UtcNow);

            PgpSignatureSubpacketGenerator signhashgen = new PgpSignatureSubpacketGenerator();

            signhashgen.SetKeyFlags(false, KeyFlags.SignData | KeyFlags.CertifyOther);
            signhashgen.SetPreferredSymmetricAlgorithms
                (false, new int[] {
                (int)SymmetricKeyAlgorithmTag.Aes256,
                (int)SymmetricKeyAlgorithmTag.Camellia256
            });

            signhashgen.SetPreferredHashAlgorithms
                (false, new int[] {
                (int)HashAlgorithmTag.Sha256,
                (int)HashAlgorithmTag.Sha384,
                (int)HashAlgorithmTag.Sha512
            });

            signhashgen.SetFeature(false, Features.FEATURE_MODIFICATION_DETECTION);

            // Create a signature on the encryption subkey.
            PgpSignatureSubpacketGenerator enchashgen = new PgpSignatureSubpacketGenerator();

            enchashgen.SetKeyFlags(false, KeyFlags.EncryptComms | KeyFlags.EncryptStorage | KeyFlags.Authentication);

            PgpKeyRingGenerator pgpKeyRing = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                rsakp_sign,
                id,
                SymmetricKeyAlgorithmTag.Aes256,
                pass,
                false,
                signhashgen.Generate(),
                null,
                new SecureRandom()
                );

            pgpKeyRing.AddSubKey(rsakp_enc, enchashgen.Generate(), null, HashAlgorithmTag.Sha512);

            return(pgpKeyRing);
        }
Пример #11
0
        public static void p5_crypto_create_pgp_keypair(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves
            using (new ArgsRemover(e.Args, true)) {
                // Retrieving identity (normally an email address), in addition to 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(true)) {
                    // 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();
                e.Args.Add("fingerprint", BitConverter.ToString(publicRing.GetPublicKey().GetFingerprint()).Replace("-", ""));
                e.Args.Add("key-id", ((int)publicRing.GetPublicKey().KeyId).ToString("X"));
            }
        }
Пример #12
0
        public static PgpKeyRingGenerator GenerateKeyRingGenerator(KeyRingParams keyRingParams)
        {
            var generator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(keyRingParams.RsaParams());

            /* Create the master (signing-only) key. */
            var masterKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.RsaSign, generator.GenerateKeyPair(), DateTime.UtcNow);

            Debug.WriteLine("Generated master key with ID " + masterKeyPair.KeyId.ToString("X"));

            var masterSubpckGen = new PgpSignatureSubpacketGenerator();

            masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify);
            masterSubpckGen.SetPreferredSymmetricAlgorithms(false, keyRingParams.SymmetricAlgorithms.Select(a => (int)a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false, keyRingParams.HashAlgorithms.Select(a => (int)a).ToArray());

            /* Create a signing and encryption key for daily use. */
            var encKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.UtcNow);

            Debug.WriteLine("Generated encryption key with ID " + encKeyPair.KeyId.ToString("X"));

            var encSubpckGen = new PgpSignatureSubpacketGenerator();

            encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);

            masterSubpckGen.SetPreferredSymmetricAlgorithms(false, (keyRingParams.SymmetricAlgorithms.Select(a => (int)a)).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false, (keyRingParams.HashAlgorithms.Select(a => (int)a)).ToArray());

            /* Create the key ring. */

            var keyRingGen = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                masterKeyPair,
                keyRingParams.Identity,
                keyRingParams.PrivateKeyEncryptionAlgorithm.Value,
                keyRingParams.GetPassword(),
                true,
                masterSubpckGen.Generate(),
                null,
                new SecureRandom());

            /* Add encryption subkey. */
            keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null);

            return(keyRingGen);
        }
Пример #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");
             * }*/
        }
Пример #14
0
        void AddEncryptionKeyPair(PgpKeyRingGenerator keyRingGenerator, KeyGenerationParameters parameters, PublicKeyAlgorithmTag algorithm, DateTime now, long expirationTime, int[] encryptionAlgorithms, int[] digestAlgorithms)
        {
            var keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            keyPairGenerator.Init(parameters);

            var keyPair            = new PgpKeyPair(algorithm, keyPairGenerator.GenerateKeyPair(), now);
            var subpacketGenerator = new PgpSignatureSubpacketGenerator();

            subpacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);
            subpacketGenerator.SetPreferredSymmetricAlgorithms(false, encryptionAlgorithms);
            subpacketGenerator.SetPreferredHashAlgorithms(false, digestAlgorithms);

            if (expirationTime > 0)
            {
                subpacketGenerator.SetKeyExpirationTime(false, expirationTime);
                subpacketGenerator.SetSignatureExpirationTime(false, expirationTime);
            }

            keyRingGenerator.AddSubKey(keyPair, subpacketGenerator.Generate(), null);
        }
Пример #15
0
        public static void ExportKeyPair(
            Stream secretOut,
            Stream publicOut,
            AsymmetricCipherKeyPair dsaKp,
            AsymmetricCipherKeyPair elgKp,
            string identity,
            char[] passPhrase,
            bool armor)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

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

            // Prepare a strong Secure Random with seed
            SecureRandom secureRandom = PgpEncryptionUtil.GetSecureRandom();

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

            keyRingGen.AddSubKey(elgKeyPair);

            keyRingGen.GenerateSecretKeyRing().Encode(secretOut);

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

            keyRingGen.GeneratePublicKeyRing().Encode(publicOut);

            if (armor)
            {
                publicOut.Dispose();
            }
        }
Пример #16
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());
        }
Пример #17
0
        private static void ExportKeyPair(
            Stream secretOut,
            Stream publicOut,
            IAsymmetricCipherKeyPair signingKey,
            IAsymmetricCipherKeyPair encryptionKey,
            string identity,
            char[] passPhrase,
            bool armor,
            ISecureRandom random)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

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

            keyRingGenerator.AddSubKey(subKey);

            keyRingGenerator.GenerateSecretKeyRing().Encode(secretOut);

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

            keyRingGenerator.GeneratePublicKeyRing().Encode(publicOut);
            {
                publicOut.Close();
            }
        }
Пример #18
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());
        }
Пример #19
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!");
            }
        }
        public void GenerateEccKeyTest()
        {
            const string identity = "GenerateEccKeyTest Identity";

            var secureRandom = new SecureRandom();
            var keyParamSet = SecObjectIdentifiers.SecP256r1;
            var ecParams = new ECKeyGenerationParameters(keyParamSet, secureRandom);

            var now = DateTime.UtcNow;
            var masterKey = GenerateKeyPair(PublicKeyAlgorithmTag.Ecdsa, ecParams, now);
            var subKey = GenerateKeyPair(PublicKeyAlgorithmTag.Ecdh, ecParams, now);

            var keyRingGenerator = new PgpKeyRingGenerator(
                PgpSignature.PositiveCertification,
                masterKey,
                identity,
                SymmetricKeyAlgorithmTag.Aes256,
                HashAlgorithmTag.Sha256,
                "".ToCharArray(),
                true,
                GenerateSignatureSubpackets(identity),
                null,
                secureRandom);
            keyRingGenerator.AddSubKey(subKey);

            var secretKeyRing = keyRingGenerator.GenerateSecretKeyRing();
            CheckEccKey(secretKeyRing);
        }
Пример #21
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!");
            }
        }
Пример #22
0
        public static PgpKeyRingGenerator GenerateKeyRing(string identity, string password)
        {
            var keyRingParams = new KeyRingParams
            {
                Password = password,
                Identity = identity,
                PrivateKeyEncryptionAlgorithm = SymmetricKeyAlgorithmTag.Aes128,
                SymmetricAlgorithms           =
                    new SymmetricKeyAlgorithmTag[]
                {
                    SymmetricKeyAlgorithmTag.Aes256, SymmetricKeyAlgorithmTag.Aes192,
                    SymmetricKeyAlgorithmTag.Aes128
                },
                HashAlgorithms = new HashAlgorithmTag[]
                {
                    HashAlgorithmTag.Sha256, HashAlgorithmTag.Sha1, HashAlgorithmTag.Sha384,
                    HashAlgorithmTag.Sha512, HashAlgorithmTag.Sha224,
                }
            };


            var generator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(keyRingParams.RsaParams);

            /* Create the master (signing-only) key. */
            var masterKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.RsaSign, generator.GenerateKeyPair(), DateTime.UtcNow);

            var masterSubpckGen = new PgpSignatureSubpacketGenerator();

            masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify);
            masterSubpckGen.SetPreferredSymmetricAlgorithms(false,
                                                            (from a in keyRingParams.SymmetricAlgorithms
                                                             select(int) a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false,
                                                       (from a in keyRingParams.HashAlgorithms
                                                        select(int) a).ToArray());

            /* Create a signing and encryption key for daily use. */
            var encKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaGeneral,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);

            var encSubpckGen = new PgpSignatureSubpacketGenerator();

            encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);

            masterSubpckGen.SetPreferredSymmetricAlgorithms(false,
                                                            (from a in keyRingParams.SymmetricAlgorithms
                                                             select(int) a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false,
                                                       (from a in keyRingParams.HashAlgorithms
                                                        select(int) a).ToArray());

            /* Create the key ring. */
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                masterKeyPair,
                keyRingParams.Identity,
                keyRingParams.PrivateKeyEncryptionAlgorithm.Value,
                keyRingParams.GetPassword(),
                true,
                masterSubpckGen.Generate(),
                null,
                new SecureRandom());

            /* Add encryption subkey. */
            keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null);

            return(keyRingGen);
        }
Пример #23
0
        public void InsertMasterTest()
        {
            SecureRandom random = new SecureRandom();

            char[] passPhrase = "hello".ToCharArray();
            IAsymmetricCipherKeyPairGenerator rsaKpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            rsaKpg.Init(new KeyGenerationParameters(random, 512));

            //
            // this is quicker because we are using pregenerated parameters.
            //
            AsymmetricCipherKeyPair rsaKp = rsaKpg.GenerateKeyPair();
            PgpKeyPair rsaKeyPair1 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow);

            rsaKp = rsaKpg.GenerateKeyPair();
            PgpKeyPair rsaKeyPair2 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow);

            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification,
                rsaKeyPair1, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random);
            PgpSecretKeyRing secRing1 = keyRingGen.GenerateSecretKeyRing();
            PgpPublicKeyRing pubRing1 = keyRingGen.GeneratePublicKeyRing();

            keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification,
                rsaKeyPair2, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random);
            PgpSecretKeyRing secRing2 = keyRingGen.GenerateSecretKeyRing();
            PgpPublicKeyRing pubRing2 = keyRingGen.GeneratePublicKeyRing();

            try
            {
                PgpPublicKeyRing.InsertPublicKey(pubRing1, pubRing2.GetPublicKey());
                Fail("adding second master key (public) should throw an ArgumentException");
            }
            catch (ArgumentException e)
            {
                if (!e.Message.Equals("cannot add a master key to a ring that already has one"))
                {
                    Fail("wrong message in public test");
                }
            }

            try
            {
                PgpSecretKeyRing.InsertSecretKey(secRing1, secRing2.GetSecretKey());
                Fail("adding second master key (secret) should throw an ArgumentException");
            }
            catch (ArgumentException e)
            {
                if (!e.Message.Equals("cannot add a master key to a ring that already has one"))
                {
                    Fail("wrong message in secret test");
                }
            }
        }
Пример #24
0
        public void GenerateTest()
        {
            char[] passPhrase = "hello".ToCharArray();
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom());
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters dsaKgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
            dsaKpg.Init(dsaKgp);

            //
            // this takes a while as the key generator has to Generate some DSA parameters
            // before it Generates the key.
            //
            AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair();
            IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");

            BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            ElGamalParameters elParams = new ElGamalParameters(p, g);
            ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
            elgKpg.Init(elKgp);

            //
            // this is quicker because we are using preGenerated parameters.
            //
            AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair();
            PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow);
            PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow);

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

            keyRingGen.AddSubKey(elgKeyPair);

            PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing();

            keyRing.GetSecretKey().ExtractPrivateKey(passPhrase);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            PgpPublicKey vKey = null;
            PgpPublicKey sKey = null;

            foreach (PgpPublicKey pk in pubRing.GetPublicKeys())
            {
                if (pk.IsMasterKey)
                {
                    vKey = pk;
                }
                else
                {
                    sKey = pk;
                }
            }

            foreach (PgpSignature sig in sKey.GetSignatures())
            {
                if (sig.KeyId == vKey.KeyId
                    && sig.SignatureType == PgpSignature.SubkeyBinding)
                {
                    sig.InitVerify(vKey);

                    if (!sig.VerifyCertification(vKey, sKey))
                    {
                        Fail("failed to verify sub-key signature.");
                    }
                }
            }
        }
Пример #25
0
        /*
         * Creates a key ring generator and returns to caller
         */
        public static PgpKeyRingGenerator GetKeyRingGenerator(
            ApplicationContext context,
            Node args,
            string identity,
            string password,
            DateTime expires,
            int strength,
            long publicExponent,
            int certainty)
        {
            // Creating a secure random generator to use when creating keypairs, seeding with all sorts of different unique values
            var sr = CreateNewSecureRandom(context, args);

            // Creating our generator
            IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(
                new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(publicExponent),
                    sr,
                    strength,
                    certainty));

            // Creates the master key (signing-only key)
            PgpKeyPair masterKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaGeneral,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);

            PgpSignatureSubpacketGenerator masterSubPacketGenerator = new PgpSignatureSubpacketGenerator();

            masterSubPacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify);
            masterSubPacketGenerator.SetPreferredSymmetricAlgorithms(false,
                                                                     new SymmetricKeyAlgorithmTag [] {
                SymmetricKeyAlgorithmTag.Aes256,
                SymmetricKeyAlgorithmTag.Aes192,
                SymmetricKeyAlgorithmTag.Aes128
            }.Select(ix => (int)ix).ToArray());
            masterSubPacketGenerator.SetPreferredHashAlgorithms(false,
                                                                new HashAlgorithmTag [] {
                HashAlgorithmTag.Sha256,
                HashAlgorithmTag.Sha1,
                HashAlgorithmTag.Sha384,
                HashAlgorithmTag.Sha512,
                HashAlgorithmTag.Sha224
            }.Select(ix => (int)ix).ToArray());
            masterSubPacketGenerator.SetKeyExpirationTime(false, (long)(expires - DateTime.Now).TotalSeconds);

            // Creating a new secure random generator to use when creating keypairs, seeding with all sorts of different unique values
            sr = CreateNewSecureRandom(context, args);

            // Create signing and encryption key, for daily use
            PgpKeyPair encryptionKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaGeneral,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);

            PgpSignatureSubpacketGenerator encryptionSubPacketGenerator = new PgpSignatureSubpacketGenerator();

            encryptionSubPacketGenerator.SetKeyFlags(false,
                                                     PgpKeyFlags.CanEncryptCommunications |
                                                     PgpKeyFlags.CanEncryptStorage |
                                                     PgpKeyFlags.CanSign);
            encryptionSubPacketGenerator.SetKeyExpirationTime(false, (long)(expires - DateTime.Now).TotalSeconds);

            // Creating keyring
            PgpKeyRingGenerator keyRingGenerator = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                masterKeyPair,
                identity,
                SymmetricKeyAlgorithmTag.Aes256,
                password.ToCharArray(),
                true,
                masterSubPacketGenerator.Generate(),
                null,
                sr);

            // Add encryption subkey
            keyRingGenerator.AddSubKey(encryptionKeyPair, encryptionSubPacketGenerator.Generate(), null);

            // Returning keyring to caller
            return(keyRingGenerator);
        }
Пример #26
0
        /// <summary>
        /// Generates a <see cref="PgpKeyRingGenerator"/>
        /// </summary>
        /// <param name="identity">
        /// The name of the identity.
        /// </param>
        /// <param name="password">
        /// The passphrase used to protect the keyring.</param>
        /// <returns>
        /// A <see cref="PgpKeyRingGenerator"/>.
        /// </returns>
        public static PgpKeyRingGenerator GenerateKeyRingGenerator(string identity, string password)
        {
            var rsaParams           = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 12);
            var symmetricAlgorithms = new SymmetricKeyAlgorithmTag[] {
                SymmetricKeyAlgorithmTag.Aes256,
                SymmetricKeyAlgorithmTag.Aes192,
                SymmetricKeyAlgorithmTag.Aes128
            }.Select(a => (int)a).ToArray();

            var hashAlgorithms = new HashAlgorithmTag[] {
                HashAlgorithmTag.Sha256,
                HashAlgorithmTag.Sha1,
                HashAlgorithmTag.Sha384,
                HashAlgorithmTag.Sha512,
                HashAlgorithmTag.Sha224,
            }.Select(a => (int)a).ToArray();

            IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(rsaParams);

            // Create the master (signing-only) key.
            PgpKeyPair masterKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaSign,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);

            PgpSignatureSubpacketGenerator masterSubpckGen
                = new PgpSignatureSubpacketGenerator();

            masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign
                                        | PgpKeyFlags.CanCertify);
            masterSubpckGen.SetPreferredSymmetricAlgorithms(false, symmetricAlgorithms);
            masterSubpckGen.SetPreferredHashAlgorithms(false, hashAlgorithms);

            // Create a signing and encryption key for daily use.
            PgpKeyPair encKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaGeneral,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);

            PgpSignatureSubpacketGenerator encSubpckGen = new PgpSignatureSubpacketGenerator();

            encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);

            masterSubpckGen.SetPreferredSymmetricAlgorithms(false, symmetricAlgorithms);
            masterSubpckGen.SetPreferredHashAlgorithms(false, hashAlgorithms);

            // Create the key ring.
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                masterKeyPair,
                identity,
                SymmetricKeyAlgorithmTag.Aes128,
                password.ToCharArray(),
                true,
                masterSubpckGen.Generate(),
                null,
                new SecureRandom());

            // Add encryption subkey.
            keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null);

            return(keyRingGen);
        }
Пример #27
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);
        }
Пример #28
0
        public static PgpKeyRingGenerator generateKeyRingGenerator(String identity, String password)
        {
            KeyRingParams keyRingParams = new KeyRingParams();

            keyRingParams.Password = password;
            keyRingParams.Identity = identity;
            keyRingParams.PrivateKeyEncryptionAlgorithm = SymmetricKeyAlgorithmTag.Aes256;
            keyRingParams.SymmetricAlgorithms           = new SymmetricKeyAlgorithmTag[] {
                SymmetricKeyAlgorithmTag.Cast5

                /*SymmetricKeyAlgorithmTag.Aes256,
                 * SymmetricKeyAlgorithmTag.Aes192,
                 * SymmetricKeyAlgorithmTag.Aes128*/
            };

            keyRingParams.HashAlgorithms = new HashAlgorithmTag[] {
                HashAlgorithmTag.Sha512,
            };

            IAsymmetricCipherKeyPairGenerator generator
                = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(keyRingParams.RsaParams);

            /* Create the master (signing-only) key. */
            PgpKeyPair masterKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaSign,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);
            //Debug.WriteLine("Generated master key with ID "
            //   + masterKeyPair.KeyId.ToString("X"));

            PgpSignatureSubpacketGenerator masterSubpckGen
                = new PgpSignatureSubpacketGenerator();

            masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign
                                        | PgpKeyFlags.CanCertify);
            masterSubpckGen.SetPreferredSymmetricAlgorithms(false,
                                                            (from a in keyRingParams.SymmetricAlgorithms
                                                             select(int) a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false,
                                                       (from a in keyRingParams.HashAlgorithms
                                                        select(int) a).ToArray());

            /* Create a signing and encryption key for daily use. */
            PgpKeyPair encKeyPair = new PgpKeyPair(
                PublicKeyAlgorithmTag.RsaGeneral,
                generator.GenerateKeyPair(),
                DateTime.UtcNow);


            PgpSignatureSubpacketGenerator encSubpckGen = new PgpSignatureSubpacketGenerator();

            encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);

            masterSubpckGen.SetPreferredSymmetricAlgorithms(false,
                                                            (from a in keyRingParams.SymmetricAlgorithms
                                                             select(int) a).ToArray());
            masterSubpckGen.SetPreferredHashAlgorithms(false,
                                                       (from a in keyRingParams.HashAlgorithms
                                                        select(int) a).ToArray());

            /* Create the key ring. */
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                masterKeyPair,
                keyRingParams.Identity,
                keyRingParams.PrivateKeyEncryptionAlgorithm.Value,
                keyRingParams.GetPassword(),
                true,
                masterSubpckGen.Generate(),
                null,
                new SecureRandom());

            /* Add encryption subkey. */
            keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null);

            return(keyRingGen);
        }