public override BigInteger CalculateAgreement(
            ICipherParameters pubKey)
        {
            // Note that the ec.KeyAgreement class in JCE only uses kdf in one
            // of the engineGenerateSecret methods.

            BigInteger result = base.CalculateAgreement(pubKey);

            int keySize = GeneratorUtilities.GetDefaultKeySize(algorithm);

            DHKdfParameters dhKdfParams = new DHKdfParameters(
                new DerObjectIdentifier(algorithm),
                keySize,
                BigIntToBytes(result));

            kdf.Init(dhKdfParams);

            byte[] keyBytes = new byte[keySize / 8];
            kdf.GenerateBytes(keyBytes, 0, keyBytes.Length);

            return(new BigInteger(1, keyBytes));
        }
Exemplo n.º 2
0
 public static string GenerateRSAKeyAsPEM(int keySize)
 {
     try
     {
         IAsymmetricCipherKeyPairGenerator generator       = GeneratorUtilities.GetKeyPairGenerator("RSA");
         RsaKeyGenerationParameters        generatorParams = new RsaKeyGenerationParameters(
             BigInteger.ValueOf(0x10001), new SecureRandom(), keySize, 12);
         generator.Init(generatorParams);
         AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
         using (StringWriter sw = new StringWriter())
         {
             PemWriter pemWriter = new PemWriter(sw);
             pemWriter.WriteObject(keyPair);
             return(sw.ToString());
         }
     }
     catch (Exception e)
     {
         logger.Error($"Could not generate new key pair: {e.Message}");
         return(null);
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Generate RSA key in Pkcs1 format. Result: Index 0 is the private key and index 1 is the public key
        /// </summary>
        /// <param name="keySize">Key Size.Unit: bits</param>
        /// <param name="format">Whether the format is true If it is standard pem file format</param>
        /// <returns></returns>
        public static List <string> Pkcs1Key(int keySize, bool format)
        {
            List <string> res = new List <string>();

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

            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize));
            var keyPair = kpGen.GenerateKeyPair();

            StringWriter sw   = new StringWriter();
            PemWriter    pWrt = new PemWriter(sw);

            pWrt.WriteObject(keyPair.Private);
            pWrt.Writer.Close();
            var privateKey = sw.ToString();

            if (!format)
            {
                privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\r\n", "");
            }

            res.Add(privateKey);

            StringWriter swpub   = new StringWriter();
            PemWriter    pWrtpub = new PemWriter(swpub);

            pWrtpub.WriteObject(keyPair.Public);
            pWrtpub.Writer.Close();
            string publicKey = swpub.ToString();

            if (!format)
            {
                publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", "");
            }

            res.Add(publicKey);

            return(res);
        }
Exemplo n.º 4
0
        /// <summary>
        /// DSA密钥对生成
        /// </summary>
        /// <param name="size">size must be from 512 - 1024 and a multiple of 64</param>
        /// <returns></returns>
        public static KeyParameter Generator(int size = 1024)
        {
            var pGen = new DsaParametersGenerator();

            pGen.Init(size, 80, new SecureRandom());
            var dsaParams = pGen.GenerateParameters();
            var kgp       = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            var kpg       = GeneratorUtilities.GetKeyPairGenerator("DSA");

            kpg.Init(kgp);

            var kp = kpg.GenerateKeyPair();

            var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public);
            var privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp.Private);

            return(new KeyParameter
            {
                PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()),
                PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded())
            });
        }
Exemplo n.º 5
0
        private KeyParameter CalculateAgreedWrapKey(
            string wrapAlg,
            AsymmetricKeyParameter senderPublicKey,
            AsymmetricKeyParameter receiverPrivateKey)
        {
            DerObjectIdentifier agreeAlgID = keyEncAlg.Algorithm;

            ICipherParameters senderPublicParams    = senderPublicKey;
            ICipherParameters receiverPrivateParams = receiverPrivateKey;

            if (agreeAlgID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                byte[] ukmEncoding        = info.UserKeyingMaterial.GetOctets();
                MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.GetInstance(
                    Asn1Object.FromByteArray(ukmEncoding));

                AsymmetricKeyParameter ephemeralKey = GetPublicKeyFromOriginatorPublicKey(
                    receiverPrivateKey, ukm.EphemeralPublicKey);

                senderPublicParams = new MqvPublicParameters(
                    (ECPublicKeyParameters)senderPublicParams,
                    (ECPublicKeyParameters)ephemeralKey);
                receiverPrivateParams = new MqvPrivateParameters(
                    (ECPrivateKeyParameters)receiverPrivateParams,
                    (ECPrivateKeyParameters)receiverPrivateParams);
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreeAlgID, wrapAlg);

            agreement.Init(receiverPrivateParams);
            BigInteger agreedValue = agreement.CalculateAgreement(senderPublicParams);

            int wrapKeySize = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;

            byte[] wrapKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, wrapKeySize);
            return(ParameterUtilities.CreateKeyParameter(wrapAlg, wrapKeyBytes));
        }
        private KeyParameter CalculateAgreedWrapKey(string wrapAlg, AsymmetricKeyParameter senderPublicKey, AsymmetricKeyParameter receiverPrivateKey)
        {
            DerObjectIdentifier objectID          = this.keyEncAlg.ObjectID;
            ICipherParameters   cipherParameters  = senderPublicKey;
            ICipherParameters   cipherParameters2 = receiverPrivateKey;

            if (objectID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                byte[] octets = this.info.UserKeyingMaterial.GetOctets();
                MQVuserKeyingMaterial  instance = MQVuserKeyingMaterial.GetInstance(Asn1Object.FromByteArray(octets));
                AsymmetricKeyParameter publicKeyFromOriginatorPublicKey = this.GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, instance.EphemeralPublicKey);
                cipherParameters  = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters, (ECPublicKeyParameters)publicKeyFromOriginatorPublicKey);
                cipherParameters2 = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters2, (ECPrivateKeyParameters)cipherParameters2);
            }
            IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(objectID, wrapAlg);

            basicAgreementWithKdf.Init(cipherParameters2);
            BigInteger s       = basicAgreementWithKdf.CalculateAgreement(cipherParameters);
            int        qLength = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;

            byte[] keyBytes = X9IntegerConverter.IntegerToBytes(s, qLength);
            return(ParameterUtilities.CreateKeyParameter(wrapAlg, keyBytes));
        }
