Ejemplo n.º 1
0
    //sets and displays theta1 each frame
    void Update()
    {
        theta = RobotBase.eulerAngles.y;

        //sets and displays theta
        if (theta == 0f)
        {
            x = 0f;
        }
        else
        {
            x = 360f;
        }

        DHParameters.setTheta1(x - theta);
        theta1Text.text = "" + (x - theta);
    }
Ejemplo n.º 2
0
    public static void Main(string[] args)
    {
        DiffieHellman diffieHellman  = new DiffieHellmanManaged();
        DHParameters  dHParameters   = diffieHellman.ExportParameters(includePrivate: false);
        DiffieHellman diffieHellman2 = new DiffieHellmanManaged(dHParameters.P, dHParameters.G, 160);

        byte[] keyEx  = diffieHellman.CreateKeyExchange();
        byte[] keyEx2 = diffieHellman2.CreateKeyExchange();
        byte[] bytes  = diffieHellman.DecryptKeyExchange(keyEx2);
        byte[] bytes2 = diffieHellman2.DecryptKeyExchange(keyEx);
        Console.WriteLine("Computed secret of instance 1:");
        PrintBytes(bytes);
        Console.WriteLine("\r\nComputed secret of instance 2:");
        PrintBytes(bytes2);
        Console.WriteLine("\r\nPress ENTER to continue...");
        Console.ReadLine();
    }
Ejemplo n.º 3
0
        public static DHParameters ValidateDHParameters(DHParameters parameters)
        {
            BigInteger p = parameters.P;
            BigInteger g = parameters.G;

            if (!p.IsProbablePrime(2))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            if (g.CompareTo(Two) < 0 || g.CompareTo(p.Subtract(Two)) > 0)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }


            return(parameters);
        }
Ejemplo n.º 4
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(AlertDescription.bad_certificate);
            }

            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);

            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            if (mTlsSigner == null)
            {
                try
                {
                    this.mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey((DHPublicKeyParameters)this.mServerPublicKey);
                    this.mDHParameters     = ValidateDHParameters(mDHAgreePublicKey.Parameters);
                }
                catch (InvalidCastException e)
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown, e);
                }

                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyAgreement);
            }
            else
            {
                if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }

                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
            }

            base.ProcessServerCertificate(serverCertificate);
        }
Ejemplo n.º 5
0
        public DiffieHellmanObject CreateBob(DiffieHellmanObject alice)
        {
            var bobKeyGen     = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            var bobParameters = new DHParameters(alice.PrimInteger, alice.NaturalInteger);

            bobKeyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), bobParameters));

            var bobKeyPair = bobKeyGen.GenerateKeyPair();

            return(new DiffieHellmanObject
            {
                PublicKey = bobKeyPair.Public,
                PrimInteger = bobParameters.P,
                NaturalInteger = bobParameters.G,
                PrivateKey = bobKeyPair.Private
            });
        }
Ejemplo n.º 6
0
 public override void ProcessServerKeyExchange(Stream input)
 {
     this.mPskIdentityHint = TlsUtilities.ReadOpaque16(input);
     if (this.mKeyExchange == 14)
     {
         ServerDHParams serverDHParams = ServerDHParams.Parse(input);
         this.mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey(serverDHParams.PublicKey);
         this.mDHParameters     = this.mDHAgreePublicKey.Parameters;
         return;
     }
     if (this.mKeyExchange == 24)
     {
         ECDomainParameters curve_params = TlsEccUtilities.ReadECParameters(this.mNamedCurves, this.mClientECPointFormats, input);
         byte[]             encoding     = TlsUtilities.ReadOpaque8(input);
         this.mECAgreePublicKey = TlsEccUtilities.ValidateECPublicKey(TlsEccUtilities.DeserializeECPublicKey(this.mClientECPointFormats, curve_params, encoding));
     }
 }
