Пример #1
0
        public byte[] ProcessBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            agree.Init(privParam);

            BigInteger z = agree.CalculateAgreement(pubParam);

            byte[] zBytes = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), z);

            return(forEncryption
                ?       EncryptBlock(input, inOff, inLen, zBytes)
                :       DecryptBlock(input, inOff, inLen, zBytes));
        }
        private static byte[] GetKeyingMaterial(PushSubscription subscription, AsymmetricKeyParameter applicationServerPrivateKey, byte[] applicationServerPublicKey)
        {
            IBasicAgreement ecdhAgreement = AgreementUtilities.GetBasicAgreement("ECDH");

            ecdhAgreement.Init(applicationServerPrivateKey);

            byte[] userAgentPublicKey   = UrlBase64Converter.FromUrlBase64String(subscription.GetKey(PushEncryptionKeyName.P256DH));
            byte[] authenticationSecret = UrlBase64Converter.FromUrlBase64String(subscription.GetKey(PushEncryptionKeyName.Auth));
            byte[] sharedSecret         = ecdhAgreement.CalculateAgreement(ECKeyHelper.GetECPublicKeyParameters(userAgentPublicKey)).ToByteArrayUnsigned();
            byte[] sharedSecretHash     = HmacSha256(authenticationSecret, sharedSecret);
            byte[] infoParameter        = GetKeyingMaterialInfoParameter(userAgentPublicKey, applicationServerPublicKey);
            byte[] keyingMaterial       = HmacSha256(sharedSecretHash, infoParameter);

            return(keyingMaterial);
        }
Пример #3
0
        public byte[] ProcessBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            agree.Init(privParam);

            BigInteger z = agree.CalculateAgreement(pubParam);

            // TODO Is a fixed length result expected?
            byte[] zBytes = z.ToByteArrayUnsigned();

            return(forEncryption
                                ?       EncryptBlock(input, inOff, inLen, zBytes)
                :       DecryptBlock(input, inOff, inLen, zBytes));
        }
Пример #4
0
        public byte[] ProcessBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            agree.Init(privParam);

            BigInteger z = agree.CalculateAgreement(pubParam);

            // TODO Check that this is right (...Unsigned? Check length?)
            byte[] zBytes = z.ToByteArray();

            return(forEncryption
                                ?       EncryptBlock(input, inOff, inLen, zBytes)
                :       DecryptBlock(input, inOff, inLen, zBytes));
        }
Пример #5
0
        /**
         * Add a key agreement based recipient.
         *
         * @param agreementAlgorithm key agreement algorithm to use.
         * @param senderPrivateKey private key to initialise sender side of agreement with.
         * @param senderPublicKey sender public key to include with message.
         * @param recipientCert recipient's public key certificate.
         * @param cekWrapAlgorithm OID for key wrapping algorithm to use.
         * @exception SecurityUtilityException if the algorithm requested cannot be found
         * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
         */
        public void AddKeyAgreementRecipient(
            string agreementAlgorithm,
            AsymmetricKeyParameter senderPrivateKey,
            AsymmetricKeyParameter senderPublicKey,
            X509Certificate recipientCert,
            string cekWrapAlgorithm)
        {
            if (!senderPrivateKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "senderPrivateKey");
            }
            if (senderPublicKey.IsPrivate)
            {
                throw new ArgumentException("Expected public key", "senderPublicKey");
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreementAlgorithm, cekWrapAlgorithm);

            agreement.Init(new ParametersWithRandom(senderPrivateKey, rand));

            BigInteger secretNum = agreement.CalculateAgreement(recipientCert.GetPublicKey());

            try
            {
                SubjectPublicKeyInfo oPubKeyInfo =
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(senderPublicKey);

                OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
                    new OriginatorPublicKey(
                        new AlgorithmIdentifier(oPubKeyInfo.AlgorithmID.ObjectID, DerNull.Instance),
                        oPubKeyInfo.PublicKeyData.GetBytes()));

                // TODO Fix the way bytes are derived from the secret
                byte[]       secretBytes = secretNum.ToByteArrayUnsigned();
                KeyParameter secret      = ParameterUtilities.CreateKeyParameter(
                    cekWrapAlgorithm, secretBytes);

                recipientInfs.Add(
                    new RecipientInf(cekWrapAlgorithm, secret, agreementAlgorithm,
                                     cekWrapAlgorithm, originator, recipientCert));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }
        }