Exemplo n.º 7
0
        private void SignedXmlHasVerifiableSignature(string signatureMethod, string digestMethod)
        {
            var keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
            var pair = keyGen.GenerateKeyPair();

            var xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(ExampleXml);
            SignXml(xmlDoc, (RsaKeyParameters)pair.Private, signatureMethod, digestMethod);

            Console.WriteLine("Signed document:");
            Console.WriteLine();
            Console.WriteLine(xmlDoc.OuterXml);

            var result = VerifyXml(xmlDoc.OuterXml, (RsaKeyParameters)pair.Public);

            Console.WriteLine();
            Console.WriteLine("Signature verification result: {0}", result ? "valid" : "invalid");
            Console.WriteLine();
        }
Exemplo n.º 8
0
        static CmsTestUtil()
        {
            try
            {
                rand = new SecureRandom();

                aes192kg = GeneratorUtilities.GetKeyGenerator("AES");
                aes192kg.Init(new KeyGenerationParameters(rand, 192));

                desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
                desede128kg.Init(new KeyGenerationParameters(rand, 112));

                desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
                desede192kg.Init(new KeyGenerationParameters(rand, 168));

                rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc240kg.Init(new KeyGenerationParameters(rand, 40));

                rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc264kg.Init(new KeyGenerationParameters(rand, 64));

                rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc2128kg.Init(new KeyGenerationParameters(rand, 128));

                aesKg = GeneratorUtilities.GetKeyGenerator("AES");

                seedKg = GeneratorUtilities.GetKeyGenerator("SEED");

                camelliaKg = GeneratorUtilities.GetKeyGenerator("Camellia");

                serialNumber = BigInteger.One;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
Exemplo n.º 9
0
        protected void oidTest(
            string[]        oids,
            string[]        names,
            int groupSize)
        {
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

            for (int i = 0; i != oids.Length; i++)
            {
                IBufferedCipher    c1 = CipherUtilities.GetCipher(oids[i]);
                IBufferedCipher    c2 = CipherUtilities.GetCipher(names[i]);
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);

                KeyParameter k = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());

                ICipherParameters cp = k;
                if (names[i].IndexOf("/ECB/") < 0)
                {
                    cp = new ParametersWithIV(cp, new byte[16]);
                }

                c1.Init(true, cp);
                c2.Init(false, cp);

                byte[] result = c2.DoFinal(c1.DoFinal(data));

                if (!AreEqual(data, result))
                {
                    Fail("failed OID test");
                }

                if (k.GetKey().Length != (16 + ((i / groupSize) * 8)))
                {
                    Fail("failed key length test");
                }
            }
        }
Exemplo n.º 10
0
        void OnSvAppSecureHandshake(string id, JsonObj args)
        {
            // https://davidtavarez.github.io/2019/implementing-elliptic-curve-diffie-hellman-c-sharp/
            X9ECParameters     x9Params     = NistNamedCurves.GetByName("P-521");
            ECDomainParameters domainParams = new ECDomainParameters(x9Params.Curve, x9Params.G, x9Params.N, x9Params.H, x9Params.GetSeed());
            ECKeyPairGenerator generator    = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator("ECDH");

            generator.Init(new ECKeyGenerationParameters(domainParams, new SecureRandom()));
            AsymmetricCipherKeyPair aliceKeyPair         = generator.GenerateKeyPair();
            ECPublicKeyParameters   alicePublicKeyParams = (ECPublicKeyParameters)aliceKeyPair.Public;

            string bobKey = args.Get <string>("key");

            byte[] bobKeyBytes = System.Convert.FromBase64String(bobKey);
            var    bobPoint    = x9Params.Curve.DecodePoint(bobKeyBytes);
            ECPublicKeyParameters bobPublicKeyParams = new ECPublicKeyParameters("ECDH", bobPoint, SecObjectIdentifiers.SecP521r1);

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(aliceKeyPair.Private);
            BigInteger sharedSecret = agreement.CalculateAgreement(bobPublicKeyParams);

            IDigest digest = new Sha256Digest();

            byte[] sharedSecretBytes = sharedSecret.ToBytes(66);
            digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length);
            derivedKeyBytes = new byte[digest.GetDigestSize()];
            digest.DoFinal(derivedKeyBytes, 0);

            Debug.Log(System.BitConverter.ToString(sharedSecretBytes));
            Debug.Log(System.Convert.ToBase64String(derivedKeyBytes));

            ReturnSuccess(id, new JsonObj()
            {
                ["key"] = alicePublicKeyParams.Q.GetEncoded(),
            });
        }
Exemplo n.º 11
0
        public static string createKey(this API_OpenPgp openPgp, string identity, string passPhrase, string pathTo_PrivateKey, string pathTo_PublicKey)
        {
            if (identity.valid().isFalse())
            {
                "[API_OpenPgp] there was no value provided for the mandatory field: PGP Identity".error();
                return(null);
            }
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpg.Init(new RsaKeyGenerationParameters(
                         //BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25));
                         BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 25));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            Stream privateKey, publicKey;

            privateKey = File.Create(pathTo_PrivateKey);
            publicKey  = File.Create(pathTo_PublicKey);

            new RsaKeyRingGenerator().ExportKeyPair(privateKey, publicKey, kp.Public, kp.Private, identity, passPhrase.ToCharArray(), true);

            privateKey.Close();
            publicKey.Close();

            openPgp.PrivateKey = pathTo_PrivateKey;
            openPgp.PublicKey  = pathTo_PublicKey;
            openPgp.Identity   = identity;
            openPgp.PassPhrase = passPhrase;

            var openPgpFile = pathTo_PublicKey.directoryName().pathCombine("{0}_OpenPgp.xml".format(identity));

            openPgp.save(openPgpFile);
            "[API_OpenPgp] Pgp mappings for identity '{0}' saved to: {0}".debug(openPgpFile);
            return(openPgpFile);
        }
