public ECPrivateKeyStructure(int orderBitLength, BigInteger key)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (orderBitLength < key.BitLength)
     {
         throw new ArgumentException("must be >= key bitlength", "orderBitLength");
     }
     byte[] str = BigIntegers.AsUnsignedByteArray((orderBitLength + 7) / 8, key);
     seq = new DerSequence(new DerInteger(1), new DerOctetString(str));
 }
        public byte[] Old()
        {
            ECPrivateKeyParameters privateKeyParameters = BouncyCrypto.WrapPrivateKey(privateKey);
            ECPublicKeyParameters  publicKeyParameters  = BouncyCrypto.WrapPublicKey(ephemeral);
            IBasicAgreement        agreement            = new ECDHBasicAgreement();

            agreement.Init(privateKeyParameters);

            BigInteger zAsInteger = agreement.CalculateAgreement(publicKeyParameters);

            byte[] bytes = BigIntegers.AsUnsignedByteArray(32, zAsInteger);
            return(bytes);
        }
예제 #3
0
 public byte[] GeneratePremasterSecret()
 {
     try
     {
         // TODO Check if this needs to be a fixed size
         return(BigIntegers.AsUnsignedByteArray(srpClient.CalculateSecret(B)));
     }
     catch (CryptoException)
     {
         handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_illegal_parameter);
         return(null);                // Unreachable!
     }
 }
