Exemple #1
0
        public void TestECNR239bitPrime()
        {
            BigInteger r = new BigInteger("308636143175167811492623515537541734843573549327605293463169625072911693");
            BigInteger s = new BigInteger("852401710738814635664888632022555967400445256405412579597015412971797143");

            byte[] kData = new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655").ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

            X9ECParameters p = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v1);
            ECDomainParameters spec = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECCurve curve = spec.Curve;

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("SHA1withECNR");
            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            checkSignature(239, priKey, pubKey, sgr, k, message, r, s);
        }
        // The ECMQV Primitive as described in SEC-1, 3.4
        private static ECPoint CalculateMqvAgreement(
			ECDomainParameters		parameters,
			ECPrivateKeyParameters	d1U,
			ECPrivateKeyParameters	d2U,
			ECPublicKeyParameters	q2U,
			ECPublicKeyParameters	q1V,
			ECPublicKeyParameters	q2V)
        {
            var n = parameters.N;
            var e = (n.BitLength + 1) / 2;
            var powE = BigInteger.One.ShiftLeft(e);

            // The Q2U public key is optional
            var q = q2U == null ? parameters.G.Multiply(d2U.D) : q2U.Q;

            var x = q.X.ToBigInteger();
            var xBar = x.Mod(powE);
            var q2UBar = xBar.SetBit(e);
            var s = d1U.D.Multiply(q2UBar).Mod(n).Add(d2U.D).Mod(n);

            var xPrime = q2V.Q.X.ToBigInteger();
            var xPrimeBar = xPrime.Mod(powE);
            var q2VBar = xPrimeBar.SetBit(e);

            var hs = parameters.H.Multiply(s).Mod(n);

            //ECPoint p = Q1V.Q.Multiply(Q2VBar).Add(Q2V.Q).Multiply(hs);
            var p = ECAlgorithms.SumOfTwoMultiplies(
                q1V.Q, q2VBar.Multiply(hs).Mod(n), q2V.Q, hs);

            if (p.IsInfinity)
                throw new InvalidOperationException("Infinity is not a valid agreement value for MQV");

            return p;
        }
		public byte[] Sign(byte[] signedData, ECPrivateKeyParameters privateKey)
		{
		    if (signedData == null)
		    {
		        throw new ArgumentNullException(nameof(signedData));
		    }
		    if (privateKey == null)
		    {
		        throw new ArgumentNullException(nameof(privateKey));
		    }

		    try
			{
			    var signature = SignerUtilities.GetSigner("SHA-256withECDSA");
				signature.Init(true, privateKey);
				signature.BlockUpdate(signedData, 0, signedData.Length);
                
                return signature.GenerateSignature();
			}
			catch (SecurityUtilityException e)
			{
				throw new U2FException("Error when signing", e);
			}
			catch (CryptoException e)
			{
				throw new U2FException("Error when signing", e);
			}
		}
Exemple #4
0
		public void TestECNR239bitPrime()
		{
			BigInteger r = new BigInteger("308636143175167811492623515537541734843573549327605293463169625072911693");
			BigInteger s = new BigInteger("852401710738814635664888632022555967400445256405412579597015412971797143");

			byte[] kData = new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655").ToByteArrayUnsigned();

			SecureRandom k = FixedSecureRandom.From(kData);

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

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

			ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
				new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
				spec);

			ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
				curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
				spec);

			ISigner sgr = SignerUtilities.GetSigner("SHA1withECNR");
			byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

			checkSignature(239, priKey, pubKey, sgr, k, message, r, s);
		}