Exemplo n.º 12
0
        private void Button1_Click(object sender, EventArgs e)
        {
            string signature = textBox1.Text;

            textBox2.Text = @"C:\Users\MARK\Desktop\PGP\PGPKEY\priv.asc";
            textBox3.Text = @"C:\Users\MARK\Desktop\PGP\PGPKEY\pub.asc";

            //RSA密鑰產生器
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            //Key 構造使用參數
            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), new SecureRandom(),
                         1024, // key 的長度
                         25));
            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            char[] password = signature.ToCharArray(); //私鑰的密碼
            Stream out1, out2;

            out1 = File.Create(textBox2.Text); //私鑰放置位置
            out2 = File.Create(textBox3.Text); //公鑰放置位置
            ExportKeyPair(out1, out2, kp.Public, kp.Private, "MarkWu", password, true);
        }
Exemplo n.º 13
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!");
            }
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        public override void PerformTest()
        {
            generationTest(512, "RSA", "SHA1withRSA");
            generationTest(512, "GOST3410", "GOST3411withGOST3410");

            //		if (Security.getProvider("SunRsaSign") != null)
            //        {
            //            generationTest(512, "RSA", "SHA1withRSA", "SunRsaSign");
            //        }

            // elliptic curve GOST A parameter set
            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(gost3410EC_A);

            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_A.");
            }

            // elliptic curve GOST B parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_B);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_B.");
            }

            // elliptic curve GOST C parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_C);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_C.");
            }

            // elliptic curve GOST ExA parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_ExA);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_ExA.");
            }

            // elliptic curve GOST ExB parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_ExB);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_ExA.");
            }

            // elliptic curve openSSL
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")),             // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"));                 // n

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            AsymmetricCipherKeyPair kp = g.GenerateKeyPair();

            req = new Pkcs10CertificationRequest(
                "ECDSAWITHSHA1", new X509Name("CN=XXX"), kp.Public, null, kp.Private);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
            createECRequest("SHA224withECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
            createECRequest("SHA256withECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
            createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
            createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ECDsaWithSha512);

            createECGostRequest();

            // TODO The setting of parameters for MGF algorithms is not implemented
//			createPssTest("SHA1withRSAandMGF1");
//			createPssTest("SHA224withRSAandMGF1");
//			createPssTest("SHA256withRSAandMGF1");
//			createPssTest("SHA384withRSAandMGF1");

            nullPointerTest();
        }
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            AsymmetricKeyParameter senderPublicKey     = senderKeyPair.Public;
            ICipherParameters      senderPrivateParams = senderKeyPair.Private;


            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }


            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }


            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);


            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();

            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int          keyEncryptionKeySize  = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[]       keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey      = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                                                               new DerSequence(recipientEncryptedKeys))));
        }
Exemplo n.º 17
0
        public void TestGeneration()
        {
            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[]       data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            SecureRandom rand = new SecureRandom();

            // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //

            doTestBadStrength(513);
            doTestBadStrength(510);
            doTestBadStrength(1025);

            //g.initialize(512, rand);
            {
                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(512, 80, rand);

                g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));
            }

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }



            //
            // ECDSA Fp generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve  = x9.Curve;
            ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }

            //
            // ECDSA F2m generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            x9     = ECNamedCurveTable.GetByName("c2tnb239v1");
            curve  = x9.Curve;
            ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }
        }
Exemplo n.º 18
0
        private void doRunTest(
            string name,
            int ivLength)
        {
            string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";

            string baseName = name;

            if (name.IndexOf('/') >= 0)
            {
                baseName = name.Substring(0, name.IndexOf('/'));
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName);

            IBufferedCipher inCipher  = CipherUtilities.GetCipher(name);
            IBufferedCipher outCipher = CipherUtilities.GetCipher(name);
            KeyParameter    key       = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey());
            MemoryStream    bIn       = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false);
            MemoryStream    bOut      = new MemoryStream();

            // In the Java build, this IV would be implicitly created and then retrieved with getIV()
            ICipherParameters cipherParams = key;

            if (ivLength > 0)
            {
                cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
            }

            inCipher.Init(true, cipherParams);

            // TODO Should we provide GetIV() method on IBufferedCipher?
            //if (inCipher.getIV() != null)
            //{
            //	outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV()));
            //}
            //else
            //{
            //	outCipher.Init(false, key);
            //}
            outCipher.Init(false, cipherParams);

            CipherStream cIn  = new CipherStream(bIn, inCipher, null);
            CipherStream cOut = new CipherStream(bOut, null, outCipher);

            int c;

            while ((c = cIn.ReadByte()) >= 0)
            {
                cOut.WriteByte((byte)c);
            }

            cIn.Close();

            cOut.Flush();
            cOut.Close();

            byte[] bs  = bOut.ToArray();
            string res = Encoding.ASCII.GetString(bs, 0, bs.Length);

            if (!res.Equals(lCode))
            {
                Fail("Failed - decrypted data doesn't match.");
            }
        }