예제 #4
0
        public void TestECDsaP256Sha256()
        {
            X9ECParameters p          = NistNamedCurves.GetByName("P-256");
            var            parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var            priKey     = new ECPrivateKeyParameters(
                new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d
                parameters);
            SecureRandom k =
                FixedSecureRandom.From(
                    BigIntegers.AsUnsignedByteArray(
                        new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335")));

            byte[] m = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");

            var dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            IBigInteger[] sig = dsa.GenerateSignature(m);

            IBigInteger r =
                new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384");
            IBigInteger s =
                new BigInteger("98506158880355671805367324764306888225238061309262649376965428126566081727535");

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + NewLine
                     + " expecting: " + r + NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + NewLine
                     + " expecting: " + s + NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            var pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(
                    Hex.Decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(m, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
예제 #5
0
        public KeyStore <T> EncryptAndGenerateKeyStore(string password, byte[] privateKey, string address, T kdfParams)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }
            if (kdfParams == null)
            {
                throw new ArgumentNullException(nameof(kdfParams));
            }

            //Validate length unsigned but store the parameter
            var keyValidation = BigIntegers.AsUnsignedByteArray(new Org.BouncyCastle.Math.BigInteger(privateKey));

            if (keyValidation.Length != 32)
            {
                throw new ArgumentException("Private key should be 32 bytes", nameof(privateKey));
            }

            var salt = RandomBytesGenerator.GenerateRandomSalt();

            var derivedKey = GenerateDerivedKey(password, salt, kdfParams);

            var cipherKey = KeyStoreCrypto.GenerateCipherKey(derivedKey);

            var iv = RandomBytesGenerator.GenerateRandomInitialisationVector();

            var cipherText = GenerateCipher(privateKey, iv, cipherKey);

            var mac = KeyStoreCrypto.GenerateMac(derivedKey, cipherText);

            var cryptoInfo = new CryptoInfo <T>(GetCipherType(), cipherText, iv, mac, salt, kdfParams, GetKdfType());

            var keyStore = new KeyStore <T>
            {
                Version = CurrentVersion,
                Address = address,
                Id      = Guid.NewGuid().ToString(),
                Crypto  = cryptoInfo
            };

            return(keyStore);
        }
예제 #6
0
        /**
         * generate a signature for the loaded message using the key we were
         * initialised with.
         */
        public virtual byte[] GenerateSignature()
        {
            CreateSignatureBlock();

            BigInteger t = new BigInteger(1, cipher.ProcessBlock(block, 0, block.Length));

            ClearBlock(block);

            t = t.Min(kParam.Modulus.Subtract(t));

            int size = BigIntegers.GetUnsignedByteLength(kParam.Modulus);

            return(BigIntegers.AsUnsignedByteArray(size, t));
        }
예제 #7
0
        public static byte[] CalculateDHBasicAgreement(DHPublicKeyParameters publicKey,
                                                       DHPrivateKeyParameters privateKey)
        {
            DHBasicAgreement basicAgreement = new DHBasicAgreement();

            basicAgreement.Init(privateKey);
            BigInteger agreementValue = basicAgreement.CalculateAgreement(publicKey);

            /*
             * RFC 5246 8.1.2. Leading bytes of Z that contain all zero bits are stripped before it is
             * used as the pre_master_secret.
             */
            return(BigIntegers.AsUnsignedByteArray(agreementValue));
        }
예제 #8
0
        public static byte[] CalculateECDHBasicAgreement(ECPublicKeyParameters publicKey, ECPrivateKeyParameters privateKey)
        {
            ECDHBasicAgreement basicAgreement = new ECDHBasicAgreement();

            basicAgreement.Init(privateKey);
            BigInteger agreementValue = basicAgreement.CalculateAgreement(publicKey);

            /*
             * RFC 4492 5.10. Note that this octet string (Z in IEEE 1363 terminology) as output by
             * FE2OSP, the Field Element to Octet String Conversion Primitive, has constant length for
             * any given field; leading zeros found in this octet string MUST NOT be truncated.
             */
            return(BigIntegers.AsUnsignedByteArray(basicAgreement.GetFieldSize(), agreementValue));
        }
예제 #9
0
 public override byte[] GeneratePremasterSecret()
 {
     byte[] result;
     try
     {
         BigInteger n = (this.mSrpServer != null) ? this.mSrpServer.CalculateSecret(this.mSrpPeerCredentials) : this.mSrpClient.CalculateSecret(this.mSrpPeerCredentials);
         result = BigIntegers.AsUnsignedByteArray(n);
     }
     catch (CryptoException alertCause)
     {
         throw new TlsFatalAlert(47, alertCause);
     }
     return(result);
 }
예제 #10
0
        public static DHPrivateKeyParameters GenerateEphemeralClientKeyExchange(SecureRandom random,
                                                                                DHParameters dhParams, Stream output)
        {
            AsymmetricCipherKeyPair dhAgreeClientKeyPair    = GenerateDHKeyPair(random, dhParams);
            DHPrivateKeyParameters  dhAgreeClientPrivateKey =
                (DHPrivateKeyParameters)dhAgreeClientKeyPair.Private;

            BigInteger Yc = ((DHPublicKeyParameters)dhAgreeClientKeyPair.Public).Y;

            byte[] keData = BigIntegers.AsUnsignedByteArray(Yc);
            TlsUtilities.WriteOpaque16(keData, output);

            return(dhAgreeClientPrivateKey);
        }
예제 #11
0
            public byte[] Calculate(IAsymmetricPublicKey publicKey)
            {
                ECDomainParameters domainParams = ((AsymmetricECPublicKey)publicKey).DomainParameters;

                byte[] zBytes = BigIntegers.AsUnsignedByteArray((domainParams.Curve.FieldSize + 7) / 8,
                                                                agreement.CalculateAgreement(GetPublicKeyParameters((AsymmetricECPublicKey)publicKey)));

                byte[] keyMaterial = parameters.KeyMaterialGenerator.Generate(zBytes);

                // ZEROIZE
                Arrays.Fill(zBytes, (byte)0);

                return(keyMaterial);
            }
예제 #12
0
        public void TestECDsaP224Sha224()
        {
            X9ECParameters p          = NistNamedCurves.GetByName("P-224");
            var            parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var            priKey     = new ECPrivateKeyParameters(
                new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d
                parameters);
            SecureRandom k =
                FixedSecureRandom.From(
                    BigIntegers.AsUnsignedByteArray(
                        new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601")));

            byte[] m = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79");

            var dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            IBigInteger[] sig = dsa.GenerateSignature(m);

            IBigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742");
            IBigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978");

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + NewLine
                     + " expecting: " + r + NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + NewLine
                     + " expecting: " + s + NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            var pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")),
                // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(m, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
예제 #13
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 ? EncryptBlock(input, inOff, inLen, array) : DecryptBlock(input, inOff, inLen, array));
        }
        finally
        {
            Array.Clear(array, 0, array.Length);
        }
    }
예제 #14
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));
        }
 public ECPrivateKeyStructure(int orderBitLength, BigInteger key)
 {
     //IL_000e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0027: Unknown result type (might be due to invalid IL or missing references)
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (orderBitLength < key.BitLength)
     {
         throw new ArgumentException("must be >= key bitlength", "orderBitLength");
     }
     byte[] str = BigIntegers.AsUnsignedByteArray((orderBitLength + 7) / 8, key);
     seq = new DerSequence(new DerInteger(1), new DerOctetString(str));
 }