Exemple #5
0
        public MemoryBlockchain(Block? genesisBlock = null)
        {
            this.shutdownToken = new CancellationToken();
            this.random = new Random();

            // create the key pair that block rewards will be sent to
            var keyPair = TransactionManager.CreateKeyPair();
            this._coinbasePrivateKey = keyPair.Item1;
            this._coinbasePublicKey = keyPair.Item2;

            // initialize unit test storage
            this._storageContext = new MemoryStorageContext();
            this._cacheContext = new CacheContext(this._storageContext);

            // initialize unit test rules
            this._rules = new UnitTestRules(this._cacheContext);

            // initialize blockchain calculator
            this._calculator = new BlockchainCalculator(this._rules, this._cacheContext, this.shutdownToken);

            // create and mine the genesis block
            this._genesisBlock = genesisBlock ?? MineEmptyBlock(0);

            // update genesis blockchain and add to storage
            this._rules.SetGenesisBlock(this._genesisBlock);
            this._currentBlockchain = this._rules.GenesisBlockchain;
            this._genesisChainedBlock = AddBlock(this._genesisBlock, null).Item2;
        }
        public ECDiffieHellmanBc(Int32 keySize)
        {
            Org.BouncyCastle.Asn1.X9.X9ECParameters ecParams;
            switch (keySize) {
            case 256:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256r1");
                break;
            case 384:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
                break;
            case 521:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp521r1");
                break;
            default:
                throw new ArgumentException("ECDiffieHellman key size " + keySize + " not supported");
            }
            _keySize = keySize;
            _domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());

            // Initialize key generation parameters with new SecureRandom
            Org.BouncyCastle.Security.SecureRandom secureRandom = new Org.BouncyCastle.Security.SecureRandom();
            ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(_domainParameters, secureRandom);

            // Generate key pair from domain parameters
            Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator generator = new Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator();
            generator.Init(keyGenParams);
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();

            // Save the private and public key parameters
            _privateKeyParameters = (ECPrivateKeyParameters) keyPair.Private;
            _publicKeyParameters = (ECPublicKeyParameters) keyPair.Public;

            _kdf = ECDiffieHellmanKeyDerivationFunction.Hash;
            _hashAlgorithm = CngAlgorithm.Sha256;
        }
 /// <summary>
 /// Inits the instance for encryption.
 /// </summary>
 /// <param name="privateKey">The private key.</param>
 /// <param name="publicKey">The public key.</param>
 public void InitForDecryption(ECDHPrivateKeyParameters privateKey, ECDHPublicKeyParameters publicKey)
 {
     _fingerPrint = (byte[]) privateKey.FingerPrint.Clone();
     _privateKey = privateKey;
     _publicKey = publicKey;
     _forEncryption = false;
 }
		public MqvPrivateParameters(
			ECPrivateKeyParameters	staticPrivateKey,
			ECPrivateKeyParameters	ephemeralPrivateKey,
			ECPublicKeyParameters	ephemeralPublicKey)
		{
            if (staticPrivateKey == null)
                throw new ArgumentNullException("staticPrivateKey");
            if (ephemeralPrivateKey == null)
                throw new ArgumentNullException("ephemeralPrivateKey");

            ECDomainParameters parameters = staticPrivateKey.Parameters;
            if (!parameters.Equals(ephemeralPrivateKey.Parameters))
                throw new ArgumentException("Static and ephemeral private keys have different domain parameters");

            if (ephemeralPublicKey == null)
            {
                ephemeralPublicKey = new ECPublicKeyParameters(
                    parameters.G.Multiply(ephemeralPrivateKey.D),
                    parameters);
            }
            else if (!parameters.Equals(ephemeralPublicKey.Parameters))
            {
                throw new ArgumentException("Ephemeral public key has different domain parameters");
            }

            this.staticPrivateKey = staticPrivateKey;
            this.ephemeralPrivateKey = ephemeralPrivateKey;
            this.ephemeralPublicKey = ephemeralPublicKey;
		}
Exemple #9
0
        public void TestECNR192bitPrime()
        {
            BigInteger r  = new BigInteger("2474388605162950674935076940284692598330235697454145648371");
            BigInteger s  = new BigInteger("2997192822503471356158280167065034437828486078932532073836");

            byte[] kData = new BigInteger("dcc5d1f1020906df2782360d36b2de7a17ece37d503784af", 16).ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

            X9ECParameters p = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime192v1);
            ECDomainParameters spec = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECCurve curve = spec.Curve;

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                curve.DecodePoint(Hex.Decode("0262B12D60690CDCF330BABAB6E69763B471F994DD702D16A5")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("SHA1withECNR");
            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            checkSignature(192, priKey, pubKey, sgr, k, message, r, s);
        }