Ejemplo n.º 7
0
        public byte[] calcAgreementDef(Byte[] pubdata)
        {
            //int hdrSize =8
            //Reading header
            int bY2Size = BitConverter.ToInt32(pubdata, 0);
            int bm2Size = BitConverter.ToInt32(pubdata, 4);
            //Reading data
            int        itr = 8;
            BigInteger Y2  = new BigInteger(pubdata, itr, bY2Size);

            itr += bY2Size;
            BigInteger            m2 = new BigInteger(pubdata, itr, bm2Size);
            DHParameters          newDHParameters = new DHParameters(this.p, this.g);
            DHPublicKeyParameters pu2             = new DHPublicKeyParameters(Y2, newDHParameters);

            return(this.e1.CalculateAgreement(pu2, m2).ToByteArray());//Variable length (not necessary bits / 8)
        }
        public override void ProcessServerKeyExchange(Stream input)
        {
            this.mPskIdentityHint = TlsUtilities.ReadOpaque16(input);

            if (this.mKeyExchange == KeyExchangeAlgorithm.DHE_PSK)
            {
                this.mDHParameters     = TlsDHUtilities.ReceiveDHParameters(mDHVerifier, input);
                this.mDHAgreePublicKey = new DHPublicKeyParameters(TlsDHUtilities.ReadDHParameter(input), mDHParameters);
            }
            else if (this.mKeyExchange == KeyExchangeAlgorithm.ECDHE_PSK)
            {
                ECDomainParameters ecParams = TlsEccUtilities.ReadECParameters(mNamedCurves, mClientECPointFormats, input);

                byte[] point = TlsUtilities.ReadOpaque8(input);

                this.mECAgreePublicKey = TlsEccUtilities.ValidateECPublicKey(TlsEccUtilities.DeserializeECPublicKey(
                                                                                 mClientECPointFormats, ecParams, point));
            }
        }
Ejemplo n.º 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));
                }
            }
        }
Ejemplo n.º 10
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            //IL_006f: Expected O, but got Unknown
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(42);
            }
            X509CertificateStructure certificateAt        = serverCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo     subjectPublicKeyInfo = certificateAt.SubjectPublicKeyInfo;

            try
            {
                mServerPublicKey = PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
            }
            catch (global::System.Exception alertCause)
            {
                throw new TlsFatalAlert(43, alertCause);
            }
            if (mTlsSigner == null)
            {
                try
                {
                    mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey((DHPublicKeyParameters)mServerPublicKey);
                    mDHParameters     = ValidateDHParameters(mDHAgreePublicKey.Parameters);
                }
                catch (InvalidCastException val)
                {
                    InvalidCastException alertCause2 = val;
                    throw new TlsFatalAlert(46, (global::System.Exception)(object) alertCause2);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 8);
            }
            else
            {
                if (!mTlsSigner.IsValidPublicKey(mServerPublicKey))
                {
                    throw new TlsFatalAlert(46);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 128);
            }
            base.ProcessServerCertificate(serverCertificate);
        }
Ejemplo n.º 11
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);
            }
        }
Ejemplo n.º 12
0
    //takes robot through all knot points over desired time
    IEnumerator RotateMe(float inTime)
    {
        DHParameters.setMoveSlider(true);
        for (int i = 0; i < knotPoints; i++)
        {
            Quaternion baseFromAngle  = BaseRotation.localRotation;
            Quaternion link1FromAngle = Link1Rotation.localRotation;
            Quaternion link2FromAngle = Link2Rotation.localRotation;

            for (float t = 0f; t < 1f; t += Time.deltaTime / inTime)
            {
                BaseRotation.localRotation  = Quaternion.Lerp(baseFromAngle, theta1Array[i], t);
                Link1Rotation.localRotation = Quaternion.Lerp(link1FromAngle, theta2Array[i], t);
                Link2Rotation.localRotation = Quaternion.Lerp(link2FromAngle, theta3Array[i], t);

                yield return(null);
            }
        }
        DHParameters.setMoveSlider(false);
    }
        public void KeyExchange()
        {
            // create a new DH instance
            DiffieHellman dh1 = new DiffieHellmanManaged();
            // export the public parameters of the first DH instance
            DHParameters dhp = dh1.ExportParameters(false);
            // create a second DH instance and initialize it with the public parameters of the first instance
            DiffieHellman dh2 = new DiffieHellmanManaged(dhp.P, dhp.G, 160);

            // generate the public key of the first DH instance
            byte[] ke1 = dh1.CreateKeyExchange();
            // generate the public key of the second DH instance
            byte[] ke2 = dh2.CreateKeyExchange();
            // let the first DH instance compute the shared secret using the second DH public key
            byte[] dh1k = dh1.DecryptKeyExchange(ke2);
            // let the second DH instance compute the shared secret using the first DH public key
            byte[] dh2k = dh2.DecryptKeyExchange(ke1);
            // both shared secrets are the same
            AssertEquals("Shared Secret", dh1k, dh2k);
        }