Exemplo n.º 19
0
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            //IL_002f: Expected O, but got Unknown
            //IL_00c8: Expected O, but got Unknown
            //IL_0169: Unknown result type (might be due to invalid IL or missing references)
            byte[] key = contentEncryptionKey.GetKey();
            AsymmetricKeyParameter    @public          = senderKeyPair.Public;
            ICipherParameters         cipherParameters = senderKeyPair.Private;
            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(CreateOriginatorPublicKey(@public));
            }
            catch (IOException val)
            {
                IOException val2 = val;
                throw new InvalidKeyException(string.Concat((object)"cannot extract originator public key: ", (object)val2));
            }
            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    keyPairGenerator.Init(((ECPublicKeyParameters)@public).CreateKeyGenerationParameters(random));
                    AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();
                    ukm = new DerOctetString(new MQVuserKeyingMaterial(CreateOriginatorPublicKey(asymmetricCipherKeyPair.Public), null));
                    cipherParameters = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters, (ECPrivateKeyParameters)asymmetricCipherKeyPair.Private, (ECPublicKeyParameters)asymmetricCipherKeyPair.Public);
                }
                catch (IOException val3)
                {
                    IOException val4 = val3;
                    throw new InvalidKeyException(string.Concat((object)"cannot extract MQV ephemeral public key: ", (object)val4));
                }
                catch (SecurityUtilityException ex)
                {
                    throw new InvalidKeyException(string.Concat((object)"cannot determine MQV ephemeral key pair parameters from public key: ", (object)ex));
                }
            }
            DerSequence         parameters             = new DerSequence(keyEncryptionOID, DerNull.Instance);
            AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(keyAgreementOID, parameters);
            Asn1EncodableVector asn1EncodableVector    = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientCerts).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    X509Certificate         x509Certificate = (X509Certificate)enumerator.get_Current();
                    TbsCertificateStructure instance;
                    try
                    {
                        instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(x509Certificate.GetTbsCertificate()));
                    }
                    catch (global::System.Exception)
                    {
                        throw new ArgumentException("can't extract TBS structure from certificate");
                    }
                    IssuerAndSerialNumber       issuerSerial      = new IssuerAndSerialNumber(instance.Issuer, instance.SerialNumber.Value);
                    KeyAgreeRecipientIdentifier id                = new KeyAgreeRecipientIdentifier(issuerSerial);
                    ICipherParameters           cipherParameters2 = x509Certificate.GetPublicKey();
                    if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                    {
                        cipherParameters2 = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters2, (ECPublicKeyParameters)cipherParameters2);
                    }
                    IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(keyAgreementOID, keyEncryptionOID.Id);
                    basicAgreementWithKdf.Init(new ParametersWithRandom(cipherParameters, random));
                    BigInteger   s           = basicAgreementWithKdf.CalculateAgreement(cipherParameters2);
                    int          qLength     = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                    byte[]       keyBytes    = X9IntegerConverter.IntegerToBytes(s, qLength);
                    KeyParameter parameters2 = ParameterUtilities.CreateKeyParameter(keyEncryptionOID, keyBytes);
                    IWrapper     wrapper     = Helper.CreateWrapper(keyEncryptionOID.Id);
                    wrapper.Init(forWrapping: true, new ParametersWithRandom(parameters2, random));
                    byte[]          str          = wrapper.Wrap(key, 0, key.Length);
                    Asn1OctetString encryptedKey = new DerOctetString(str);
                    asn1EncodableVector.Add(new RecipientEncryptedKey(id, encryptedKey));
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncryptionAlgorithm, new DerSequence(asn1EncodableVector))));
        }
Exemplo n.º 20
0
        private void doTest(
            string algorithm,
            byte[]      input,
            byte[]      output)
        {
            KeyParameter       key = null;
            CipherKeyGenerator keyGen;
            SecureRandom       rand;
            IBufferedCipher    inCipher = null, outCipher = null;

            byte[]       iv = null;
            CipherStream cIn, cOut;
            MemoryStream bIn, bOut;

            rand = new FixedSecureRandom();

            string[] parts = algorithm.ToUpper(CultureInfo.InvariantCulture).Split('/');
            string   baseAlgorithm = parts[0];
            string   mode  = parts.Length > 1 ? parts[1] : null;

#if !INCLUDE_IDEA
            if (baseAlgorithm.Equals("IDEA"))
            {
                return;
            }
#endif

            try
            {
                keyGen = GeneratorUtilities.GetKeyGenerator(baseAlgorithm);

                // TODO Add Algorithm property to CipherKeyGenerator?
//				if (!keyGen.getAlgorithm().Equals(baseAlgorithm))
//				{
//					Fail("wrong key generator returned!");
//				}

                // TODO Add new Init method to CipherKeyGenerator?
//				keyGen.Init(rand);
                keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));

                byte[] keyBytes = keyGen.GenerateKey();

                if (algorithm.StartsWith("RC5"))
                {
                    key = new RC5Parameters(keyBytes, rc5Rounds);
                }
                else
                {
                    key = ParameterUtilities.CreateKeyParameter(baseAlgorithm, keyBytes);
                }

                inCipher  = CipherUtilities.GetCipher(algorithm);
                outCipher = CipherUtilities.GetCipher(algorithm);

                if (!inCipher.AlgorithmName.ToUpper(CultureInfo.InvariantCulture).StartsWith(baseAlgorithm))
                {
                    Fail("wrong cipher returned!");
                }

                ICipherParameters parameters = key;

                int ivLength = GetIVLength(algorithm);

                if (ivLength > 0)
                {
                    if (baseAlgorithm == "RC2")
                    {
                        iv = rc2IV;
                    }
                    else if (baseAlgorithm == "RC5")
                    {
                        iv = rc5IV;
                    }
                    else if (baseAlgorithm == "RC5-64")
                    {
                        iv = rc564IV;
                    }
                    else
                    {
                        // NB: rand always generates same values each test run
                        iv = rand.GenerateSeed(ivLength);
                    }

                    parameters = new ParametersWithIV(key, iv);
                }

                // NB: 'rand' still needed e.g. for some paddings
                parameters = new ParametersWithRandom(parameters, rand);

                outCipher.Init(true, parameters);
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed initialisation - " + e.ToString(), e);
            }

            //
            // grab the iv if there is one
            //
            try
            {
                // The Java version set this implicitly, but we set it explicity
                //byte[] iv = outCipher.getIV();

                if (iv != null)
                {
                    // TODO Examine short IV handling for these FIPS-compliant modes in Java build
                    if (mode.StartsWith("CFB") ||
                        mode.StartsWith("GOFB") ||
                        mode.StartsWith("OFB") ||
                        mode.StartsWith("OPENPGPCFB"))
                    {
                        // These modes automatically pad out the IV if it is short
                    }
                    else
                    {
                        try
                        {
                            byte[] nIv = new byte[iv.Length - 1];
                            inCipher.Init(false, new ParametersWithIV(key, nIv));
                            Fail("failed to pick up short IV");
                        }
                        //catch (InvalidAlgorithmParameterException e)
                        catch (ArgumentException)
                        {
                            // ignore - this is what we want...
                        }
                    }

                    //IvParameterSpec spec = new IvParameterSpec(iv);
                    inCipher.Init(false, new ParametersWithIV(key, iv));
                }
                else
                {
                    inCipher.Init(false, key);
                }
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed initialisation - " + e.ToString());
            }

            //
            // encryption pass
            //
            bOut = new MemoryStream();
            cOut = new CipherStream(bOut, null, outCipher);

            try
            {
                for (int i = 0; i != input.Length / 2; i++)
                {
                    cOut.WriteByte(input[i]);
                }
                cOut.Write(input, input.Length / 2, input.Length - input.Length / 2);
                cOut.Close();
            }
            catch (IOException e)
            {
                Fail("" + algorithm + " failed encryption - " + e.ToString());
            }

            byte[] bytes = bOut.ToArray();

            if (!AreEqual(bytes, output))
            {
                Fail("" + algorithm + " failed encryption - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(bytes));
            }

            //
            // decryption pass
            //
            bIn = new MemoryStream(bytes, false);
            cIn = new CipherStream(bIn, inCipher, null);

            try
            {
                BinaryReader dIn = new BinaryReader(cIn);

                bytes = new byte[input.Length];

                for (int i = 0; i != input.Length / 2; i++)
                {
                    bytes[i] = dIn.ReadByte();
                }

                int    remaining = bytes.Length - input.Length / 2;
                byte[] extra     = dIn.ReadBytes(remaining);
                if (extra.Length < remaining)
                {
                    throw new EndOfStreamException();
                }
                extra.CopyTo(bytes, input.Length / 2);
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed decryption - " + e.ToString());
            }

            if (!AreEqual(bytes, input))
            {
                Fail("" + algorithm + " failed decryption - expected "
                     + Hex.ToHexString(input) + " got "
                     + Hex.ToHexString(bytes));
            }
        }
