コード例 #1
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();
            }
        }
コード例 #2
0
ファイル: PgpECDHTest.cs プロジェクト: KimikoMuffin/bc-csharp
        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);
        }
コード例 #3
0
 public PgpKeyRingGenerator(int certificationLevel, PgpKeyPair masterKey, string id, SymmetricKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, byte[] rawPassPhrase, bool useSha1, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
 {
     this.certificationLevel = certificationLevel;
     this.masterKey          = masterKey;
     this.id              = id;
     this.encAlgorithm    = encAlgorithm;
     this.rawPassPhrase   = rawPassPhrase;
     this.useSha1         = useSha1;
     hashedPacketVector   = hashedPackets;
     unhashedPacketVector = unhashedPackets;
     this.rand            = rand;
     this.hashAlgorithm   = hashAlgorithm;
     keys.Add(new PgpSecretKey(certificationLevel, masterKey, id, encAlgorithm, hashAlgorithm, rawPassPhrase, clearPassPhrase: false, useSha1, hashedPackets, unhashedPackets, rand));
 }
コード例 #4
0
ファイル: PGP.cs プロジェクト: cecada/Crypto-Notes
        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);
        }
コード例 #5
0
ファイル: EncryptionHelper.cs プロジェクト: treverson/prime
        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);
        }
コード例 #6
0
 public void AddSubKey(PgpKeyPair keyPair, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets)
 {
     try
     {
         PgpSignatureGenerator pgpSignatureGenerator = new PgpSignatureGenerator(masterKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
         pgpSignatureGenerator.InitSign(24, masterKey.PrivateKey);
         pgpSignatureGenerator.SetHashedSubpackets(hashedPackets);
         pgpSignatureGenerator.SetUnhashedSubpackets(unhashedPackets);
         IList list = Platform.CreateArrayList();
         list.Add(pgpSignatureGenerator.GenerateCertification(masterKey.PublicKey, keyPair.PublicKey));
         keys.Add(new PgpSecretKey(keyPair.PrivateKey, new PgpPublicKey(keyPair.PublicKey, null, list), encAlgorithm, rawPassPhrase, clearPassPhrase: false, useSha1, rand, isMasterKey: false));
     }
     catch (PgpException ex)
     {
         throw ex;
     }
     catch (Exception exception)
     {
         throw new PgpException("exception adding subkey: ", exception);
     }
 }
コード例 #7
0
ファイル: OpenPgpContext.cs プロジェクト: xiaowei-asp/MimeKit
        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);
        }
コード例 #8
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();
            }
        }
コード例 #9
0
        public void SimpleSignature()
        {
            var keyPair = new PgpKeyPair(DSA.Create(512), DateTime.UtcNow);

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

            using (var messageGenerator = new PgpMessageGenerator(new ArmoredPacketWriter(encodedStream, useClearText: true)))
                using (var signedGenerator = messageGenerator.CreateSigned(PgpSignatureType.CanonicalTextDocument, keyPair.PrivateKey, PgpHashAlgorithm.Sha256))
                    using (var literalStream = signedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow))
                    {
                        literalStream.Write(msg);
                    }

            encodedStream = new MemoryStream(encodedStream.ToArray(), false);
            var signedMessage  = (PgpSignedMessage)PgpMessage.ReadMessage(new ArmoredPacketReader(encodedStream));
            var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage();
            // Skip over literal data
            var bytes = Streams.ReadAll(literalMessage.GetStream());

            Assert.AreEqual(msg, bytes);
            // NOTE: The order is significant
            Assert.IsTrue(signedMessage.Verify(keyPair.PublicKey));
        }
コード例 #10
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();
            }
        }
コード例 #11
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.");
                    }
                }
            }
        }
コード例 #12
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!");
            }
        }
コード例 #13
0
ファイル: PgpECDHTest.cs プロジェクト: KimikoMuffin/bc-csharp
        private void EncryptDecryptTest()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

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

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

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

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
            MemoryStream ldOut = new MemoryStream();
            Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow);

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

            pOut.Close();

            byte[] data = ldOut.ToArray();

            MemoryStream cbOut = new MemoryStream();

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

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

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

            cOut.Close();

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

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey);

            pgpF = new PgpObjectFactory(clear);

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

            clear = ld.GetInputStream();
            MemoryStream bOut = new MemoryStream();

            int ch;
            while ((ch = clear.ReadByte()) >= 0)
            {
                bOut.WriteByte((byte)ch);
            }

            byte[] output = bOut.ToArray();

            if (!AreEqual(output, text))
            {
                Fail("wrong plain text in Generated packet");
            }
        }
コード例 #14
0
        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.");