Ejemplo n.º 14
0
        public static DHPublicKeyParameters ValidateDHPublicKey(DHPublicKeyParameters key)
        {
            BigInteger   y          = key.Y;
            DHParameters parameters = key.Parameters;
            BigInteger   p          = parameters.P;
            BigInteger   g          = parameters.G;

            if (!p.IsProbablePrime(2))
            {
                throw new TlsFatalAlert(47);
            }
            if (g.CompareTo(Two) < 0 || g.CompareTo(p.Subtract(Two)) > 0)
            {
                throw new TlsFatalAlert(47);
            }
            if (y.CompareTo(Two) < 0 || y.CompareTo(p.Subtract(Two)) > 0)
            {
                throw new TlsFatalAlert(47);
            }
            return(key);
        }
    //Show each motors angle

    //sets and displays theta1 each frame
    void Update()
    {
        angle0Text.text = sliderTheta0.value.ToString("0.#");
        angle1Text.text = sliderTheta1.value.ToString("0.#");
        angle2Text.text = sliderTheta2.value.ToString("0.#");

        theta = RobotBase.eulerAngles.y;

        //sets and displays theta
        if (theta == 0f)
        {
            x = 0f;
        }
        else
        {
            x = 360f;
        }

        DHParameters.setTheta1(x - theta);
        //theta1Text.text = ""+(x-theta);
    }
    public TlsPskKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, TlsPskIdentity pskIdentity, TlsPskIdentityManager pskIdentityManager, DHParameters dhParameters, int[] namedCurves, byte[] clientECPointFormats, byte[] serverECPointFormats)
        : base(keyExchange, supportedSignatureAlgorithms)
    {
        switch (keyExchange)
        {
        default:
            throw new InvalidOperationException("unsupported key exchange algorithm");

        case 13:
        case 14:
        case 15:
        case 24:
            mPskIdentity          = pskIdentity;
            mPskIdentityManager   = pskIdentityManager;
            mDHParameters         = dhParameters;
            mNamedCurves          = namedCurves;
            mClientECPointFormats = clientECPointFormats;
            mServerECPointFormats = serverECPointFormats;
            break;
        }
    }
Ejemplo n.º 17
0
        public TlsDHKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, DHParameters dhParameters) : base(keyExchange, supportedSignatureAlgorithms)
        {
            switch (keyExchange)
            {
            case 3:
                this.mTlsSigner = new TlsDssSigner();
                goto IL_5E;

            case 5:
                this.mTlsSigner = new TlsRsaSigner();
                goto IL_5E;

            case 7:
            case 9:
                this.mTlsSigner = null;
                goto IL_5E;
            }
            throw new InvalidOperationException("unsupported key exchange algorithm");
IL_5E:
            this.mDHParameters = dhParameters;
        }
Ejemplo n.º 18
0
    // Update is called once per frame
    void Update()
    {
        //get vector from joint 0 to 1
        link1 = joint1.position - joint0.position;

        //get vector from joint 1 to 2
        link2 = joint2.position - joint1.position;

        //get the angle (in degrees) between the vectors along the links
        theta = Vector3.Angle(link1, link2);

        //give angle correct sign
        if ((AngleDir(link1, link2, Quaternion.Euler(0, -90, 0) * link1) < 0f) || DHParameters.getTheta2() >= 90f)      //&& (baseRotation.rotation.eulerAngles.y > 180))
        {
            theta *= -1;
        }

        //sets and displays theta
        DHParameters.setTheta3(theta);
        theta3Text.text = "" + theta;
    }