Пример #6
0
        private byte[] GenerateAESKey(ECPublicKeyParameters bobPublicKey, AsymmetricKeyParameter alicePrivateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(alicePrivateKey);
            BigInteger sharedSecret = aKeyAgree.CalculateAgreement(bobPublicKey);

            byte[] sharedSecretBytes = sharedSecret.ToByteArray();

            IDigest digest = new Sha256Digest();

            byte[] symmetricKey = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length);
            digest.DoFinal(symmetricKey, 0);

            return(symmetricKey);
        }
Пример #7
0
        public byte[] ProcessBlock(
            byte[] input,
            int inOff,
            int inLen,
            byte[] macData)
        {
            // Compute the common value and convert to byte array.
            _agreement.Init(_privParam);
            BigInteger zAsInteger = _agreement.CalculateAgreement(_pubParam);

            byte[] z = BigIntegers.AsUnsignedByteArray(_agreement.GetFieldSize(), zAsInteger);

            _kdfKey = _optimizedKdf.Derive(z);

            return(_forEncryption
                ? EncryptBlock(input, inOff, inLen, macData)
                : DecryptBlock(input, inOff, inLen, macData));
        }
Пример #8
0
        public virtual byte[] ProcessBlock(byte[] input, int inOff, int inLen)
        {
            agree.Init(privParam);
            BigInteger n = agree.CalculateAgreement(pubParam);

            byte[] array = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), n);
            try
            {
                return((!forEncryption) ? DecryptBlock(input, inOff, inLen, array) : EncryptBlock(input, inOff, inLen, array));

IL_005f:
                byte[] result;
                return(result);
            }
            finally
            {
                Array.Clear(array, 0, array.Length);
            }
        }
Пример #9
0
        public void TestSubgroupConfinement()
        {
            DHParameters parameters = Ike2048();
            BigInteger   p = parameters.P, g = parameters.G;

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

            //keyGen.initialize(params);
            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), parameters));

            AsymmetricCipherKeyPair kp               = keyGen.GenerateKeyPair();
            AsymmetricKeyParameter  priv             = kp.Private;

            IBasicAgreement ka = AgreementUtilities.GetBasicAgreement("DH");

            BigInteger[] weakPublicKeys = { BigInteger.Zero,       BigInteger.One, p.Subtract(BigInteger.One), p,
                                            p.Add(BigInteger.One), BigInteger.One.Negate() };

            foreach (BigInteger weakKey in weakPublicKeys)
            {
                try
                {
                    new DHPublicKeyParameters(weakKey, parameters);
                    Fail("Generated weak public key");
                }
                catch (ArgumentException ex)
                {
                    IsTrue("wrong message (constructor)", ex.Message.StartsWith("invalid DH public key"));
                }

                ka.Init(priv);

                try
                {
                    ka.CalculateAgreement(new DHWeakPubKey(weakKey, parameters));
                    Fail("Generated secrets with weak public key");
                }
                catch (ArgumentException ex)
                {
                    IsTrue("wrong message (CalculateAgreement)", "Diffie-Hellman public key is weak".Equals(ex.Message));
                }
            }
        }
Пример #10
0
        private void GetShardSecret()
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(this.merchantPrivateKey);
            BigInteger SharedSecret = aKeyAgree.CalculateAgreement(this.ephemeralPublicKey);

            byte[] tmpSharedSecret = SharedSecret.ToByteArray();

            if (tmpSharedSecret.Length > 32)
            {
                this.sharedSecret = new byte[tmpSharedSecret.Length - 1];
                Array.Copy(tmpSharedSecret, 1, this.sharedSecret, 0, tmpSharedSecret.Length - 1);
            }
            else
            {
                this.sharedSecret = tmpSharedSecret;
            }
        }
Пример #11
0
        public byte[] ProcessBlock(
            byte[]  input,
            int inOff,
            int inLen)
        //throws InvalidCipherTextException
        {
            agree.Init(privParam);

            BigInteger z = agree.CalculateAgreement(pubParam);

            if (forEncryption)
            {
                return(EncryptBlock(input, inOff, inLen, z.ToByteArray()));
            }
            else
            {
                return(DecryptBlock(input, inOff, inLen, z.ToByteArray()));
            }
        }