Exemple #10
0
        /// <summary>
        /// Creates ECDSA from imported data
        /// </summary>
        /// <param name="type">0 or 1 (1 faster)</param>
        /// <param name="forSign">if created for signing, otherwise for verifying</param>
        /// <param name="import">Imporeted public or private key</param>
        public ECDSAWrapper(int type, bool forSign, byte[] import)
        {
            this.initCurveandParams(type);

            if (forSign)
            {
                try
                {
                    //import - D (BigInteger)
                    SecureRandom random = new SecureRandom();
                    BigInteger Drec = new BigInteger(import);
                    ECPrivateKeyParameters ecPrivImported = new ECPrivateKeyParameters(Drec, this.parameters);
                    ParametersWithRandom ecPrivImportedpwr = new ParametersWithRandom(ecPrivImported, random);
                    this.ecdsa.Init(true, ecPrivImportedpwr);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error while creating ECDSAWrapper from import for signing", ex);
                }
            }
            else
            {
                try
                {
                    //import - Q (ECPoint)
                    ECPoint Qrec = this.ecCurve.DecodePoint(import);
                    ECPublicKeyParameters recPub = new ECPublicKeyParameters(Qrec, this.parameters);
                    this.ecdsa.Init(false, recPub);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error while creating ECDSAWrapperfom import for verifying", ex);
                }
            }
        }
        public void TestECNR192bitPrime()
        {
            IBigInteger r  = new BigInteger("2474388605162950674935076940284692598330235697454145648371");
            IBigInteger s  = new BigInteger("2997192822503471356158280167065034437828486078932532073836");

            byte[] kData = new BigInteger("dcc5d1f1020906df2782360d36b2de7a17ece37d503784af", 16).ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

            FPCurve curve = new FPCurve(
                new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q (or p)
                new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", 16),   // a
                new BigInteger("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", 16));  // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("03188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012")), // G
                new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                curve.DecodePoint(Hex.Decode("0262B12D60690CDCF330BABAB6E69763B471F994DD702D16A5")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("SHA1withECNR");
            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            checkSignature(192, priKey, pubKey, sgr, k, message, r, s);
        }
        /// <summary>
        /// Creates a signature for the given messsage and the given private key.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="privateKey">The array of 32 bytes of the private key.</param>
        /// <param name="useCompressedPublicKey">true to specify that the public key should have the compressed format; otherwise, false.</param>
        /// <exception cref="ArgumentException">The message is null or private key is null or invalid.</exception>
        /// <returns>The signature for the given message and the given private key in base-64 encoding.</returns>
        public static string SingMesssage(string message, byte[] privateKey, bool useCompressedPublicKey)
        {
            if (message == null)
            {
                throw new ArgumentException("The message is null.", nameof(message));
            }

            if (privateKey == null)
            {
                throw new ArgumentException("The private key is null.", nameof(privateKey));
            }

            if (!BitcoinPrivateKey.IsValid(privateKey))
            {
                throw new ArgumentException("The private key is invalid.", nameof(privateKey));
            }

            ECPrivateKeyParameters parameters = new ECPrivateKeyParameters(new BigInteger(1, privateKey), domainParameters);

            ECDsaSigner signer = new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest()));
            signer.Init(true, parameters);

            var hash = GetMessageHash(message);

            BigInteger[] signatureArray = signer.GenerateSignature(hash);
            BigInteger r = signatureArray[0];
            BigInteger s = signatureArray[1];

            s = NormalizeS(s);

            byte[] encodedPublicKey = BitcoinPrivateKey.ToEncodedPublicKey(privateKey, useCompressedPublicKey);

            int pubKeyMaskOffset = useCompressedPublicKey ? 4 : 0;

            Signature signature = null;

            for (int i = 0; i < 4; i++)
            {
                Signature candidateSignature = new Signature();
                candidateSignature.PublicKeyMask = i + pubKeyMaskOffset;
                candidateSignature.R = r;
                candidateSignature.S = s;

                byte[] recoveredPublicKey = RecoverPublicKeyFromSignature(hash, candidateSignature);
                if (recoveredPublicKey != null && recoveredPublicKey.SequenceEqual(encodedPublicKey))
                {
                    signature = candidateSignature;
                    break;
                }
            }

            if (signature == null)
            {
                // this should not happen
                throw new Exception("The public key is not recoverable from signature.");
            }

            return EncodeSignature(signature);
        }