Exemplo n.º 21
0
        public void TestDsa2Parameters()
        {
            byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");

            //AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
            //a.init(2048, new DSATestSecureRandom(seed));
            DsaParametersGenerator a = new DsaParametersGenerator(new Sha256Digest());

            a.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed)));

            //AlgorithmParameters parameters = a.generateParameters();

            //DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(DSAParameterSpec.class);
            DsaParameters dsaP = a.GenerateParameters();

            if (!dsaP.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
            {
                Fail("Q incorrect");
            }

            if (!dsaP.P.Equals(new BigInteger(
                                   "F56C2A7D366E3EBDEAA1891FD2A0D099" +
                                   "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
                                   "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
                                   "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
                                   "5909132627F51A0C866877E672E555342BDF9355347DBD43" +
                                   "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
                                   "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
                                   "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
                                   "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
                                   "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
                                   "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
            {
                Fail("P incorrect");
            }

            if (!dsaP.G.Equals(new BigInteger(
                                   "8DC6CC814CAE4A1C05A3E186A6FE27EA" +
                                   "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
                                   "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
                                   "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
                                   "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
                                   "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
                                   "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
                                   "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
                                   "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
                                   "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
                                   "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
            {
                Fail("G incorrect");
            }

            //KeyPairGenerator    g = KeyPairGenerator.getInstance("DSA", "BC");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            //g.initialize(dsaP, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")));
            g.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), dsaP));
            //KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            //DSAPrivateKey  sKey = (DSAPrivateKey)p.getPrivate();
            //DSAPublicKey   vKey = (DSAPublicKey)p.getPublic();
            DsaPrivateKeyParameters sKey = (DsaPrivateKeyParameters)p.Private;
            DsaPublicKeyParameters  vKey = (DsaPublicKeyParameters)p.Public;

            if (!vKey.Y.Equals(new BigInteger(
                                   "2828003D7C747199143C370FDD07A286" +
                                   "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
                                   "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
                                   "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
                                   "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
                                   "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
                                   "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
                                   "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
                                   "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
                                   "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
                                   "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!sKey.X.Equals(
                    new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
            {
                Fail("X value incorrect");
            }

            //byte[] encodeParams = parameters.getEncoded();
            byte[] encodeParams = new DsaParameter(dsaP.P, dsaP.Q, dsaP.G).GetDerEncoded();

            //AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
            //a2.init(encodeParams);
            DsaParameter  dsaP2 = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2    = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
            //byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/decode parameters failed");
            }

            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
Exemplo n.º 22
0
        public void TestParameters()
        {
//			AlgorithmParameterGenerator a = AlgorithmParameterGenerator.GetInstance("DSA");
//			a.init(512, random);
            DsaParametersGenerator a = new DsaParametersGenerator();

            a.Init(512, 20, random);

//			AlgorithmParameters parameters = a.generateParameters();
            DsaParameters p = a.GenerateParameters();

//			byte[] encodeParams = parameters.GetEncoded();
            byte[] encodeParams = new DsaParameter(p.P, p.Q, p.G).GetDerEncoded();

//			AlgorithmParameters a2 = AlgorithmParameters.GetInstance("DSA");
//			a2.init(encodeParams);
            DsaParameter  dsaP = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2   = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
//			byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/Decode parameters failed");
            }

//			DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(typeof(DSAParameterSpec));

//			KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

//			g.initialize(dsaP, new SecureRandom());
            g.Init(new DsaKeyGenerationParameters(new SecureRandom(), p));
//			KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();

//			PrivateKey sKey = p.Private;
//			PublicKey vKey = p.Public;
            AsymmetricKeyParameter sKey = pair.Private;
            AsymmetricKeyParameter vKey = pair.Public;

            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
        /**
         * Prepare the document for encryption.
         *
         * @param doc The document that will be encrypted.
         *
         * @throws IOException If there is an error while encrypting.
         */
        public override void PrepareDocumentForEncryption(Document doc)
        {
            try
            {
                PdfEncryption dictionary = doc.File.Encryption;
                if (dictionary == null)
                {
                    dictionary = new PdfEncryption(doc.File);
                }

                dictionary.Filter = FILTER;
                dictionary.Length = this.keyLength;
                int version = ComputeVersionNumber();
                dictionary.Version = version;

                // remove CF, StmF, and StrF entries that may be left from a previous encryption
                dictionary.RemoveV45filters();

                // create the 20 bytes seed
                byte[] seed = new byte[20];

                CipherKeyGenerator key;
                try
                {
                    key = GeneratorUtilities.GetKeyGenerator("AES");
                }
                catch (Exception e)
                {
                    // should never happen
                    throw new Exception("AES Key Generator", e);
                }

                key.Init(new KeyGenerationParameters(new SecureRandom(), 192));
                var sk = key.GenerateKey();

                // create the 20 bytes seed
                Array.Copy(sk, 0, seed, 0, 20);

                byte[][] recipientsFields = ComputeRecipientsField(seed);

                int shaInputLength = seed.Length;

                foreach (byte[] field in recipientsFields)
                {
                    shaInputLength += field.Length;
                }

                byte[] shaInput = new byte[shaInputLength];

                Array.Copy(seed, 0, shaInput, 0, 20);

                int shaInputOffset = 20;

                foreach (byte[] recipientsField in recipientsFields)
                {
                    Array.Copy(recipientsField, 0, shaInput, shaInputOffset, recipientsField.Length);
                    shaInputOffset += recipientsField.Length;
                }

                byte[] mdResult;
                if (version == 4 || version == 5)
                {
                    dictionary.SubFilter = SUBFILTER5;
                    mdResult             = SHA256.Create().Digest(shaInput);
                    PdfName aesVName = version == 5 ? PdfName.AESV3 : PdfName.AESV2;
                    PrepareEncryptionDictAES(dictionary, aesVName, recipientsFields);
                }
                else
                {
                    dictionary.SubFilter = SUBFILTER4;
                    mdResult             = SHA1.Create().Digest(shaInput);
                    dictionary.SetRecipients(recipientsFields);
                }

                this.encryptionKey = new byte[this.keyLength / 8];
                Array.Copy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8);

                doc.File.Encryption = dictionary;
            }
            catch (Exception e)
            {
                throw new IOException("", e);
            }
        }
Exemplo n.º 24
0
        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");
            }
        }
Exemplo n.º 25
0
        public void TestAlgorithms()
        {
            //
            // RSA parameters
            //
            BigInteger rsaMod    = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16);
            BigInteger rsaPubExp = new BigInteger("10001", 16);

            BigInteger rsaPrivExp  = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16);
            BigInteger rsaPrivP    = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16);
            BigInteger rsaPrivQ    = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16);
            BigInteger rsaPrivDP   = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16);
            BigInteger rsaPrivDQ   = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16);
            BigInteger rsaPrivQinv = new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16);

            RsaKeyParameters           rsaPublic  = new RsaKeyParameters(false, rsaMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(
                rsaMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            //
            // ECDSA parameters
            //
            BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            BigInteger ECParraH  = new BigInteger(Base64.Decode("AQ=="));
            BigInteger ECParraN  = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            BigInteger ECPubQX   = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            BigInteger ECPubQY   = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            BigInteger ECPrivD   = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

            FpCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),         // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));        // b

            ECDomainParameters ecDomain = new ECDomainParameters(curve,
                                                                 new FpPoint(curve,
                                                                             curve.FromBigInteger(ECParraGX),
                                                                             curve.FromBigInteger(ECParraGY)),
                                                                 ECParraN);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                new FpPoint(curve,
                            curve.FromBigInteger(ECPubQX),
                            curve.FromBigInteger(ECPubQY)),
                ecDomain);

            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

            //
            // DSA parameters
            //
            BigInteger DSAParaG    = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            BigInteger DSAParaP    = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            BigInteger DSAParaQ    = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            BigInteger DSAPublicY  = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters           para    = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters  dsaPub  = new DsaPublicKeyParameters(DSAPublicY, para);

            //
            // GOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            gostKpg.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair gostPair = gostKpg.GenerateKeyPair();

            //
            // signer loop
            //
            byte[] shortMsg = new byte[] { 1, 4, 5, 6, 8, 8, 4, 2, 1, 3 };
            byte[] longMsg  = new byte[100];
            new SecureRandom().NextBytes(longMsg);

            foreach (string algorithm in SignerUtilities.Algorithms)
            {
                ISigner signer = SignerUtilities.GetSigner(algorithm);

                string upper   = algorithm.ToUpper(CultureInfo.InvariantCulture);
                int    withPos = upper.LastIndexOf("WITH");

                string cipherName = withPos < 0
                    ?   upper
                    :   upper.Substring(withPos + "WITH".Length);

                ICipherParameters signParams = null, verifyParams = null;

                if (cipherName == "RSA" || cipherName == "RSAANDMGF1")
                {
                    signParams   = rsaPrivate;
                    verifyParams = rsaPublic;
                }
                else if (cipherName == "ECDSA")
                {
                    signParams   = ecPriv;
                    verifyParams = ecPub;
                }
                else if (cipherName == "DSA")
                {
                    signParams   = dsaPriv;
                    verifyParams = dsaPub;
                }
                else if (cipherName == "ECGOST3410")
                {
                    AsymmetricCipherKeyPair ecGostPair = GetEcCipherKeyPair(
                        "ECGOST3410",
                        CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);
                    signParams   = ecGostPair.Private;
                    verifyParams = ecGostPair.Public;
                }
                else if (cipherName == "GOST3410")
                {
                    signParams   = gostPair.Private;
                    verifyParams = gostPair.Public;
                }
                else if (cipherName == "GOST3410_2012_256")
                {
                    AsymmetricCipherKeyPair gost2012_256Pair = GetEcCipherKeyPair(
                        "GOST3410_2012_256",
                        RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256_paramSetA);
                    signParams   = gost2012_256Pair.Private;
                    verifyParams = gost2012_256Pair.Public;
                }
                else if (cipherName == "GOST3410_2012_512")
                {
                    AsymmetricCipherKeyPair gost2012_512Pair = GetEcCipherKeyPair(
                        "GOST3410_2012_512",
                        RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA);
                    signParams   = gost2012_512Pair.Private;
                    verifyParams = gost2012_512Pair.Public;
                }
                else
                {
                    Assert.Fail("Unknown algorithm encountered: " + cipherName);
                }

                signer.Init(true, signParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);
                byte[] sig = signer.GenerateSignature();

                signer.Init(false, verifyParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);

                Assert.IsTrue(signer.VerifySignature(sig), cipherName + " signer " + algorithm + " failed.");
            }
        }