Пример #12
0
        public byte[] ProcessBlock(
            byte[] input,
            int inOff,
            int inLen,
            byte[] macData)
        {
            // Compute the common value and convert to byte array.
            _agreement.Init(_privParam);
            BigInteger zAsInteger = _agreement.CalculateAgreement(_pubParam);

            byte[] z = BigIntegers.AsUnsignedByteArray(_agreement.GetFieldSize(), zAsInteger);

            // Create input to KDF.
            byte[] vz;
//        if (V.Length != 0)
//        {
//            VZ = new byte[V.Length + Z.Length];
//            Array.Copy(V, 0, VZ, 0, V.Length);
//            Array.Copy(Z, 0, VZ, V.Length, Z.Length);
//        }
//        else
            {
                vz = z;
            }

            // Initialise the KDF.
            IDerivationParameters kdfParam;

            if (_kdf is Mgf1BytesGenerator)
            {
                kdfParam = new MgfParameters(vz);
            }
            else
            {
                kdfParam = new KdfParameters(vz, _iesParameters.GetDerivationV());
            }
            _kdf.Init(kdfParam);

            return(_forEncryption
                ? EncryptBlock(input, inOff, inLen, macData)
                : DecryptBlock(input, inOff, inLen, macData));
        }
Пример #13
0
        public void TestExceptions()
        {
            DHParameters dhParams = new DHParameters(p512, g512);

            try
            {
                IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement("DH");

//				aKeyAgreeBasic.generateSecret("DES");
                aKeyAgreeBasic.CalculateAgreement(null);
            }
            catch (InvalidOperationException)
            {
                // okay
            }
            catch (Exception e)
            {
                Fail("Unexpected exception: " + e, e);
            }
        }
Пример #14
0
        public static BigInteger CalculateSharedKey(BigInteger BIx, BigInteger BIy, ECPrivateKeyParameters privateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(privateKey);

            X9ECParameters     ecP    = NistNamedCurves.GetByName("P-521");
            ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());

            FpCurve c = (FpCurve)ecSpec.Curve;

            ECFieldElement x = new FpFieldElement(c.Q, BIx);
            ECFieldElement y = new FpFieldElement(c.Q, BIy);
            ECPoint        q = new FpPoint(ecP.Curve, x, y);

            ECPublicKeyParameters publicKey = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);

            BigInteger k1 = aKeyAgree.CalculateAgreement(publicKey);

            return(k1);
        }
Пример #15
0
        static byte[] GetSharedKey(ECPrivateKeyParameters sigPrivKey, byte[] serverPubKey)
        {
            Console.WriteLine("Generating shared key!");

            var ecP = ECNamedCurveTable.GetByName("secp256k1");

            var domainParams = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());

            Org.BouncyCastle.Math.EC.ECPoint point = domainParams.Curve.DecodePoint(serverPubKey);

            ECPublicKeyParameters oEcPublicKeyParameters = new ECPublicKeyParameters(point, domainParams);

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

            aKeyAgree.Init(sigPrivKey);

            var sharedKey = aKeyAgree.CalculateAgreement(oEcPublicKeyParameters).ToByteArray();

            Console.WriteLine($"{sharedKey.Length} bytes Created shared key ({ToHex(sharedKey)})");

            return(sharedKey);
        }
Пример #16
0
        public virtual byte[] ProcessBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            agree.Init(privParam);

            BigInteger z = agree.CalculateAgreement(pubParam);

            byte[] zBytes = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), z);

            try
            {
                return(forEncryption
                    ?   EncryptBlock(input, inOff, inLen, zBytes)
                    :   DecryptBlock(input, inOff, inLen, zBytes));
            }
            finally
            {
                Array.Clear(zBytes, 0, zBytes.Length);
            }
        }
Пример #17
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));
        }