예제 #16
0
        public override byte[] GeneratePremasterSecret()
        {
            try
            {
                BigInteger S = mSrpServer != null
                    ?   mSrpServer.CalculateSecret(mSrpPeerCredentials)
                    :   mSrpClient.CalculateSecret(mSrpPeerCredentials);

                // TODO Check if this needs to be a fixed size
                return(BigIntegers.AsUnsignedByteArray(S));
            }
            catch (CryptoException e)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
            }
        }
예제 #17
0
        public virtual byte[] ProcessBlock(byte[] input, int inOff, int inLen)
        {
            this.agree.Init(this.privParam);
            BigInteger n = this.agree.CalculateAgreement(this.pubParam);

            byte[] array = BigIntegers.AsUnsignedByteArray(this.agree.GetFieldSize(), n);
            byte[] result;
            try
            {
                result = (this.forEncryption ? this.EncryptBlock(input, inOff, inLen, array) : this.DecryptBlock(input, inOff, inLen, array));
            }
            finally
            {
                Array.Clear(array, 0, array.Length);
            }
            return(result);
        }
예제 #18
0
        public virtual byte[] ProcessBlock(byte[] input, int inOff, int inLen)
        {
            byte[] buffer2;
            this.agree.Init(this.privParam);
            BigInteger n = this.agree.CalculateAgreement(this.pubParam);

            byte[] z = BigIntegers.AsUnsignedByteArray(this.agree.GetFieldSize(), n);
            try
            {
                buffer2 = !this.forEncryption ? this.DecryptBlock(input, inOff, inLen, z) : this.EncryptBlock(input, inOff, inLen, z);
            }
            finally
            {
                Array.Clear(z, 0, z.Length);
            }
            return(buffer2);
        }
        public string GenerateSharedSecretHex(string pubKeyHex)
        {
            var encoded = pubKeyHex.HexToByteArray();

            if (encoded.Length == 64)
            {
                var numArray = new byte[encoded.Length + 1];
                numArray[0] = (byte)4;
                Array.Copy((Array)encoded, 0, (Array)numArray, 1, encoded.Length);
                encoded = numArray;
            }
            var publicKeyParameters = new ECPublicKeyParameters("ECDH", ECDH_Key._curve.Curve.DecodePoint(encoded), ECDH_Key._domain);
            var ecdhBasicAgreement  = new ECDHBasicAgreement();

            ecdhBasicAgreement.Init(_key.Private);
            return(BigIntegers.AsUnsignedByteArray(ecdhBasicAgreement.GetFieldSize(), ecdhBasicAgreement.CalculateAgreement((ICipherParameters)publicKeyParameters)).ToHex(true));
        }
예제 #20
0
        public void TestECDsaP521Sha512()
        {
            X9ECParameters         p          = NistNamedCurves.GetByName("P-521");
            ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey     = new ECPrivateKeyParameters(
                new BigInteger("617573726813476282316253885608633222275541026607493641741273231656161177732180358888434629562647985511298272498852936680947729040673640492310550142822667389"), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("6806532878215503520845109818432174847616958675335397773700324097584974639728725689481598054743894544060040710846048585856076812050552869216017728862957612913")));

            byte[] M = Hex.Decode("6893B64BD3A9615C39C3E62DDD269C2BAAF1D85915526083183CE14C2E883B48B193607C1ED871852C9DF9C3147B574DC1526C55DE1FE263A676346A20028A66");

            ECDsaSigner dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            BigInteger[] sig = dsa.GenerateSignature(M);

            BigInteger r = new BigInteger("1368926195812127407956140744722257403535864168182534321188553460365652865686040549247096155740756318290773648848859639978618869784291633651685766829574104630");
            BigInteger s = new BigInteger("1624754720348883715608122151214003032398685415003935734485445999065609979304811509538477657407457976246218976767156629169821116579317401249024208611945405790");

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(Hex.Decode("020145E221AB9F71C5FE740D8D2B94939A09E2816E2167A7D058125A06A80C014F553E8D6764B048FB6F2B687CEC72F39738F223D4CE6AFCBFF2E34774AA5D3C342CB3")), // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(M, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
예제 #21
0
        private void DoTestECDsa239BitBinary(
            string algorithm,
            DerObjectIdentifier oid)
        {
            BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
            BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");

            byte[] kData = BigIntegers.AsUnsignedByteArray(
                new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));

            SecureRandom k = FixedSecureRandom.From(kData);

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

            ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
                new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
                parameters);

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
                parameters);

            ISigner sgr = SignerUtilities.GetSigner(algorithm);

            byte[] message = Encoding.ASCII.GetBytes("abc");

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr = SignerUtilities.GetSigner(oid.Id);

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC RIPEMD160 verification failed");
            }
        }