Exemplo n.º 26
0
        public void TestECMqv()
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECMQV");

//			EllipticCurve curve = new EllipticCurve(
//				new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
//				new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
//				new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
            ECCurve curve = new FPCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
//				ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"),      // n
                BigInteger.One);                                                                                 //1); // h

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            //
            // U side
            //
            IAsymmetricCipherKeyPair U1 = g.GenerateKeyPair();
            IAsymmetricCipherKeyPair U2 = g.GenerateKeyPair();

            IBasicAgreement uAgree = AgreementUtilities.GetBasicAgreement("ECMQV");

            uAgree.Init(new MqvPrivateParameters(
                            (ECPrivateKeyParameters)U1.Private,
                            (ECPrivateKeyParameters)U2.Private,
                            (ECPublicKeyParameters)U2.Public));

            //
            // V side
            //
            IAsymmetricCipherKeyPair V1 = g.GenerateKeyPair();
            IAsymmetricCipherKeyPair V2 = g.GenerateKeyPair();

            IBasicAgreement vAgree = AgreementUtilities.GetBasicAgreement("ECMQV");

            vAgree.Init(new MqvPrivateParameters(
                            (ECPrivateKeyParameters)V1.Private,
                            (ECPrivateKeyParameters)V2.Private,
                            (ECPublicKeyParameters)V2.Public));

            //
            // agreement
            //
            IBigInteger ux = uAgree.CalculateAgreement(new MqvPublicParameters(
                                                           (ECPublicKeyParameters)V1.Public,
                                                           (ECPublicKeyParameters)V2.Public));
            IBigInteger vx = vAgree.CalculateAgreement(new MqvPublicParameters(
                                                           (ECPublicKeyParameters)U1.Public,
                                                           (ECPublicKeyParameters)U2.Public));

            if (!ux.Equals(vx))
            {
                Fail("Agreement failed");
            }
        }