Пример #19
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(),
            });
        }
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
//			Key key)
            ICipherParameters key)
        {
            if (!(key is AsymmetricKeyParameter))
            {
                throw new ArgumentException("KeyAgreement requires asymmetric key", "key");
            }

            AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)key;

            if (!privKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "key");
            }

            try
            {
                OriginatorPublicKey    origK    = _info.Originator.OriginatorKey;
                PrivateKeyInfo         privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
                SubjectPublicKeyInfo   pubInfo  = new SubjectPublicKeyInfo(privInfo.AlgorithmID, origK.PublicKey.GetBytes());
                AsymmetricKeyParameter pubKey   = PublicKeyFactory.CreateKey(pubInfo);

                string wrapAlg = DerObjectIdentifier.GetInstance(
                    Asn1Sequence.GetInstance(_keyEncAlg.Parameters)[0]).Id;

                IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    _keyEncAlg.ObjectID, wrapAlg);

                agreement.Init(privKey);

                BigInteger wKeyNum = agreement.CalculateAgreement(pubKey);
                // TODO Fix the way bytes are derived from the secret
                byte[]       wKeyBytes = wKeyNum.ToByteArrayUnsigned();
                KeyParameter wKey      = ParameterUtilities.CreateKeyParameter(wrapAlg, wKeyBytes);

                IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);

                keyCipher.Init(false, wKey);

                AlgorithmIdentifier aid = _encAlg;
                string alg = aid.ObjectID.Id;

                byte[] encryptedKey = _encryptedKey.GetOctets();
                byte[] sKeyBytes    = keyCipher.Unwrap(encryptedKey, 0, encryptedKey.Length);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(alg, sKeyBytes);

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (Exception e)
            {
                throw new CmsException("originator key invalid.", e);
            }
        }
Пример #21
0
 public BigInteger GenerateAgreementValue(AsymmetricKeyParameter remotePublicKey)
 {
     return(agreement.CalculateAgreement(remotePublicKey));
 }
        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))));
        }
Пример #23
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");
            }
        }
Пример #24
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))));
        }