예제 #22
0
        internal static byte[] ComputeSharedSecret(ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey)
        {
            if (!KeyParser.ValidateCurve(privateKey))
            {
                throw new ArgumentException("Private key not on NIST P-256 curve", "privateKey");
            }
            if (!KeyParser.ValidateCurve(publicKey))
            {
                throw new ArgumentException("Public key not on NIST P-256 curve", "publicKey");
            }

            var ecdhAgreement = new ECDHBasicAgreement();

            ecdhAgreement.Init(privateKey);
            BigInteger secret = ecdhAgreement.CalculateAgreement(publicKey);

            return(BigIntegers.AsUnsignedByteArray(SharedSecretSize, secret));
        }
예제 #23
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));
        }
예제 #24
0
        /**
         * return true if the signature represents a ISO9796-2 signature
         * for the passed in message.
         */
        public virtual bool VerifySignature(byte[] signature)
        {
            try
            {
                block = cipher.ProcessBlock(signature, 0, signature.Length);
            }
            catch (Exception)
            {
                return(false);
            }

            BigInteger t = new BigInteger(block);
            BigInteger f;

            if ((t.IntValue & 15) == 12)
            {
                f = t;
            }
            else
            {
                t = kParam.Modulus.Subtract(t);
                if ((t.IntValue & 15) == 12)
                {
                    f = t;
                }
                else
                {
                    return(false);
                }
            }

            CreateSignatureBlock();

            byte[] fBlock = BigIntegers.AsUnsignedByteArray(block.Length, f);

            bool rv = Arrays.ConstantTimeAreEqual(block, fBlock);

            ClearBlock(block);
            ClearBlock(fBlock);

            return(rv);
        }
예제 #25
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));
        }
예제 #26
0
        protected static BigInteger calculateY_FF1(IBlockCipher cipher, BigInteger bigRadix, byte[] T, int b, int d, int round, byte[] P, ushort[] AB)
        {
            int t = T.Length;

            // i.
            BigInteger numAB = num(bigRadix, AB);

            byte[] bytesAB = BigIntegers.AsUnsignedByteArray(numAB);

            int zeroes = -(t + b + 1) & 15;

            byte[] Q = new byte[t + zeroes + 1 + b];
            Array.Copy(T, 0, Q, 0, t);
            Q[t + zeroes] = (byte)round;
            Array.Copy(bytesAB, 0, Q, Q.Length - bytesAB.Length, bytesAB.Length);

            // ii.
            byte[] R = prf(cipher, Arrays.Concatenate(P, Q));

            // iii.
            byte[] sBlocks = R;
            if (d > BLOCK_SIZE)
            {
                int sBlocksLen = (d + BLOCK_SIZE - 1) / BLOCK_SIZE;
                sBlocks = new byte[sBlocksLen * BLOCK_SIZE];
                Array.Copy(R, 0, sBlocks, 0, BLOCK_SIZE);

                byte[] uint32 = new byte[4];
                for (uint j = 1; j < sBlocksLen; ++j)
                {
                    int sOff = (int)(j * BLOCK_SIZE);
                    Array.Copy(R, 0, sBlocks, sOff, BLOCK_SIZE);
                    Pack.UInt32_To_BE(j, uint32, 0);
                    xor(uint32, 0, sBlocks, sOff + BLOCK_SIZE - 4, 4);
                    cipher.ProcessBlock(sBlocks, sOff, sBlocks, sOff);
                }
            }

            // iv.
            return(num(sBlocks, 0, d));
        }