Exemplo n.º 27
0
        public override void PerformTest()
        {
            ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

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

            fact.Init(
                new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    768,
                    25));

            IAsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            IAsymmetricKeyParameter signingKey = keyPair.Private;
            IAsymmetricKeyParameter verifyKey  = keyPair.Public;

            DoTestBadSig(signingKey, verifyKey);

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA1 verification failed");
            }

            sig = SignerUtilities.GetSigner("MD2WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD2 verification failed");
            }

            sig = SignerUtilities.GetSigner("MD5WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD5 verification failed");
            }

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160 verification failed");
            }

            //
            // RIPEMD-128
            //
            sig = SignerUtilities.GetSigner("RIPEMD128WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD128 verification failed");
            }

            //
            // RIPEMD256
            //
            sig = SignerUtilities.GetSigner("RIPEMD256WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD256 verification failed");
            }

            //
            // SHA-224
            //
            sig = SignerUtilities.GetSigner("SHA224WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA224 verification failed");
            }

            //
            // SHA-256
            //
            sig = SignerUtilities.GetSigner("SHA256WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA256 verification failed");
            }

            //
            // SHA-384
            //
            sig = SignerUtilities.GetSigner("SHA384WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA384 verification failed");
            }

            //
            // SHA-512
            //
            sig = SignerUtilities.GetSigner("SHA512WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA512 verification failed");
            }

            //
            // ISO Sigs.
            //
            sig = SignerUtilities.GetSigner("MD5WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD5/ISO verification failed");
            }

            sig = SignerUtilities.GetSigner("SHA1WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA1/ISO verification failed");
            }

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160/ISO verification failed");
            }

            //
            // standard vector test - B.1.3 RIPEMD160, implicit.
            //
            IBigInteger mod = new BigInteger("ffffffff78f6c55506c59785e871211ee120b0b5dd644aa796d82413a47b24573f1be5745b5cd9950f6b389b52350d4e01e90009669a8720bf265a2865994190a661dea3c7828e2e7ca1b19651adc2d5", 16);
            IBigInteger pub = new BigInteger("03", 16);
            IBigInteger pri = new BigInteger("2aaaaaaa942920e38120ee965168302fd0301d73a4e60c7143ceb0adf0bf30b9352f50e8b9e4ceedd65343b2179005b2f099915e4b0c37e41314bb0821ad8330d23cba7f589e0f129b04c46b67dfce9d", 16);

//			KeyFactory  f = KeyFactory.getInstance("RSA");
//			IAsymmetricKeyParameter privKey = f.generatePrivate(new RSAPrivateKeySpec(mod, pri));
//			IAsymmetricKeyParameter pubKey = f.generatePublic(new RSAPublicKeySpec(mod, pub));
            IAsymmetricKeyParameter privKey = new RsaKeyParameters(true, mod, pri);
            IAsymmetricKeyParameter pubKey  = new RsaKeyParameters(false, mod, pub);

            byte[] testSig = Hex.Decode("5cf9a01854dbacaec83aae8efc563d74538192e95466babacd361d7c86000fe42dcb4581e48e4feb862d04698da9203b1803b262105104d510b365ee9c660857ba1c001aa57abfd1c8de92e47c275cae");

            data = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2");

            sig.Init(true, privKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            if (!AreEqual(testSig, sigBytes))
            {
                Fail("SigTest: failed ISO9796-2 generation Test");
            }

            sig.Init(false, pubKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160/ISO verification failed");
            }
        }