Exemple #13
0
		public void TestECDsa192bitPrime()
		{
			BigInteger r = new BigInteger("3342403536405981729393488334694600415596881826869351677613");
			BigInteger s = new BigInteger("5735822328888155254683894997897571951568553642892029982342");

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

			SecureRandom k = FixedSecureRandom.From(kData);

			FpCurve curve = new FpCurve(
				new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
				new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
				new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

			ECDomainParameters parameters = new ECDomainParameters(
				curve,
				curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
				new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

			ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
				"ECDSA",
				new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
				parameters);

			ParametersWithRandom param = new ParametersWithRandom(priKey, k);

			ECDsaSigner ecdsa = new ECDsaSigner();

			ecdsa.Init(true, param);

			byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
			BigInteger[] sig = ecdsa.GenerateSignature(message);

			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(
				"ECDSA",
				curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
				parameters);

			ecdsa.Init(false, pubKey);
			if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
			{
				Fail("verification fails");
			}
		}
        public void Init(ICipherParameters parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                parameters = ((ParametersWithRandom)parameters).Parameters;
            }

            this.PrivKey = (ECPrivateKeyParameters)parameters;
        }
		public MqvPrivateParameters(
			ECPrivateKeyParameters	staticPrivateKey,
			ECPrivateKeyParameters	ephemeralPrivateKey,
			ECPublicKeyParameters	ephemeralPublicKey)
		{
			this.staticPrivateKey = staticPrivateKey;
			this.ephemeralPrivateKey = ephemeralPrivateKey;
			this.ephemeralPublicKey = ephemeralPublicKey;
		}
        public static string ConvertPrikToHexString(string privateKey)
        {
            TextReader ptr = new StringReader(privateKey);

            Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(ptr);
            Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters ecdsaPrivateKey = (Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters)pem.ReadObject();
            var Db = ByteArrayToHexString(ecdsaPrivateKey.D.ToByteArrayUnsigned());

            return(Db);
        }
Exemple #17
0
        public TestBlocks(TestBlocks parent)
        {
            this.random = parent.random;
            this.txManager = parent.txManager;
            this.coinbasePrivateKey = parent.coinbasePrivateKey;
            this.coinbasePublicKey = parent.coinbasePublicKey;

            this.miner = parent.miner;
            this.rules = parent.rules;

            this.blocks = parent.blocks.ToImmutable().ToBuilder();
            this.chain = parent.chain.ToImmutable().ToBuilder();
        }
        public void InitForEncryption(ISecureRandom random, ECDHPublicKeyParameters publicKey, byte[] fingerPrint, out ECDHPublicKeyParameters ephemeralPublicKey)
        {
            var genParams = publicKey.CreateKeyGenerationParameters(random, publicKey.HashAlgorithm, publicKey.SymmetricKeyAlgorithm);
            var generator = new ECKeyPairGenerator("ECDH");
            generator.Init(genParams);
            var ephemeralKeyPair = generator.GenerateKeyPair();

            _fingerPrint = (byte[])fingerPrint.Clone();
            _privateKey = (ECPrivateKeyParameters)ephemeralKeyPair.Private;
            _publicKey = publicKey;
            _forEncryption = true;
            ephemeralPublicKey = (ECDHPublicKeyParameters)ephemeralKeyPair.Public;
        }