Пример #25
0
        public virtual byte[] ProcessBlock(
            byte[] @in,
            int inOff,
            int inLen)
        {
            if (ForEncryption)
            {
                if (KeyPairGenerator != null)
                {
                    EphemeralKeyPair ephKeyPair = KeyPairGenerator.Generate();

                    PrivParam = ephKeyPair.GetKeyPair().Private;
                    V         = ephKeyPair.GetEncodedPublicKey();
                }
            }
            else
            {
                if (KeyParser != null)
                {
                    MemoryStream bIn = new MemoryStream(@in, inOff, inLen)
                    {
                        Position = 0
                    };
                    try
                    {
                        PubParam = KeyParser.ReadKey(bIn);
                    }
                    catch (IOException e)
                    {
                        throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.Message, e);
                    }
                    catch (ArgumentException e)
                    {
                        throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.Message, e);
                    }

                    int encLength = (inLen - (int)(bIn.Length - bIn.Position));
                    V = Arrays.CopyOfRange(@in, inOff, inOff + encLength);
                }
            }

            // Compute the common value and convert to byte array.
            Agree.Init(PrivParam);
            BigInteger z = Agree.CalculateAgreement(PubParam);

            byte[] bigZ = BigIntegers.AsUnsignedByteArray(Agree.GetFieldSize(), z);

            // Create input to KDF.
            if (V.Length != 0)
            {
                byte[] vz = Arrays.Concatenate(V, bigZ);
                Arrays.Fill(bigZ, 0);
                bigZ = vz;
            }

            try
            {
                // Initialise the KDF.
                KdfParameters kdfParam = new KdfParameters(bigZ, _param.GetDerivationV());
                Kdf.Init(kdfParam);

                return(ForEncryption
                    ? EncryptBlock(@in, inOff, inLen)
                    : DecryptBlock(@in, inOff, inLen));
            }
            finally
            {
                Arrays.Fill(bigZ, 0);
            }
        }
        static void Main(string[] args)
        {
            var privateKey = "pX/BvdXXUdpC79mW/jWi10Z6PJb5SBY2+aqkR/qYOjqgakKsqZFKnl0kz10Ve+BP";
            var token      = "BDiRKNnPiPUb5oala31nkmCaXMB0iyWy3Q93p6fN7vPxEQSUlFVsInkJzPBBqmW1FUIY1KBA3BQb3W3Qv4akZ8kblqbmvupE/EJzPKbROZFBNvxpvVOHHgO2qadmHAjHSmnxUuxrpKxopWnOgyhzUx+mBUTao0pcEgqZFw0Y/qZIJPf1KusCMlz5TAhpjsw=";

            // #####
            // ##### Step 1
            // #####
            var decodedToken = Convert.FromBase64String(token);
            var decodedEphemeralPublicKey      = decodedToken.Take(97).ToArray();
            var encodedEphemeralPublicKeyCheck = Convert.ToBase64String(decodedEphemeralPublicKey);

            if (encodedEphemeralPublicKeyCheck != "BDiRKNnPiPUb5oala31nkmCaXMB0iyWy3Q93p6fN7vPxEQSUlFVsInkJzPBBqmW1FUIY1KBA3BQb3W3Qv4akZ8kblqbmvupE/EJzPKbROZFBNvxpvVOHHgO2qadmHAjHSg==")
            {
                throw new Exception("Public key check failed");
            }

            X9ECParameters        curveParams           = ECNamedCurveTable.GetByName("secp384r1");
            ECPoint               decodePoint           = curveParams.Curve.DecodePoint(decodedEphemeralPublicKey);
            ECDomainParameters    domainParams          = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H, curveParams.GetSeed());
            ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(decodePoint, domainParams);

            var x = ecPublicKeyParameters.Q.AffineXCoord.ToBigInteger();
            var y = ecPublicKeyParameters.Q.AffineYCoord.ToBigInteger();

            if (!x.Equals(new BigInteger("8706462696031173094919866327685737145866436939551712382591956952075131891462487598200779332295613073905587629438229")))
            {
                throw new Exception("X coord check failed");
            }

            if (!y.Equals(new BigInteger("10173258529327482491525749925661342501140613951412040971418641469645769857676705559747557238888921287857458976966474")))
            {
                throw new Exception("Y coord check failed");
            }

            Console.WriteLine("Step 1 complete");

            // #####
            // ##### Step 2
            // #####
            var privateKeyBytes        = Convert.FromBase64String(privateKey);
            var ecPrivateKeyParameters = new ECPrivateKeyParameters("ECDHC", new BigInteger(1, privateKeyBytes), domainParams);
            var privateKeyInfo         = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecPrivateKeyParameters);
            var ecPrivateKey           = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privateKeyInfo);

            IBasicAgreement agree = AgreementUtilities.GetBasicAgreement("ECDHC");

            agree.Init(ecPrivateKey);
            BigInteger sharedKey       = agree.CalculateAgreement(ecPublicKeyParameters);
            var        sharedKeyBytes  = sharedKey.ToByteArrayUnsigned();
            var        sharedKeyBase64 = Convert.ToBase64String(sharedKeyBytes);

            if (sharedKeyBase64 != "2lvSJsBO2keUHRfvPG6C1RMUmGpuDbdgNrZ9YD7RYnvAcfgq/fjeYr1p0hWABeif")
            {
                throw new Exception("Shared key check failed");
            }

            Console.WriteLine("Step 2 complete");

            // #####
            // ##### Step 3
            // #####
            var kdf2Bytes  = Kdf2(sharedKeyBytes, decodedEphemeralPublicKey);
            var kdf2Base64 = Convert.ToBase64String(kdf2Bytes);

            if (kdf2Base64 != "mAzkYatDlz4SzrCyM23NhgL/+mE3eGgfUz9h1CFPhZOtXequzN3Q8w+B5GE2eU5g")
            {
                throw new Exception("Kdf2 failed");
            }

            Console.WriteLine("Step 3 complete");

            // #####
            // ##### Step 4
            // #####
            var decryptionKeyBytes = kdf2Bytes.Take(32).ToArray();
            var decryptionIvBytes  = kdf2Bytes.Skip(32).ToArray();

            var decryptionKeyBase64 = Convert.ToBase64String(decryptionKeyBytes);
            var decryptionIvBase64  = Convert.ToBase64String(decryptionIvBytes);

            if (decryptionKeyBase64 != "mAzkYatDlz4SzrCyM23NhgL/+mE3eGgfUz9h1CFPhZM=")
            {
                throw new Exception("Decryption key check failed");
            }

            if (decryptionIvBase64 != "rV3qrszd0PMPgeRhNnlOYA==")
            {
                throw new Exception("Decryption iv check failed");
            }

            var encryptedDataBytes = decodedToken.Skip(97).Take(decodedToken.Length - 113).ToArray();
            var tagBytes           = decodedToken.Skip(decodedToken.Length - 16).ToArray();

            var encryptedDataBase64 = Convert.ToBase64String(encryptedDataBytes);
            var tagBase64           = Convert.ToBase64String(tagBytes);

            if (encryptedDataBase64 != "afFS7GukrGilac6DKHNTH6YFRNqjSlwSCpkXDRj+")
            {
                throw new Exception("Encrypted data check failed");
            }

            if (tagBase64 != "pkgk9/Uq6wIyXPlMCGmOzA==")
            {
                throw new Exception("Tag check failed");
            }

            KeyParameter     keyParam   = ParameterUtilities.CreateKeyParameter("AES", decryptionKeyBytes);
            ParametersWithIV parameters = new ParametersWithIV(keyParam, decryptionIvBytes);
            IBufferedCipher  cipher     = CipherUtilities.GetCipher("AES/GCM/NoPadding");

            cipher.Init(false, parameters);
            var resultBytes  = cipher.DoFinal(encryptedDataBytes.Concat(tagBytes).ToArray());
            var resultBase64 = Convert.ToBase64String(resultBytes);
            var resultString = Strings.FromByteArray(resultBytes);

            if (resultString != "xXTi32iZwrQ6O8Sy6r1isKwF6Ff1Py")
            {
                throw new Exception("Decryption failed");
            }

            Console.WriteLine("Step 4 complete");
            Console.WriteLine(resultString);

            Console.WriteLine();
            Console.WriteLine("Done... press any key to finish");
            Console.ReadLine();
        }