Exemplo n.º 28
0
        public override void PerformTest()
        {
            PgpPublicKey pubKey = null;

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

            pubKey = pgpPub.GetPublicKey();

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

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

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

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

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

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            int ch;

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

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

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

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

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

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

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

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

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

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            DateTime testDateTime        = new DateTime(1973, 7, 27);
            Stream   lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Text,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

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

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

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

            dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

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

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

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

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

            pubKey = pgpPub.GetPublicKey();

            int count = 0;

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

                    sigCount++;
                }

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

                count++;
            }

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

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

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

                count++;
            }

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

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

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

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

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

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

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

            kpg.Init(kgp);


            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

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

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
Exemplo n.º 29
0
        // TODO Make private again and call from PerformTest
        public void doTestExceptions()
        {
            // TODO Put back in
//			SecretKeyFactory skF = null;
//
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			KeySpec ks = null;
//			SecretKey secKey = null;
//			byte[] bb = new byte[24];
//
//			try
//			{
//				skF.getKeySpec(null, null);
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				ks = (KeySpec)new DESedeKeySpec(bb);
//				skF.getKeySpec(null, ks.getClass());
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay;
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				skF.getKeySpec(secKey, null);
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}

            try
            {
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator("DESede");

                try
                {
                    kg.Init(new KeyGenerationParameters(new SecureRandom(), int.MinValue));

                    Fail("failed exception test - no exception thrown");
                }
//				catch (InvalidParameterException)
                catch (ArgumentException)
                {
                    // ignore okay
                }
                catch (Exception e)
                {
                    Fail("failed exception test.", e);
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//
//				try
//				{
//					skF.translateKey(null);
//
//					Fail("failed exception test - no exception thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore okay
//				}
//				catch (Exception e)
//				{
//					Fail("failed exception test.", e);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

//			try
//			{
//				byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
//						(byte)137, (byte)138, (byte)140, (byte)143 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/CBC/NoPadding");
//
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if this
//					// cipher is being
//					// initialized for decryption and requires algorithm parameters
//					// that cannot be determined from the given key
////					cipher.Init(false, cipherKey, (SecureRandom)null);
//					cipher.Init(false, new ParametersWithRandom(cipherKey, new SecureRandom()));
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
//				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118 };
                byte[] rawDESKey = { 128, 131, 133, 134, 137, 138 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");

//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
                try
                {
                    KeyParameter cipherKey = new DesParameters(rawDESKey);

                    // According specification engineInit(int opmode, Key key,
                    // SecureRandom random) throws InvalidKeyException if the given
                    // key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);

//					Fail("failed exception test - no InvalidKeyException thrown");
                    Fail("failed exception test - no ArgumentException thrown");
                }
//				catch (InvalidKeyException)
                catch (ArgumentException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

//			try
//			{
////				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118, -117, -115, -114 };
//				byte[] rawDESKey = { 128, 131, 133, 134, 137, 138, 139, 141, 142 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if the given
//					// key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}


            try
            {
                byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
                                     (byte)137, (byte)138, (byte)140, (byte)143 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
                KeyParameter cipherKey = new DesParameters(rawDESKey);

                IBufferedCipher ecipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
                ecipher.Init(true, cipherKey);

                byte[] cipherText = new byte[0];
                try
                {
                    // According specification Method engineUpdate(byte[] input,
                    // int inputOffset, int inputLen, byte[] output, int
                    // outputOffset)
                    // throws ShortBufferException - if the given output buffer is
                    // too
                    // small to hold the result
//					ecipher.update(new byte[20], 0, 20, cipherText);
                    ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0);

//					Fail("failed exception test - no ShortBufferException thrown");
                    Fail("failed exception test - no DataLengthException thrown");
                }
//				catch (ShortBufferException)
                catch (DataLengthException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//
//				keyGen.init((SecureRandom)null);
//
//				// According specification engineGenerateKey() doesn't throw any exceptions.
//
//				SecretKey key = keyGen.generateKey();
//				if (key == null)
//				{
//					Fail("key is null!");
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			try
//			{
//				AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");
//
//				algParams.init(new IvParameterSpec(new byte[8]));
//
//				// According specification engineGetEncoded() returns
//				// the parameters in their primary encoding format. The primary
//				// encoding
//				// format for parameters is ASN.1, if an ASN.1 specification for
//				// this type
//				// of parameters exists.
//				byte[] iv = algParams.getEncoded();
//
//				if (iv.Length!= 10)
//				{
//					Fail("parameters encoding wrong length - "  + iv.Length);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
                try
                {
//					AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");

                    byte[] encoding = new byte[10];
                    encoding[0] = 3;
                    encoding[1] = 8;

//					algParams.init(encoding, "ASN.1");
                    ParameterUtilities.GetCipherParameters(
                        "AES",
                        ParameterUtilities.CreateKeyParameter("AES", new byte[16]),
                        Asn1Object.FromByteArray(encoding));

//					Fail("failed exception test - no IOException thrown");
                    Fail("failed exception test - no Exception thrown");
                }
//				catch (IOException)
                catch (ArgumentException)
                {
                    // okay
                }

//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PublicKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(true, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for public key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
//
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PrivateKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(false, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for private key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }
        }
Exemplo n.º 30
0
        private const string alg = "1.2.840.113549.1.12.1.3";         // 3 key triple DES with SHA-1

        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");

            fact.Init(new KeyGenerationParameters(new SecureRandom(), 512));

            AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            AsymmetricKeyParameter priKey = keyPair.Private;
            AsymmetricKeyParameter pubKey = keyPair.Public;

            //
            // set up the parameters
            //
            byte[]        salt           = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int           iterationCount = 100;
            Asn1Encodable defParams      = PbeUtilities.GenerateAlgorithmParameters(alg, salt, iterationCount);

            char[] password1 = { 'h', 'e', 'l', 'l', 'o' };

//				AlgorithmParameters parameters = AlgorithmParameters.getInstance(alg);
//
//				parameters.init(defParams);

            //
            // set up the key
            //
//				PBEKeySpec pbeSpec = new PBEKeySpec(password1);
//				SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg);

//				IBufferedCipher cipher = CipherUtilities.GetCipher(alg);
            IWrapper wrapper = WrapperUtilities.GetWrapper(alg);

            ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(
                alg, password1, defParams);

//				cipher.Init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters);
            wrapper.Init(true, parameters);

//				byte[] wrappedKey = cipher.Wrap(priKey);
            byte[] pkb        = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded();
            byte[] wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length);

            //
            // create encrypted object
            //

            // TODO Figure out what this was supposed to do
//				EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(parameters, wrappedKey);
            PrivateKeyInfo          plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey);
            EncryptedPrivateKeyInfo pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg, password1, salt, iterationCount, plain);


            //
            // decryption step
            //
            char[] password2 = { 'h', 'e', 'l', 'l', 'o' };

//				pbeSpec = new PBEKeySpec(password2);
//
//				cipher = CipherUtilities.GetCipher(pInfo.EncryptionAlgorithm);
//
//				cipher.Init(false, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
//
//				PKCS8EncodedKeySpec keySpec = pInfo.getKeySpec(cipher);
            PrivateKeyInfo decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo);

//				if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded()))
            if (!decrypted.Equals(plain))
            {
                Fail("Private key does not match");
            }

            //
            // using ICipherParameters test
            //
//			pbeSpec = new PBEKeySpec(password1);
//			keyFact = SecretKeyFactory.getInstance(alg);
//			cipher = CipherUtilities.GetCipher(alg);
            wrapper = WrapperUtilities.GetWrapper(alg);

//			cipher.init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters);
            wrapper.Init(true, parameters);

//			wrappedKey = cipher.wrap(priKey);
            wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length);

            //
            // create encrypted object
            //

            // TODO Figure out what this was supposed to do
//			pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey);
            plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey);
            pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg, password1, salt, iterationCount, plain);

            //
            // decryption step
            //
//			pbeSpec = new PBEKeySpec(password2);
//
//			cipher = CipherUtilities.GetCipher(pInfo.getAlgName());
//
//			cipher.init(IBufferedCipher.DECRYPT_MODE, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
//
//			keySpec = pInfo.getKeySpec(cipher);
            decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo);

//			if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded()))
            if (!decrypted.Equals(plain))
            {
                Fail("Private key does not match");
            }
        }