Ejemplo n.º 19
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(0x2a);
            }
            X509CertificateStructure certificateAt        = serverCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo     subjectPublicKeyInfo = certificateAt.SubjectPublicKeyInfo;

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
            }
            catch (Exception exception)
            {
                throw new TlsFatalAlert(0x2b, exception);
            }
            if (this.mTlsSigner == null)
            {
                try
                {
                    this.mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey((DHPublicKeyParameters)this.mServerPublicKey);
                    this.mDHParameters     = this.ValidateDHParameters(this.mDHAgreePublicKey.Parameters);
                }
                catch (InvalidCastException exception2)
                {
                    throw new TlsFatalAlert(0x2e, exception2);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 8);
            }
            else
            {
                if (!this.mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                {
                    throw new TlsFatalAlert(0x2e);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 0x80);
            }
            base.ProcessServerCertificate(serverCertificate);
        }
Ejemplo n.º 20
0
        public static RequestSetClientDHParams GetRequest(TServerDHParamsOk serverDhParams, byte[] newNonce, out byte[] clientAgree, out int serverTime)
        {
            AesHelper.ComputeAesParameters(newNonce, serverDhParams.ServerNonce, out var aesKeyData);

            var dhInnerData = DeserializeResponse(serverDhParams, aesKeyData);

            serverTime = dhInnerData.ServerTime;

            var p = new BigInteger(1, dhInnerData.DhPrimeAsBinary);
            var g = BigInteger.ValueOf(dhInnerData.G);

            var dhParameters            = new DHParameters(p, g);
            KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParameters);
            var keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(kgp);

            var clientKeyPair = keyGen.GenerateKeyPair();
            var publicKey     = ((DHPublicKeyParameters)clientKeyPair.Public);

            var y = new BigInteger(1, dhInnerData.GAAsBinary);

            Guard.That(y).IsValidDhPublicKey(dhParameters.P);

            var serverPublicKey = new DHPublicKeyParameters(y, dhParameters);
            var clientKeyAgree  = AgreementUtilities.GetBasicAgreement("DH");

            clientKeyAgree.Init(clientKeyPair.Private);
            clientAgree = clientKeyAgree.CalculateAgreement(serverPublicKey).ToByteArrayUnsigned();

            var clientDhInnerData = new TClientDHInnerData
            {
                RetryId     = 0,
                Nonce       = serverDhParams.Nonce,
                ServerNonce = serverDhParams.ServerNonce,
                GBAsBinary  = publicKey.Y.ToByteArray()
            };

            return(SerializeRequest(clientDhInnerData, aesKeyData));
        }
Ejemplo n.º 21
0
        public TlsPskKeyExchange(int keyExchange, global::System.Collections.IList supportedSignatureAlgorithms, TlsPskIdentity pskIdentity, TlsPskIdentityManager pskIdentityManager, DHParameters dhParameters, int[] namedCurves, byte[] clientECPointFormats, byte[] serverECPointFormats)
            : base(keyExchange, supportedSignatureAlgorithms)
        {
            //IL_0068: Unknown result type (might be due to invalid IL or missing references)
            switch (keyExchange)
            {
            default:
                throw new InvalidOperationException("unsupported key exchange algorithm");

            case 13:
            case 14:
            case 15:
            case 24:
                mPskIdentity          = pskIdentity;
                mPskIdentityManager   = pskIdentityManager;
                mDHParameters         = dhParameters;
                mNamedCurves          = namedCurves;
                mClientECPointFormats = clientECPointFormats;
                mServerECPointFormats = serverECPointFormats;
                break;
            }
        }
Ejemplo n.º 22
0
        public TlsPskKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, TlsPskIdentity pskIdentity,
                                 DHParameters dhParameters, int[] namedCurves, byte[] clientECPointFormats, byte[] serverECPointFormats)
            :   base(keyExchange, supportedSignatureAlgorithms)
        {
            switch (keyExchange)
            {
            case KeyExchangeAlgorithm.DHE_PSK:
            case KeyExchangeAlgorithm.ECDHE_PSK:
            case KeyExchangeAlgorithm.PSK:
            case KeyExchangeAlgorithm.RSA_PSK:
                break;

            default:
                throw new InvalidOperationException("unsupported key exchange algorithm");
            }

            this.mPskIdentity          = pskIdentity;
            this.mDHParameters         = dhParameters;
            this.mNamedCurves          = namedCurves;
            this.mClientECPointFormats = clientECPointFormats;
            this.mServerECPointFormats = serverECPointFormats;
        }