Exemple #19
0
        public ECKeyPair([NotNull] ECPublicKeyParameters publicKey, [NotNull] ECPrivateKeyParameters privateKey)
        {
            if (publicKey == null)
            {
                throw new ArgumentNullException(nameof(publicKey));
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            PublicKey = publicKey;
            PrivateKey = privateKey;
        }
        /// <summary>
        /// Initialize new CKeyPair instance with random secret.
        /// </summary>
        public CKeyPair(bool Compressed = true)
        {
            var genParams = new ECKeyGenerationParameters(domain, new SecureRandom());
            var generator = new ECKeyPairGenerator("ECDSA");
            generator.Init(genParams);
            var ecKeyPair = generator.GenerateKeyPair();

            _Private = (ECPrivateKeyParameters)ecKeyPair.Private;
            _Public = (ECPublicKeyParameters)ecKeyPair.Public;

            if (Compressed)
            {
                _Public = Compress(_Public);
            }
        }
Exemple #21
0
        private void ecNR239bitPrime()
        {
            BigInteger n = new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307");

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

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

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                parameters);

            ECNRSigner ecnr = new ECNRSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecnr.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecnr.GenerateSignature(message);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong.", r, sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong.", s, sig[1]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                parameters);

            ecnr.Init(false, pubKey);
            if (!ecnr.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        public ECDsaBouncyCastle(byte[] encodedKey, bool isPrivateKey)
        {
            ContractsCommon.NotNull(encodedKey, "encodedKey");

            var secp256k1 = SecP256k1;
            if (isPrivateKey)
            {
                var d = new BigInteger(encodedKey);
                _publicKey = new ECPublicKeyParameters(secp256k1.G.Multiply(d), secp256k1);
                _privateKey = new ECPrivateKeyParameters(d, secp256k1);
            }
            else
            {
                _publicKey = new ECPublicKeyParameters(secp256k1.Curve.DecodePoint(encodedKey), secp256k1);
            }
        }
        public byte[] CreatePrivateKeyScript(Transaction tx, int inputIndex, byte hashType, ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey)
        {
            //TODO
            var scriptEngine = new ScriptEngine();

            var publicAddress = CreatePublicAddress(publicKey);
            var publicKeyScript = CreatePublicKeyScript(publicAddress);
            var txSignature = scriptEngine.TxSignature(publicKeyScript, tx, inputIndex, hashType);
            var txSignatureHash = SHA256Static.ComputeDoubleHash(txSignature);

            //Debug.WriteLine("Signing Tx:       {0}".Format2(txSignature.ToHexDataString()));
            //Debug.WriteLine("Signing Tx  Hash: {0}".Format2(txSignatureHash.ToHexDataString()));

            var signer = new ECDsaSigner();
            signer.Init(forSigning: true, parameters: privateKey);
            var signature = signer.GenerateSignature(txSignatureHash);
            var r = signature[0];
            var s = signature[1];

            byte[] sigEncoded;
            using (var stream = new MemoryStream())
            {
                using (var asn1Stream = new Asn1OutputStream(stream))
                {
                    asn1Stream.WriteObject(new DerSequence(new DerInteger(r), new DerInteger(s)));
                }

                sigEncoded = stream.ToArray().Concat(hashType);
            }

            //Debug.WriteLine("Sig R:       {0}".Format2(r.ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Sig S:       {0}".Format2(s.ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Sig Encoded: {0}".Format2(sigEncoded.ToHexDataString()));

            using (var privateKeyScript = new ScriptBuilder())
            {
                privateKeyScript.WritePushData(sigEncoded);
                privateKeyScript.WritePushData(publicAddress);
                //Debug.WriteLine("Private Script: {0}".Format2(privateKeyScript.GetScript().ToHexDataString()));

                return privateKeyScript.GetScript();
            }
        }
Exemple #24
0
        public string GetPublicKey(byte[] privKey)
        {
            var privHex = BitConverter.ToString(privKey).Replace("-", "");

            privHex = privHex.Substring(104, (privHex.Length - 104));
            privKey = StringToByteArray(privHex);

            Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(privKey);
            this.privateKeyParameters = new Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters(d, domain);
            Org.BouncyCastle.Math.EC.ECPoint q = domain.G.Multiply(d);
            this.pubKeyParameters = new Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters(q, domain);

            //strip first byte
            var pubBytes         = this.pubKeyParameters.Q.GetEncoded();
            var pubHex           = BitConverter.ToString(pubBytes).Replace("-", "");
            var strippedPubBytes = StringToByteArray(pubHex.Substring(2, (pubHex.Length - 2)));

            return("MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE" + Convert.ToBase64String(strippedPubBytes));
        }
        public U2FKeyReferenceImpl([NotNull] X509Certificate vendorCertificate,
            [NotNull] ECPrivateKeyParameters certificatePrivateKey, [NotNull] IKeyPairGenerator keyPairGenerator,
            [NotNull] IKeyHandleGenerator keyHandleGenerator, [NotNull] IKeyDataStore dataStore,
            [NotNull] IUserPresenceVerifier userPresenceVerifier, [NotNull] IKeyCrypto crypto)
        {
            if (vendorCertificate == null)
            {
                throw new ArgumentNullException(nameof(vendorCertificate));
            }
            if (certificatePrivateKey == null)
            {
                throw new ArgumentNullException(nameof(certificatePrivateKey));
            }
            if (keyPairGenerator == null)
            {
                throw new ArgumentNullException(nameof(keyPairGenerator));
            }
            if (keyHandleGenerator == null)
            {
                throw new ArgumentNullException(nameof(keyHandleGenerator));
            }
            if (dataStore == null)
            {
                throw new ArgumentNullException(nameof(dataStore));
            }
            if (userPresenceVerifier == null)
            {
                throw new ArgumentNullException(nameof(userPresenceVerifier));
            }
            if (crypto == null)
            {
                throw new ArgumentNullException(nameof(crypto));
            }

            this.vendorCertificate = vendorCertificate;
            this.certificatePrivateKey = certificatePrivateKey;
            this.keyPairGenerator = keyPairGenerator;
            this.keyHandleGenerator = keyHandleGenerator;
            this.dataStore = dataStore;
            this.userPresenceVerifier = userPresenceVerifier;
            this.crypto = crypto;
        }
        public ECDsaBouncyCastle()
        {
            var secp256k1 = SecP256k1;
            var privateKey = new byte[secp256k1.N.BitLength];
            BigInteger d;

            using (var cryptoRng = RandomNumberGenerator.Create())
            {
                do
                {
                    cryptoRng.GetBytes(privateKey);
                    d = new BigInteger(1, privateKey);
                }
                while (d.SignValue == 0 || (d.CompareTo(secp256k1.N) >= 0));

            }

            _publicKey = new ECPublicKeyParameters(secp256k1.G.Multiply(d), secp256k1);
            _privateKey = new ECPrivateKeyParameters(d, secp256k1);
        }
Exemple #27
0
		public void TestEC()
		{
			BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
			BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
			BigInteger ECParraH = new BigInteger(Base64.Decode("AQ=="));
			BigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
			BigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
			BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
			BigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

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

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

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

			ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

			SubjectPublicKeyInfo subinfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(ecPub);
			PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecPriv);

			ECPublicKeyParameters tecPub = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(subinfo);
			ECPrivateKeyParameters tecPriv = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

			Assert.IsTrue(tecPub.Equals(ecPub), "EC: public key to info back to public key");
			Assert.IsTrue(tecPriv.Equals(ecPriv), "EC: private key to info back to private key");
		}
        // The ECMQV Primitive as described in SEC-1, 3.4
        private static ECPoint CalculateMqvAgreement(
            ECDomainParameters		parameters,
            ECPrivateKeyParameters	d1U,
            ECPrivateKeyParameters	d2U,
            ECPublicKeyParameters	Q2U,
            ECPublicKeyParameters	Q1V,
            ECPublicKeyParameters	Q2V)
        {
            BigInteger n = parameters.N;
            int e = (n.BitLength + 1) / 2;
            BigInteger powE = BigInteger.One.ShiftLeft(e);

            ECCurve curve = parameters.Curve;

            ECPoint[] points = new ECPoint[]{
                // The Q2U public key is optional - but will be calculated for us if it wasn't present
                ECAlgorithms.ImportPoint(curve, Q2U.Q),
                ECAlgorithms.ImportPoint(curve, Q1V.Q),
                ECAlgorithms.ImportPoint(curve, Q2V.Q)
            };

            curve.NormalizeAll(points);

            ECPoint q2u = points[0], q1v = points[1], q2v = points[2];

            BigInteger x = q2u.AffineXCoord.ToBigInteger();
            BigInteger xBar = x.Mod(powE);
            BigInteger Q2UBar = xBar.SetBit(e);
            BigInteger s = d1U.D.Multiply(Q2UBar).Add(d2U.D).Mod(n);

            BigInteger xPrime = q2v.AffineXCoord.ToBigInteger();
            BigInteger xPrimeBar = xPrime.Mod(powE);
            BigInteger Q2VBar = xPrimeBar.SetBit(e);

            BigInteger hs = parameters.H.Multiply(s).Mod(n);

            return ECAlgorithms.SumOfTwoMultiplies(
                q1v, Q2VBar.Multiply(hs).Mod(n), q2v, hs);
        }