//					}
                }
            }
        }
コード例 #15
0
 public PgpKeyRingGenerator(int certificationLevel, PgpKeyPair masterKey, string id, SymmetricKeyAlgorithmTag encAlgorithm, char[] passPhrase, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
     : this(certificationLevel, masterKey, id, encAlgorithm, passPhrase, useSha1 : false, hashedPackets, unhashedPackets, rand)
 {
 }
コード例 #16
0
ファイル: PgpECDHTest.cs プロジェクト: AlexPaskhin/bc-csharp
        private void EncryptDecryptTest()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

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

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

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

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

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

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
            MemoryStream            ldOut = new MemoryStream();
            Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow);

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

            pOut.Close();

            byte[] data = ldOut.ToArray();

            MemoryStream cbOut = new MemoryStream();

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

            cPk.AddMethod(ecdhKeyPair.PublicKey);

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

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

            cOut.Close();

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

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey);

            pgpF = new PgpObjectFactory(clear);

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

            clear = ld.GetInputStream();
            MemoryStream bOut = new MemoryStream();

            int ch;

            while ((ch = clear.ReadByte()) >= 0)
            {
                bOut.WriteByte((byte)ch);
            }

            byte[] output = bOut.ToArray();

            if (!AreEqual(output, text))
            {
                Fail("wrong plain text in Generated packet");
            }
        }
コード例 #17
0
        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;
        }
コード例 #18
0
ファイル: PGPRSATest.cs プロジェクト: 1hub/springburg
        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);
        }
コード例 #19
0
 public void AddSubKey(PgpKeyPair keyPair, HashAlgorithmTag hashAlgorithm)
 {
     AddSubKey(keyPair, hashedPacketVector, unhashedPacketVector, hashAlgorithm);
 }
コード例 #20
0
 public void AddSubKey(PgpKeyPair keyPair)
 {
     AddSubKey(keyPair, hashedPacketVector, unhashedPacketVector);
 }
コード例 #21
0
ファイル: PGPRSATest.cs プロジェクト: KimikoMuffin/bc-csharp
        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();
        }
コード例 #22
0
 public PgpKeyRingGenerator(int certificationLevel, PgpKeyPair masterKey, string id, SymmetricKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, bool utf8PassPhrase, char[] passPhrase, bool useSha1, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
     : this(certificationLevel, masterKey, id, encAlgorithm, hashAlgorithm, PgpUtilities.EncodePassPhrase(passPhrase, utf8PassPhrase), useSha1, hashedPackets, unhashedPackets, rand)
 {
 }
コード例 #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
ファイル: PGPDSATest.cs プロジェクト: jwtvh/bc-csharp
        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;
        }
コード例 #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
        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!");
            }
        }
コード例 #27
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);
        }
コード例 #28
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);
        }
コード例 #29
0
        /// <summary>
        /// Create master signing key.
        /// </summary>
        /// <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="signKeyLength">
        /// Length of the signing key.
        /// </param>
        /// <param name="signGenerator">
        /// Generator for the signing key.
        /// </param>
        /// <param name="signingAlgorithm">
        /// Signing algorithm.
        /// </param>
        /// <param name="symmetricAlgorithm">
        /// Symmetric algorithm.
        /// </param>
        /// <returns>
        /// Returns the <see cref="PgpKeyRingGenerator"/> with the keyring properties
        /// thus far.
        /// </returns>
        public static PgpKeyRingGenerator CreateMasterSigningKey(
            string identity,
            string password,
            DateTime?expires,
            int signKeyLength    = 2048,
            string signGenerator = "RSA",
            PublicKeyAlgorithmTag signingAlgorithm      = PublicKeyAlgorithmTag.RsaSign,
            SymmetricKeyAlgorithmTag symmetricAlgorithm = SymmetricKeyAlgorithmTag.Aes256)
        {
            var keyringParameters = new KeyRingParameters(signKeyLength, signGenerator)
            {
                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,
                }
            };

            // master signing key
            var generator = GeneratorUtilities.GetKeyPairGenerator(signGenerator);

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

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

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

            var masterSubpckGen = new PgpSignatureSubpacketGenerator();

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

            // keyring -- adding master key
            return(new PgpKeyRingGenerator(
                       PgpSignature.DefaultCertification,
                       masterKeyPair,
                       keyringParameters.Identity,
                       keyringParameters.PrivateKeyEncryptionAlgorithm,
                       keyringParameters.GetPassword(),
                       true,
                       masterSubpckGen.Generate(),
                       null,
                       new SecureRandom()));
        }
コード例 #30
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.");
//					}
                }
            }
		}
コード例 #31
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);
        }