Ejemplo n.º 23
0
    //rotates robot base to face desired point 将机器人基座旋转到所需要的点
    IEnumerator RotateBaseToTarget(float inTime)
    {
        //values for internal use 内部使用的值
        Quaternion _lookRotation;
        Vector3    _direction;

        //find the vector pointing from our position to the target 求出指向目标的向量
        _direction = (target - baseFrame.position);

        //create the rotation we need to be in to look at the target 创建我们需要的旋转来观察目标
        _lookRotation = Quaternion.LookRotation(_direction);
        Quaternion start = baseFrame.rotation;

        DHParameters.setMoveSlider(true);
        for (float t = 0f; t < 1f; t += Time.deltaTime / inTime)
        {
            //rotate us over time according to speed until we are in the required rotation
            baseFrame.localRotation = Quaternion.Euler(0f, (Quaternion.Lerp(start, _lookRotation, t)).eulerAngles.y, 0f);
            yield return(null);
        }
        DHParameters.setMoveSlider(false);
    }
Ejemplo n.º 24
0
        public void Init(ICipherParameters parameters)
        {
            AsymmetricKeyParameter asymmetricKeyParameter;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom parametersWithRandom = (ParametersWithRandom)parameters;
                this.random            = parametersWithRandom.Random;
                asymmetricKeyParameter = (AsymmetricKeyParameter)parametersWithRandom.Parameters;
            }
            else
            {
                this.random            = new SecureRandom();
                asymmetricKeyParameter = (AsymmetricKeyParameter)parameters;
            }
            if (!(asymmetricKeyParameter is DHPrivateKeyParameters))
            {
                throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
            }
            this.key      = (DHPrivateKeyParameters)asymmetricKeyParameter;
            this.dhParams = this.key.Parameters;
        }