Exemple #29
0
        public TestBlocks(Block genesisBlock = null)
        {
            // create the key pair that block rewards will be sent to
            var keyPair = txManager.CreateKeyPair();
            coinbasePrivateKey = keyPair.Item1;
            coinbasePublicKey = keyPair.Item2;

            // create and mine the genesis block
            genesisBlock = genesisBlock ?? MineEmptyBlock(UInt256.Zero);

            // initialize unit test rules
            rules = new UnitTestRules()
            {
                // disable execution of rules validation
                ValidateTransactionAction = (_, __) => { },
                ValidationTransactionScriptAction = (_, __, ___, ____, _____) => { }
            };
            ChainParams.SetGenesisBlock(genesisBlock);

            blocks.Add(genesisBlock);
            chain.AddBlock(ChainParams.GenesisChainedHeader);
        }
Exemple #30
0
        public MqvPrivateParameters(
            ECPrivateKeyParameters staticPrivateKey,
            ECPrivateKeyParameters ephemeralPrivateKey,
            ECPublicKeyParameters ephemeralPublicKey)
        {
            if (staticPrivateKey == null)
            {
                throw new ArgumentNullException("staticPrivateKey");
            }
            if (ephemeralPrivateKey == null)
            {
                throw new ArgumentNullException("ephemeralPrivateKey");
            }

            ECDomainParameters parameters = staticPrivateKey.Parameters;

            if (!parameters.Equals(ephemeralPrivateKey.Parameters))
            {
                throw new ArgumentException("Static and ephemeral private keys have different domain parameters");
            }

            if (ephemeralPublicKey == null)
            {
                ephemeralPublicKey = new ECPublicKeyParameters(
                    parameters.G.Multiply(ephemeralPrivateKey.D),
                    parameters);
            }
            else if (!parameters.Equals(ephemeralPublicKey.Parameters))
            {
                throw new ArgumentException("Ephemeral public key has different domain parameters");
            }

            this.staticPrivateKey    = staticPrivateKey;
            this.ephemeralPrivateKey = ephemeralPrivateKey;
            this.ephemeralPublicKey  = ephemeralPublicKey;
        }