Пример #27
0
        private void doTestGP(
            string algName,
            int size,
            int privateValueSize,
            IBigInteger g,
            IBigInteger p)
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            DHParameters            dhParams = new DHParameters(p, g, null, privateValueSize);
            KeyGenerationParameters kgp      = new DHKeyGenerationParameters(new SecureRandom(), dhParams);

            keyGen.Init(kgp);

            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);

            checkKeySize(privateValueSize, aKeyPair);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);

            checkKeySize(privateValueSize, bKeyPair);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
//			bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
//			IBigInteger  k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
//			IBigInteger  k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
            IBigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            IBigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(size + " bit 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance(algName);
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			DHPublicKey         pubKey = (DHPublicKey)keyFac.generatePublic(pubX509);
            DHPublicKeyParameters pubKey = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);
//			DHParameterSpec     spec = pubKey.Parameters;
            DHParameters spec = pubKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit public key encoding/decoding test failed on parameters");
            }

            if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key encoding/decoding test failed on y value");
            }

            //
            // public key serialisation test
            //
            // TODO Put back in
//			MemoryStream bOut = new MemoryStream();
//			ObjectOutputStream oOut = new ObjectOutputStream(bOut);
//
//			oOut.WriteObject(aKeyPair.Public);
//
//			MemoryStream bIn = new MemoryStream(bOut.ToArray(), false);
//			ObjectInputStream oIn = new ObjectInputStream(bIn);
//
//			pubKey = (DHPublicKeyParameters)oIn.ReadObject();
            spec = pubKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit public key serialisation test failed on parameters");
            }

            if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key serialisation test failed on y value");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();
//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8);
            DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

            spec = privKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit private key encoding/decoding test failed on parameters");
            }

            if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key encoding/decoding test failed on y value");
            }

            //
            // private key serialisation test
            //
            // TODO Put back in
//			bOut = new MemoryStream();
//			oOut = new ObjectOutputStream(bOut);
//
//			oOut.WriteObject(aKeyPair.Private);
//
//			bIn = new MemoryStream(bOut.ToArray(), false);
//			oIn = new ObjectInputStream(bIn);
//
//			privKey = (DHPrivateKeyParameters)oIn.ReadObject();
            spec = privKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit private key serialisation test failed on parameters");
            }

            if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key serialisation test failed on y value");
            }

            //
            // three party test
            //
            IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            IAsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair();

            IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            IAsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair();

            IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            IAsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair();


            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            aKeyAgree.Init(aPair.Private);

            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            bKeyAgree.Init(bPair.Private);

            IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            cKeyAgree.Init(cPair.Private);

//			Key ac = aKeyAgree.doPhase(cPair.Public, false);
//			Key ba = bKeyAgree.doPhase(aPair.Public, false);
//			Key cb = cKeyAgree.doPhase(bPair.Public, false);
//
//			aKeyAgree.doPhase(cb, true);
//			bKeyAgree.doPhase(ac, true);
//			cKeyAgree.doPhase(ba, true);
//
//			IBigInteger aShared = new BigInteger(aKeyAgree.generateSecret());
//			IBigInteger bShared = new BigInteger(bKeyAgree.generateSecret());
//			IBigInteger cShared = new BigInteger(cKeyAgree.generateSecret());

            DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec);
            DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec);
            DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec);

            IBigInteger aShared = aKeyAgree.CalculateAgreement(cb);
            IBigInteger bShared = bKeyAgree.CalculateAgreement(ac);
            IBigInteger cShared = cKeyAgree.CalculateAgreement(ba);

            if (!aShared.Equals(bShared))
            {
                Fail(size + " bit 3-way test failed (a and b differ)");
            }

            if (!cShared.Equals(bShared))
            {
                Fail(size + " bit 3-way test failed (c and b differ)");
            }
        }