예제 #27
0
        public virtual bool VerifySignature(byte[] signature)
        {
            BigInteger integer2;

            try
            {
                this.block = this.cipher.ProcessBlock(signature, 0, signature.Length);
            }
            catch (Exception)
            {
                return(false);
            }
            BigInteger n = new BigInteger(1, this.block);

            if ((n.IntValue & 15) == 12)
            {
                integer2 = n;
            }
            else
            {
                n = this.kParam.Modulus.Subtract(n);
                if ((n.IntValue & 15) == 12)
                {
                    integer2 = n;
                }
                else
                {
                    return(false);
                }
            }
            this.CreateSignatureBlock();
            byte[] b     = BigIntegers.AsUnsignedByteArray(this.block.Length, integer2);
            bool   flag2 = Arrays.ConstantTimeAreEqual(this.block, b);

            this.ClearBlock(this.block);
            this.ClearBlock(b);
            return(flag2);
        }
    public ECPrivateKeyStructure(int orderBitLength, BigInteger key, DerBitString publicKey, Asn1Encodable parameters)
    {
        if (key == null)
        {
            throw new ArgumentNullException("key");
        }
        if (orderBitLength < key.BitLength)
        {
            throw new ArgumentException("must be >= key bitlength", "orderBitLength");
        }
        byte[] str = BigIntegers.AsUnsignedByteArray((orderBitLength + 7) / 8, key);
        Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new DerInteger(1), new DerOctetString(str));

        if (parameters != null)
        {
            asn1EncodableVector.Add(new DerTaggedObject(explicitly: true, 0, parameters));
        }
        if (publicKey != null)
        {
            asn1EncodableVector.Add(new DerTaggedObject(explicitly: true, 1, publicKey));
        }
        seq = new DerSequence(asn1EncodableVector);
    }
예제 #29
0
        public byte[] GenerateClientKeyExchange()
        {
            // TODO RFC 2246 7.4.72

            /*
             * If the client certificate already contains a suitable Diffie-Hellman key, then
             * Yc is implicit and does not need to be sent again. In this case, the Client Key
             * Exchange message will be sent, but will be empty.
             */
            //return new byte[0];

            /*
             * Generate a keypair (using parameters from server key) and send the public value
             * to the server.
             */
            DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator();

            dhGen.Init(new DHKeyGenerationParameters(handler.Random, dhAgreeServerPublicKey.Parameters));
            this.dhAgreeClientKeyPair = dhGen.GenerateKeyPair();
            BigInteger Yc = ((DHPublicKeyParameters)dhAgreeClientKeyPair.Public).Y;

            return(BigIntegers.AsUnsignedByteArray(Yc));
        }
예제 #30
0
        public byte[] Encode()
        {
            BigInteger amount   = BigInteger.ValueOf(long.Parse(Amount));
            BigInteger gasPrice = BigInteger.ValueOf(long.Parse(GasPrice));

            ProtoTransactionInfo info = new ProtoTransactionInfo();

            info.Version      = (uint)Version;
            info.Nonce        = (ulong)Nonce;
            info.Toaddr       = ByteString.CopyFrom(ByteUtil.HexStringToByteArray(ToAddr.ToLower()));
            info.Senderpubkey = new ByteArray()
            {
                Data = ByteString.CopyFrom(ByteUtil.HexStringToByteArray(PubKey))
            };
            info.Amount = new ByteArray()
            {
                Data = ByteString.CopyFrom(BigIntegers.AsUnsignedByteArray(16, amount))
            };
            info.Gasprice = new ByteArray()
            {
                Data = ByteString.CopyFrom(BigIntegers.AsUnsignedByteArray(16, gasPrice))
            };
            info.Gaslimit = ulong.Parse(GasLimit);
            if (!string.IsNullOrEmpty(Code))
            {
                info.Code = ByteString.CopyFrom(System.Text.Encoding.Default.GetBytes(Code));
            }

            if (!string.IsNullOrEmpty(Data))
            {
                info.Data = ByteString.CopyFrom(System.Text.Encoding.Default.GetBytes(Data));
            }


            return(info.ToByteArray());
        }