Exemple #31
0
        /**
         * we Generate a self signed certificate for the sake of testing - ECDSA
         */
        internal void checkCreation3()
        {
            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

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

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            //
            // set up the keys
            //
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			try
//			{
//				KeyFactory fact = KeyFactory.GetInstance("ECDSA");
//
//				privKey = fact.generatePrivate(privKeySpec);
//				pubKey = fact.generatePublic(pubKeySpec);
//			}
//			catch (Exception e)
//			{
//				Fail("error setting up keys - " + e.ToString());
//				return;
//			}

            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            IList order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);


            //
            // ToString test
            //
            X509Name p = new X509Name(order, attrs);
            string s = p.ToString();

            if (!s.Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,[email protected]"))
            {
                Fail("ordered X509Principal test failed - s = " + s + ".");
            }

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1withECDSA");

            try
            {
                X509Certificate cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                X509CertificateParser fact = new X509CertificateParser();
                cert = fact.ReadCertificate(cert.GetEncoded());

                //
                // try with point compression turned off
                //
//				((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
                ECPoint q = pubKey.Q.Normalize();
                pubKey = new ECPublicKeyParameters(
                    pubKey.AlgorithmName,
                    q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                    pubKey.Parameters);

                certGen.SetPublicKey(pubKey);

                cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = fact.ReadCertificate(cert.GetEncoded());

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            X509Name pr = new X509Name("O=\"The Bouncy Castle, The Legion of\",[email protected],ST=Victoria,L=Melbourne,C=AU");

            if (!pr.ToString().Equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
            {
                Fail("string based X509Principal test failed.");
            }

            pr = new X509Name("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU");

            if (!pr.ToString().Equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
            {
                Fail("string based X509Principal test failed.");
            }
        }
Exemple #32
0
 protected bool Equals(ECPrivateKeyParameters other) =>
 (this.d.Equals(other.d) && base.Equals((ECKeyParameters)other));
Exemple #33
0
 public MqvPrivateParameters(
     ECPrivateKeyParameters staticPrivateKey,
     ECPrivateKeyParameters ephemeralPrivateKey)
     : this(staticPrivateKey, ephemeralPrivateKey, null)
 {
 }
 protected bool Equals(ECPrivateKeyParameters other)
 {
     return(d.Equals(other.d) && Equals((ECKeyParameters)other));
 }
Exemple #35
0
 public MqvPrivateParameters(ECPrivateKeyParameters staticPrivateKey, ECPrivateKeyParameters ephemeralPrivateKey, ECPublicKeyParameters ephemeralPublicKey)
 {
     this.staticPrivateKey    = staticPrivateKey;
     this.ephemeralPrivateKey = ephemeralPrivateKey;
     this.ephemeralPublicKey  = ephemeralPublicKey;
 }
Exemple #36
0
        /**
         * we Generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECCert(
            string				algorithm,
            DerObjectIdentifier	algOid)
        {
            FpCurve curve = new FpCurve(
                new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16),   // a
                new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16));  // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                spec);

//			//
//			// set up the keys
//			//
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.GetInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);


            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            IList order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm(algorithm);


            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            X509CertificateParser fact = new X509CertificateParser();
            cert = fact.ReadCertificate(cert.GetEncoded());

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            ECPoint q = pubKey.Q.Normalize();
            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                pubKey.Parameters);

            certGen.SetPublicKey(pubKey);

            cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = fact.ReadCertificate(cert.GetEncoded());

            if (!cert.SigAlgOid.Equals(algOid.ToString()))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (cert.GetSigAlgParams() != null)
            {
                Fail("sig parameters present");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = cert.GetTbsCertificate();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(cert.GetSignature()))
            {
                Fail("EC certificate signature not mapped correctly.");
            }
            // Console.WriteLine(cert);
        }
Exemple #37
0
		private void StaticTest()
		{
			FpCurve curve = new FpCurve(
				new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
				new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
				new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

			ECDomainParameters parameters = new ECDomainParameters(
				curve,
				curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
				new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

			ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
				"ECDH",
				new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
				parameters);

			ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
				"ECDH",
				curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
				parameters);

			AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey);
			AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey);

			//
			// stream test
			//
			IesEngine i1 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()));
			IesEngine i2 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()));
			byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
			byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
			IesParameters p = new IesParameters(d, e, 64);

			i1.Init(true, p1.Private, p2.Public, p);
			i2.Init(false, p2.Private, p1.Public, p);

			byte[] message = Hex.Decode("1234567890abcdef");

			byte[] out1 = i1.ProcessBlock(message, 0, message.Length);

			if (!AreEqual(out1, Hex.Decode("468d89877e8238802403ec4cb6b329faeccfa6f3a730f2cdb3c0a8e8")))
			{
				Fail("stream cipher test failed on enc");
			}

			byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);

			if (!AreEqual(out2, message))
			{
				Fail("stream cipher test failed");
			}

			//
			// twofish with CBC
			//
			BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new TwofishEngine()));
			BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new TwofishEngine()));
			i1 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()),
				c1);
			i2 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()),
				c2);
			d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
			e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
			p = new IesWithCipherParameters(d, e, 64, 128);

			i1.Init(true, p1.Private, p2.Public, p);
			i2.Init(false, p2.Private, p1.Public, p);

			message = Hex.Decode("1234567890abcdef");

			out1 = i1.ProcessBlock(message, 0, message.Length);

			if (!AreEqual(out1, Hex.Decode("b8a06ea5c2b9df28b58a0a90a734cde8c9c02903e5c220021fe4417410d1e53a32a71696")))
			{
				Fail("twofish cipher test failed on enc");
			}

			out2 = i2.ProcessBlock(out1, 0, out1.Length);

			if (!AreEqual(out2, message))
			{
				Fail("twofish cipher test failed");
			}
		}
Exemple #38
0
 protected bool Equals(ECPrivateKeyParameters other)
 {
     return(this.d.Equals(other.d) && base.Equals(other));
 }