Пример #28
0
        public void doTestCurve(
            string name)
        {
//			ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
            ECDomainParameters ecSpec = GetCurveParameters(name);

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

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

            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();

//			KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDHC");
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC");

            aKeyAgree.Init(aKeyPair.Private);

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();

//			KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDHC");
            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC");

            bKeyAgree.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgree.doPhase(bKeyPair.Public, true);
//			bKeyAgree.doPhase(aKeyPair.Public, true);
//
//			BigInteger k1 = new BigInteger(aKeyAgree.generateSecret());
//			BigInteger k2 = new BigInteger(bKeyAgree.generateSecret());
            BigInteger k1 = aKeyAgree.CalculateAgreement(bKeyPair.Public);
            BigInteger k2 = bKeyAgree.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail("2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = aKeyPair.Public.getEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance("ECDH");
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey         pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

//			if (!pubKey.getW().Equals(((ECPublicKey)aKeyPair.Public).getW()))
            if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q))
            {
                Fail("public key encoding (Q test) failed");
            }

            // TODO Put back in?
//			if (!(pubKey.getParams() is ECNamedCurveSpec))
//			{
//				Fail("public key encoding not named curve");
//			}

            //
            // private key encoding test
            //
//			byte[]              privEnc = aKeyPair.Private.getEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
            {
                Fail("private key encoding (S test) failed");
            }

            // TODO Put back in?
//			if (!(privKey.getParams() is ECNamedCurveSpec))
//			{
//				Fail("private key encoding not named curve");
//			}
//
//			ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
//			if (!(privSpec.GetName().Equals(name) || privSpec.GetName().Equals(CurveNames.get(name))))
//			{
//				Fail("private key encoding wrong named curve. Expected: "
//					+ CurveNames[name] + " got " + privSpec.GetName());
//			}
        }
Пример #29
0
        private void doTestECDH(
            string algorithm)
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm);

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

            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
//			bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
//			IBigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
//			IBigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
            IBigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            IBigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(algorithm + " 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[] pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory keyFac = KeyFactory.getInstance(algorithm);
//			X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

            ECDomainParameters ecDP = pubKey.Parameters;

//			if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW()))
            if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q))
            {
//				Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX());
//				Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY());
//				Fail(algorithm + " public key encoding (W test) failed");
                Console.WriteLine(" expected " + pubKey.Q.X.ToBigInteger()
                                  + " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.X.ToBigInteger());
                Console.WriteLine(" expected " + pubKey.Q.Y.ToBigInteger()
                                  + " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.Y.ToBigInteger());
                Fail(algorithm + " public key encoding (Q test) failed");
            }

//			if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator()))
            if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G))
            {
                Fail(algorithm + " public key encoding (G test) failed");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
            {
//				Fail(algorithm + " private key encoding (S test) failed");
                Fail(algorithm + " private key encoding (D test) failed");
            }

//			if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator()))
            if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G))
            {
                Fail(algorithm + " private key encoding (G test) failed");
            }
        }
Пример #30
0
    public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
    {
        byte[] key = contentEncryptionKey.GetKey();
        AsymmetricKeyParameter    @public          = senderKeyPair.Public;
        ICipherParameters         cipherParameters = senderKeyPair.Private;
        OriginatorIdentifierOrKey originator;

        try
        {
            originator = new OriginatorIdentifierOrKey(CreateOriginatorPublicKey(@public));
        }
        catch (IOException arg)
        {
            throw new InvalidKeyException("cannot extract originator public key: " + arg);
        }
        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 arg2)
            {
                throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + arg2);
            }
            catch (SecurityUtilityException arg3)
            {
                throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + arg3);
            }
        }
        DerSequence         parameters             = new DerSequence(keyEncryptionOID, DerNull.Instance);
        AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(keyAgreementOID, parameters);
        Asn1EncodableVector asn1EncodableVector    = new Asn1EncodableVector();

        foreach (X509Certificate recipientCert in recipientCerts)
        {
            TbsCertificateStructure instance;
            try
            {
                instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
            }
            catch (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 = recipientCert.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));
        }
        return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncryptionAlgorithm, new DerSequence(asn1EncodableVector))));
    }