Ejemplo n.º 25
0
        /**
         * Return the value for a specific size for a sized property such as DH_DEFAULT_PARAMS or
         * DSA_DEFAULT_PARAMS.
         *
         * @param property the name of the property to look up.
         * @param size the size (in bits) of the defining value in the property type.
         * @param <T> the type of the value to be returned.
         * @return the current value for the size, null if there is no value set,
         */
        public static T GetSizedProperty <T>(Property property, int size) where T : class
        {
            T[] values = lookupProperty <T>(property);

            if (values == null)
            {
                return(null);
            }

            if (property.Type.IsAssignableFrom(typeof(DHParameters)))

            {
                for (int i = 0; i != values.Length; i++)
                {
                    DHParameters dHParameters = values[i] as DHParameters;

                    if (dHParameters.P.BitLength == size)
                    {
                        return(dHParameters as T);
                    }
                }
            }

            else if (property.Type.IsAssignableFrom(typeof(DSAParameters)))
            {
                for (int i = 0; i != values.Length; i++)
                {
                    List <DSAParameters> dSAParameters = values[i] as List <DSAParameters>;

                    if (dSAParameters.Count() == size)
                    {
                        return(dSAParameters as T);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 26
0
        public static byte[] ComputeSharedSecret(string A, string BPrivateKey, string p, string g)
        {
            DHParameters           internalParameters = new DHParameters(new Org.BouncyCastle.Math.BigInteger(p, 16), new Org.BouncyCastle.Math.BigInteger(g, 16));
            AsymmetricKeyParameter bPrivateKey        = new DHPrivateKeyParameters(new Org.BouncyCastle.Math.BigInteger(BPrivateKey, 16), internalParameters);
            var importedKey      = new DHPublicKeyParameters(new Org.BouncyCastle.Math.BigInteger(A, 16), internalParameters);
            var internalKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            internalKeyAgree.Init(bPrivateKey);
            byte[] sharedSecret          = internalKeyAgree.CalculateAgreement(importedKey).ToByteArray();
            byte[] fixedSizeSharedSecret = new byte[32];
            for (int i = 0; i < 32; i++)
            {
                if (i >= sharedSecret.Length)
                {
                    fixedSizeSharedSecret[i] = 0xFF;
                }
                else
                {
                    fixedSizeSharedSecret[i] = sharedSecret[i];
                }
            }
            return(fixedSizeSharedSecret);
        }
Ejemplo n.º 27
0
        public virtual AsymmetricCipherKeyPair generateKeyPair()
        {
            BigInteger   p, g, x, y;
            int          qLength  = param.getStrength() - 1;
            DHParameters dhParams = param.getParameters();

            p = dhParams.getP();
            g = dhParams.getG();

            //
            // calculate the private key
            //
            x = new BigInteger(qLength, param.getRandom());

            //
            // calculate the public key.
            //
            y = g.modPow(x, p);

            return(new AsymmetricCipherKeyPair(
                       new DHPublicKeyParameters(y, dhParams),
                       new DHPrivateKeyParameters(x, dhParams)));
        }
Ejemplo n.º 28
0
    public TlsDHKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, DHParameters dhParameters)
        : base(keyExchange, supportedSignatureAlgorithms)
    {
        switch (keyExchange)
        {
        case 7:
        case 9:
            mTlsSigner = null;
            break;

        case 5:
            mTlsSigner = new TlsRsaSigner();
            break;

        case 3:
            mTlsSigner = new TlsDssSigner();
            break;

        default:
            throw new InvalidOperationException("unsupported key exchange algorithm");
        }
        mDHParameters = dhParameters;
    }
Ejemplo n.º 29
0
        public void TestDH()
        {
            BigInteger DHParraP = new BigInteger(Base64.Decode("ALJCm1CUL6mOnyVqWTSV6Z2+DVSGOvgboOhmbyyxCrym59uVnXMmPjIgQTrmniFg7PvdcN7NNFwFmcZleULso1s="));
            BigInteger DHParraQ = new BigInteger(Base64.Decode("WSFNqEoX1MdPkrUsmkr0zt8GqkMdfA3QdDM3lliFXlNz7crOuZMfGRAgnXNPELB2fe64b2aaLgLM4zK8oXZRrQ=="));
            BigInteger DHPubY   = new BigInteger(Base64.Decode("AIki+8/zggCS2e488AsTNULI4LujdUeQQsZI949Dc9lKXZRmrPIC1h8NRoneHQEhpAe4Rhe0nhUOGZJekT5++SA="));
            BigInteger DHPrivX  = new BigInteger(Base64.Decode("Apo67noMRO5eDWo/TtpRiBmKGw7ywh25shIu0Rs03krQmWKRbDPvdygWdJ5IpW6ZbKlCTAMhSxpz03YSeSEDmw=="));


            DHParameters           dhPara    = new DHParameters(DHParraP, DHParraQ);
            DHPublicKeyParameters  dhPublic  = new DHPublicKeyParameters(DHPubY, dhPara);
            DHPrivateKeyParameters dhPrivate = new DHPrivateKeyParameters(DHPrivX, dhPara);

            SubjectPublicKeyInfo pubInfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(dhPublic);
            PrivateKeyInfo       privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dhPrivate);

            DHPublicKeyParameters  testPubKey  = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            DHPrivateKeyParameters testPrivKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsFalse(!testPrivKey.Equals(dhPrivate), "DH: Private key to info back to key");
            Assert.IsFalse(!testPubKey.Equals(dhPublic), "DH: Public key to info back to key");

            Assert.IsTrue(true, "Diffe Helman Test worked.");
        }
Ejemplo n.º 30
0
        public void Init(ICipherParameters parameters)
        {
            //IL_0048: Unknown result type (might be due to invalid IL or missing references)
            AsymmetricKeyParameter asymmetricKeyParameter;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom parametersWithRandom = (ParametersWithRandom)parameters;
                random = parametersWithRandom.Random;
                asymmetricKeyParameter = (AsymmetricKeyParameter)parametersWithRandom.Parameters;
            }
            else
            {
                random = new SecureRandom();
                asymmetricKeyParameter = (AsymmetricKeyParameter)parameters;
            }
            if (!(asymmetricKeyParameter is DHPrivateKeyParameters))
            {
                throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
            }
            key      = (DHPrivateKeyParameters)asymmetricKeyParameter;
            dhParams = key.Parameters;
        }