public TimeStampRequest Generate(
			string		digestAlgorithmOid,
			byte[]		digest,
			IBigInteger	nonce)
        {
            if (digestAlgorithmOid == null)
            {
                throw new ArgumentException("No digest algorithm specified");
            }

            DerObjectIdentifier digestAlgOid = new DerObjectIdentifier(digestAlgorithmOid);

            AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOid, DerNull.Instance);
            MessageImprint messageImprint = new MessageImprint(algID, digest);

            X509Extensions  ext = null;

            if (extOrdering.Count != 0)
            {
                ext = new X509Extensions(extOrdering, extensions);
            }

            DerInteger derNonce = nonce == null
                ?	null
                :	new DerInteger(nonce);

            return new TimeStampRequest(
                new TimeStampReq(messageImprint, reqPolicy, derNonce, certReq, ext));
        }
 public DsaPublicBcpgKey(IBigInteger p, IBigInteger q, IBigInteger g, IBigInteger y)
 {
     _p = new MPInteger(p);
     _q = new MPInteger(q);
     _g = new MPInteger(g);
     _y = new MPInteger(y);
 }
Esempio n. 3
0
        public RsaSecretBcpgKey(IBigInteger d, IBigInteger p, IBigInteger q)
        {
            // PGP requires (p < q)
            var cmp = p.CompareTo(q);

            if (cmp >= 0)
            {
                if (cmp == 0)
                {
                    throw new ArgumentException("p and q cannot be equal");
                }

                var tmp = p;
                p = q;
                q = tmp;
            }

            _d = new MPInteger(d);
            _p = new MPInteger(p);
            _q = new MPInteger(q);
            _u = new MPInteger(p.ModInverse(q));

            _expP = d.Remainder(p.Subtract(BigInteger.One));
            _expQ = d.Remainder(q.Subtract(BigInteger.One));
            _crt  = q.ModInverse(p);
        }
        public ECDomainParameters(ECCurve curve, ECPoint g, IBigInteger n, IBigInteger h, byte[] seed)
        {
            if (curve == null)
            {
                throw new ArgumentNullException("curve");
            }
            if (g == null)
            {
                throw new ArgumentNullException("g");
            }
            if (n == null)
            {
                throw new ArgumentNullException("n");
            }
            if (h == null)
            {
                throw new ArgumentNullException("h");
            }

            _curve = curve;
            _g     = g;
            _n     = n;
            _h     = h;
            _seed  = Arrays.Clone(seed);
        }
 public DHParameters(
     IBigInteger p,
     IBigInteger g,
     IBigInteger q)
     : this(p, g, q, 0)
 {
 }
        internal IBigInteger CalculatePrivate(
            DHParameters dhParams,
            ISecureRandom random)
        {
            int limit = dhParams.L;

            if (limit != 0)
            {
                return(new BigInteger(limit, random).SetBit(limit - 1));
            }

            IBigInteger min = BigInteger.Two;
            int         m   = dhParams.M;

            if (m != 0)
            {
                min = BigInteger.One.ShiftLeft(m - 1);
            }

            IBigInteger max = dhParams.P.Subtract(BigInteger.Two);
            IBigInteger q   = dhParams.Q;

            if (q != null)
            {
                max = q.Subtract(BigInteger.Two);
            }

            return(BigIntegers.CreateRandomInRange(min, max, random));
        }
 public DHPrivateKeyParameters(
     IBigInteger x,
     DHParameters	parameters)
     : base(true, parameters)
 {
     this.x = x;
 }
 /**
  * @param privateKey
  */
 public NaccacheSternKeyParameters(bool privateKey, IBigInteger g, IBigInteger n, int lowerSigmaBound)
     : base(privateKey)
 {
     this.g = g;
     this.n = n;
     this.lowerSigmaBound = lowerSigmaBound;
 }
 public IssuerAndSerialNumber(
     X509Name	name,
     IBigInteger	serialNumber)
 {
     this.name = name;
     this.serialNumber = new DerInteger(serialNumber);
 }
        public RsaPrivateCrtKeyParameters(
            IBigInteger modulus,
            IBigInteger publicExponent,
            IBigInteger privateExponent,
            IBigInteger p,
            IBigInteger q,
            IBigInteger dP,
            IBigInteger dQ,
            IBigInteger qInv)
            : base(true, modulus, privateExponent)
        {
            ValidateValue(publicExponent, "publicExponent", "exponent");
            ValidateValue(p, "p", "P value");
            ValidateValue(q, "q", "Q value");
            ValidateValue(dP, "dP", "DP value");
            ValidateValue(dQ, "dQ", "DQ value");
            ValidateValue(qInv, "qInv", "InverseQ value");

            this.e    = publicExponent;
            this.p    = p;
            this.q    = q;
            this.dP   = dP;
            this.dQ   = dQ;
            this.qInv = qInv;
        }
Esempio n. 11
0
        private PrivateKeyInfo(
            Asn1Sequence seq)
        {
            IEnumerator e = seq.GetEnumerator();

            e.MoveNext();
            IBigInteger version = ((DerInteger)e.Current).Value;

            if (version.IntValue != 0)
            {
                throw new ArgumentException("wrong version for private key info");
            }

            e.MoveNext();
            algID = AlgorithmIdentifier.GetInstance(e.Current);

            try
            {
                e.MoveNext();
                Asn1OctetString data = (Asn1OctetString)e.Current;

                privKey = Asn1Object.FromByteArray(data.GetOctets());
            }
            catch (IOException)
            {
                throw new ArgumentException("Error recoverying private key from sequence");
            }

            if (e.MoveNext())
            {
                attributes = Asn1Set.GetInstance((Asn1TaggedObject)e.Current, false);
            }
        }
        private static ECPoint ImplShamirsTrick(ECPoint p, IBigInteger k, ECPoint q, IBigInteger l)
        {
            var m = System.Math.Max(k.BitLength, l.BitLength);
            var z = p.Add(q);
            var r = p.Curve.Infinity;

            for (var i = m - 1; i >= 0; --i)
            {
                r = r.Twice();

                if (k.TestBit(i))
                {
                    r = r.Add(l.TestBit(i) ? z : p);
                }
                else
                {
                    if (l.TestBit(i))
                    {
                        r = r.Add(q);
                    }
                }
            }

            return r;
        }
Esempio n. 13
0
        /**
         * Constructor for Ppb.
         * @param m  The exponent <code>m</code> of
         * <code>F<sub>2<sup>m</sup></sub></code>.
         * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param x The IBigInteger representing the value of the field element.
         */
        public F2MFieldElement(int m, int k1, int k2, int k3, IBigInteger x)
        {
            // t = m / 32 rounded up to the next integer
            _t = (m + 31) >> 5;
            _x = new IntArray(x, _t);

            if ((k2 == 0) && (k3 == 0))
            {
                _representation = Tpb;
            }
            else
            {
                if (k2 >= k3)
                {
                    throw new ArgumentException("k2 must be smaller than k3");
                }
                if (k2 <= 0)
                {
                    throw new ArgumentException("k2 must be larger than 0");
                }

                _representation = Ppb;
            }

            if (x.SignValue < 0)
            {
                throw new ArgumentException("x value cannot be negative");
            }

            _m  = m;
            _k1 = k1;
            _k2 = k2;
            _k3 = k3;
        }
Esempio n. 14
0
        // 5.4 pg 29

        /**
         * return true if the value r and s represent a DSA signature for
         * the passed in message (for standard DSA the message should be
         * a SHA-1 hash of the real message to be verified).
         */
        public bool VerifySignature(byte[] message, IBigInteger r, IBigInteger s)
        {
            var n = _key.Parameters.N;

            // r and s should both in the range [1,n-1]
            if (r.SignValue < 1 || s.SignValue < 1 || r.CompareTo(n) >= 0 || s.CompareTo(n) >= 0)
            {
                return(false);
            }

            var e = CalculateE(n, message);
            var c = s.ModInverse(n);

            var u1 = e.Multiply(c).Mod(n);
            var u2 = r.Multiply(c).Mod(n);

            var g = _key.Parameters.G;
            var q = ((ECPublicKeyParameters)_key).Q;

            var point = ECAlgorithms.SumOfTwoMultiplies(g, u1, q, u2);

            var v = point.X.ToBigInteger().Mod(n);

            return(v.Equals(r));
        }
Esempio n. 15
0
        private static IBigInteger allocateSerialNumber()
        {
            IBigInteger _tmp = serialNumber;

            serialNumber = serialNumber.Add(BigInteger.One);
            return(_tmp);
        }
        public RsaPrivateCrtKeyParameters(
            IBigInteger modulus,
            IBigInteger publicExponent,
            IBigInteger privateExponent,
            IBigInteger p,
            IBigInteger q,
            IBigInteger dP,
            IBigInteger dQ,
            IBigInteger qInv)
            : base(true, modulus, privateExponent)
        {
            ValidateValue(publicExponent, "publicExponent", "exponent");
            ValidateValue(p, "p", "P value");
            ValidateValue(q, "q", "Q value");
            ValidateValue(dP, "dP", "DP value");
            ValidateValue(dQ, "dQ", "DQ value");
            ValidateValue(qInv, "qInv", "InverseQ value");

            this.e = publicExponent;
            this.p = p;
            this.q = q;
            this.dP = dP;
            this.dQ = dQ;
            this.qInv = qInv;
        }
 public DsaParameters(
     IBigInteger p,
     IBigInteger q,
     IBigInteger g)
     : this(p, q, g, null)
 {
 }
        static TspTestUtil()
        {
            rand = new SecureRandom();

            kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpg.Init(new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), rand, 1024, 25));

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

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

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

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

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

            serialNumber = BigInteger.One;
        }
Esempio n. 19
0
        public X9Curve(
            X9FieldID fieldID,
            Asn1Sequence seq)
        {
            if (fieldID == null)
            {
                throw new ArgumentNullException("fieldID");
            }
            if (seq == null)
            {
                throw new ArgumentNullException("seq");
            }

            this.fieldIdentifier = fieldID.Identifier;

            if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
            {
                IBigInteger    q   = ((DerInteger)fieldID.Parameters).Value;
                X9FieldElement x9A = new X9FieldElement(q, (Asn1OctetString)seq[0]);
                X9FieldElement x9B = new X9FieldElement(q, (Asn1OctetString)seq[1]);
                curve = new FPCurve(q, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
            }
            else
            {
                if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
                {
                    // Characteristic two field
                    DerSequence         parameters = (DerSequence)fieldID.Parameters;
                    int                 m          = ((DerInteger)parameters[0]).Value.IntValue;
                    DerObjectIdentifier representation
                        = (DerObjectIdentifier)parameters[1];

                    int k1 = 0;
                    int k2 = 0;
                    int k3 = 0;
                    if (representation.Equals(X9ObjectIdentifiers.TPBasis))
                    {
                        // Trinomial basis representation
                        k1 = ((DerInteger)parameters[2]).Value.IntValue;
                    }
                    else
                    {
                        // Pentanomial basis representation
                        DerSequence pentanomial = (DerSequence)parameters[2];
                        k1 = ((DerInteger)pentanomial[0]).Value.IntValue;
                        k2 = ((DerInteger)pentanomial[1]).Value.IntValue;
                        k3 = ((DerInteger)pentanomial[2]).Value.IntValue;
                    }
                    X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[0]);
                    X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[1]);
                    // TODO Is it possible to get the order (n) and cofactor(h) too?
                    curve = new F2MCurve(m, k1, k2, k3, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
                }
            }

            if (seq.Count == 3)
            {
                seed = ((DerBitString)seq[2]).GetBytes();
            }
        }
Esempio n. 20
0
        private void randMult(string curveName)
        {
            X9ECParameters spec = SecNamedCurves.GetByName(curveName);

            IBigInteger  n      = spec.N;
            ECPoint      g      = (ECPoint)spec.G;
            SecureRandom random = new SecureRandom();             //SecureRandom.getInstance("SHA1PRNG", "SUN");
            IBigInteger  k      = new BigInteger(n.BitLength - 1, random);

            ECPoint qMultiply = null;
            long    startTime = DateTimeUtilities.CurrentUnixMs();

            for (int i = 0; i < NUM_ROUNDS; i++)
            {
                qMultiply = g.Multiply(k);
            }
            long endTime = DateTimeUtilities.CurrentUnixMs();

            double avgDuration = (double)(endTime - startTime) / NUM_ROUNDS;

            Console.WriteLine(curveName);
            Console.Write("Millis   : ");
            Console.WriteLine(avgDuration);
            Console.WriteLine();
        }
Esempio n. 21
0
        public virtual byte[] GenerateAgreement(IAsymmetricKeyParameter serverPublicKey)
        {
            basicAgreement.Init(clientPrivateKey);
            IBigInteger agreementValue = basicAgreement.CalculateAgreement(serverPublicKey);

            return(BigIntegers.AsUnsignedByteArray(agreementValue));
        }
        /**
         * D.3.2 pg 101
         * @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger)
         */
        public ECPoint Multiply(ECPoint p, IBigInteger k, IPreCompInfo preCompInfo)
        {
            // TODO Probably should try to add this
            // IBigInteger e = k.Mod(n); // n == order of p
            IBigInteger e = k;
            IBigInteger h = e.Multiply(BigInteger.Three);

            ECPoint neg = p.Negate();
            ECPoint R   = p;

            for (int i = h.BitLength - 2; i > 0; --i)
            {
                R = R.Twice();

                bool hBit = h.TestBit(i);
                bool eBit = e.TestBit(i);

                if (hBit != eBit)
                {
                    R = R.Add(hBit ? p : neg);
                }
            }

            return(R);
        }
        public SimpleBigDecimal Divide(SimpleBigDecimal b)
        {
            CheckScale(b);
            IBigInteger dividend = bigInt.ShiftLeft(scale);

            return(new SimpleBigDecimal(dividend.Divide(b.bigInt), scale));
        }
 public DHPrivateKeyParameters(
     IBigInteger x,
     DHParameters parameters)
     : base(true, parameters)
 {
     this.x = x;
 }
Esempio n. 25
0
        public void TestECMqvRandom()
        {
            var random = new SecureRandom();

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

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

            var pGen = new ECKeyPairGenerator();

            pGen.Init(new ECKeyGenerationParameters(parameters, random));


            // Pre-established key pairs
            IAsymmetricCipherKeyPair u1 = pGen.GenerateKeyPair();
            IAsymmetricCipherKeyPair v1 = pGen.GenerateKeyPair();

            // Ephemeral key pairs
            IAsymmetricCipherKeyPair u2 = pGen.GenerateKeyPair();
            IAsymmetricCipherKeyPair v2 = pGen.GenerateKeyPair();

            IBigInteger x = CalculateAgreement(u1, u2, v1, v2);

            if (x == null)
            {
                Fail("MQV Test Vector (random) agreement failed");
            }
        }
Esempio n. 26
0
        /**
         * X9.62 - 1998,<br/>
         * J.3.1, Page 152, ECDSA over the field Fp<br/>
         * an example with 192 bit prime
         */

        private static IBigInteger CalculateAgreement(
            IAsymmetricCipherKeyPair u1,
            IAsymmetricCipherKeyPair u2,
            IAsymmetricCipherKeyPair v1,
            IAsymmetricCipherKeyPair v2)
        {
            var u = new ECMqvBasicAgreement();

            u.Init(new MqvPrivateParameters(
                       (ECPrivateKeyParameters)u1.Private,
                       (ECPrivateKeyParameters)u2.Private,
                       (ECPublicKeyParameters)u2.Public));
            IBigInteger ux = u.CalculateAgreement(new MqvPublicParameters(
                                                      (ECPublicKeyParameters)v1.Public,
                                                      (ECPublicKeyParameters)v2.Public));

            var v = new ECMqvBasicAgreement();

            v.Init(new MqvPrivateParameters(
                       (ECPrivateKeyParameters)v1.Private,
                       (ECPrivateKeyParameters)v2.Private,
                       (ECPublicKeyParameters)v2.Public));
            IBigInteger vx = v.CalculateAgreement(new MqvPublicParameters(
                                                      (ECPublicKeyParameters)u1.Public,
                                                      (ECPublicKeyParameters)u2.Public));

            if (ux.Equals(vx))
            {
                return(ux);
            }

            return(null);
        }
 /**
  * @param privateKey
  */
 public NaccacheSternKeyParameters(bool privateKey, IBigInteger g, IBigInteger n, int lowerSigmaBound)
     : base(privateKey)
 {
     this.g = g;
     this.n = n;
     this.lowerSigmaBound = lowerSigmaBound;
 }
Esempio n. 28
0
        public IAsymmetricCipherKeyPair GenerateKeyPair()
        {
            ISecureRandom      random         = param.Random;
            Gost3410Parameters gost3410Params = param.Parameters;

            IBigInteger q = gost3410Params.Q;
            IBigInteger x;

            do
            {
                x = new BigInteger(256, random);
            }while (x.SignValue < 1 || x.CompareTo(q) >= 0);

            IBigInteger p = gost3410Params.P;
            IBigInteger a = gost3410Params.A;

            // calculate the public key.
            IBigInteger y = a.ModPow(x, p);

            if (param.PublicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(
                           new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet),
                           new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet)));
            }

            return(new AsymmetricCipherKeyPair(
                       new Gost3410PublicKeyParameters(y, gost3410Params),
                       new Gost3410PrivateKeyParameters(x, gost3410Params)));
        }
 /**
  * Initialises the client to begin new authentication attempt
  * @param N The safe prime associated with the client's verifier
  * @param g The group parameter associated with the client's verifier
  * @param digest The digest algorithm associated with the client's verifier
  * @param random For key generation
  */
 public virtual void Init(IBigInteger N, IBigInteger g, IDigest digest, SecureRandom random)
 {
     this.N = N;
     this.g = g;
     this.digest = digest;
     this.random = random;
 }
        public Gost3410Parameters(
			IBigInteger	p,
			IBigInteger	q,
			IBigInteger	a)
            : this(p, q, a, null)
        {
        }
        /**
        * Return a random IBigInteger not less than 'min' and not greater than 'max'
        *
        * @param min the least value that may be generated
        * @param max the greatest value that may be generated
        * @param random the source of randomness
        * @return a random IBigInteger value in the range [min,max]
        */
        public static IBigInteger CreateRandomInRange(
            IBigInteger min,
            IBigInteger max,
			// TODO Should have been just Random class
			ISecureRandom	random)
        {
            int cmp = min.CompareTo(max);
            if (cmp >= 0)
            {
                if (cmp > 0)
                    throw new ArgumentException("'min' may not be greater than 'max'");

                return min;
            }

            if (min.BitLength > max.BitLength / 2)
            {
                return CreateRandomInRange(BigInteger.Zero, max.Subtract(min), random).Add(min);
            }

            for (int i = 0; i < MaxIterations; ++i)
            {
                IBigInteger x = new BigInteger(max.BitLength, random);
                if (x.CompareTo(min) >= 0 && x.CompareTo(max) <= 0)
                {
                    return x;
                }
            }

            // fall back to a faster (restricted) method
            return new BigInteger(max.Subtract(min).BitLength - 1, random).Add(min);
        }
 public ElGamalParameter(
     IBigInteger p,
     IBigInteger g)
 {
     this.p = new DerInteger(p);
     this.g = new DerInteger(g);
 }
 public DsaParameters(
     IBigInteger p,
     IBigInteger q,
     IBigInteger g)
     : this(p, q, g, null)
 {
 }
Esempio n. 34
0
 public IssuerAndSerialNumber(
     X509Name name,
     IBigInteger serialNumber)
 {
     this.name         = name;
     this.serialNumber = new DerInteger(serialNumber);
 }
Esempio n. 35
0
        public TimeStampRequest Generate(
            string digestAlgorithmOid,
            byte[]          digest,
            IBigInteger nonce)
        {
            if (digestAlgorithmOid == null)
            {
                throw new ArgumentException("No digest algorithm specified");
            }

            DerObjectIdentifier digestAlgOid = new DerObjectIdentifier(digestAlgorithmOid);

            AlgorithmIdentifier algID          = new AlgorithmIdentifier(digestAlgOid, DerNull.Instance);
            MessageImprint      messageImprint = new MessageImprint(algID, digest);

            X509Extensions ext = null;

            if (extOrdering.Count != 0)
            {
                ext = new X509Extensions(extOrdering, extensions);
            }

            DerInteger derNonce = nonce == null
                                ?       null
                                :       new DerInteger(nonce);

            return(new TimeStampRequest(
                       new TimeStampReq(messageImprint, reqPolicy, derNonce, certReq, ext)));
        }
 public TimeStampResponse Generate(
     TimeStampRequest request,
     IBigInteger serialNumber,
     DateTime genTime)
 {
     return Generate(request, serialNumber, new DateTimeObject(genTime));
 }
 /**
  * Add a CRL entry with extensions.
  **/
 public void AddCrlEntry(
     IBigInteger userCertificate,
     DateTime revocationDate,
     X509Extensions extensions)
 {
     tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), extensions);
 }
Esempio n. 38
0
        private static ECPoint ImplShamirsTrick(ECPoint p, IBigInteger k, ECPoint q, IBigInteger l)
        {
            var m = System.Math.Max(k.BitLength, l.BitLength);
            var z = p.Add(q);
            var r = p.Curve.Infinity;

            for (var i = m - 1; i >= 0; --i)
            {
                r = r.Twice();

                if (k.TestBit(i))
                {
                    r = r.Add(l.TestBit(i) ? z : p);
                }
                else
                {
                    if (l.TestBit(i))
                    {
                        r = r.Add(q);
                    }
                }
            }

            return(r);
        }
 /**
  * Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
  * or 0 if CrlReason is not to be used
  **/
 public void AddCrlEntry(
     IBigInteger userCertificate,
     DateTime revocationDate,
     int reason)
 {
     tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), reason);
 }
Esempio n. 40
0
        public void TestDsa()
        {
            IBigInteger a = BigInteger.ValueOf(1), b = BigInteger.ValueOf(2), c = BigInteger.ValueOf(3);

            DsaParameters dsaP1 = new DsaParameters(a, b, c);
            DsaParameters dsaP2 = new DsaParameters(a, b, c);
            DsaParameters dsaP3 = new DsaParameters(b, c, a);

            doTest(dsaP1, dsaP2, dsaP3);

            DsaValidationParameters vp1 = new DsaValidationParameters(new byte[20], 1024);
            DsaValidationParameters vp2 = new DsaValidationParameters(new byte[20], 1024);
            DsaValidationParameters vp3 = new DsaValidationParameters(new byte[24], 1024);

            doTest(vp1, vp1, vp3);
            doTest(vp1, vp2, vp3);

            byte[] bytes = new byte[20];
            bytes[0] = 1;

            vp3 = new DsaValidationParameters(bytes, 1024);

            doTest(vp1, vp2, vp3);

            vp3 = new DsaValidationParameters(new byte[20], 2048);

            doTest(vp1, vp2, vp3);
        }
Esempio n. 41
0
        public void TestGost3410()
        {
            IBigInteger a = BigInteger.ValueOf(1), b = BigInteger.ValueOf(2), c = BigInteger.ValueOf(3);

            Gost3410Parameters g1 = new Gost3410Parameters(a, b, c);
            Gost3410Parameters g2 = new Gost3410Parameters(a, b, c);
            Gost3410Parameters g3 = new Gost3410Parameters(a, c, c);

            doTest(g1, g2, g3);

            Gost3410ValidationParameters v1 = new Gost3410ValidationParameters(100, 1);
            Gost3410ValidationParameters v2 = new Gost3410ValidationParameters(100, 1);
            Gost3410ValidationParameters v3 = new Gost3410ValidationParameters(101, 1);

            doTest(v1, v2, v3);

            v3 = new Gost3410ValidationParameters(100, 2);

            doTest(v1, v2, v3);

            v1 = new Gost3410ValidationParameters(100L, 1L);
            v2 = new Gost3410ValidationParameters(100L, 1L);
            v3 = new Gost3410ValidationParameters(101L, 1L);

            doTest(v1, v2, v3);

            v3 = new Gost3410ValidationParameters(100L, 2L);

            doTest(v1, v2, v3);
        }
        /**
        * D.3.2 pg 101
        * @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger)
        */
        public ECPoint Multiply(ECPoint p, IBigInteger k, IPreCompInfo preCompInfo)
        {
            // TODO Probably should try to add this
            // IBigInteger e = k.Mod(n); // n == order of p
            IBigInteger e = k;
            IBigInteger h = e.Multiply(BigInteger.Three);

            ECPoint neg = p.Negate();
            ECPoint R = p;

            for (int i = h.BitLength - 2; i > 0; --i)
            {
                R = R.Twice();

                bool hBit = h.TestBit(i);
                bool eBit = e.TestBit(i);

                if (hBit != eBit)
                {
                    R = R.Add(hBit ? p : neg);
                }
            }

            return R;
        }
Esempio n. 43
0
        public ECPrivateKeyStructure(
            IBigInteger key,
            DerBitString publicKey,
            Asn1Encodable parameters)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerInteger(1),
                new DerOctetString(key.ToByteArrayUnsigned()));

            if (parameters != null)
            {
                v.Add(new DerTaggedObject(true, 0, parameters));
            }

            if (publicKey != null)
            {
                v.Add(new DerTaggedObject(true, 1, publicKey));
            }

            this.seq = new DerSequence(v);
        }
        public RsaKeyParameters(
            bool isPrivate,
            IBigInteger modulus,
            IBigInteger exponent)
            : base(isPrivate)
        {
            if (modulus == null)
            {
                throw new ArgumentNullException("modulus");
            }
            if (exponent == null)
            {
                throw new ArgumentNullException("exponent");
            }
            if (modulus.SignValue <= 0)
            {
                throw new ArgumentException(@"Not a valid RSA modulus", "modulus");
            }
            if (exponent.SignValue <= 0)
            {
                throw new ArgumentException(@"Not a valid RSA exponent", "exponent");
            }

            this.modulus  = modulus;
            this.exponent = exponent;
        }
Esempio n. 45
0
        /**
         * return true if the value r and s represent a DSA signature for
         * the passed in message for standard DSA the message should be a
         * SHA-1 hash of the real message to be verified.
         */
        public bool VerifySignature(byte[] message, IBigInteger r, IBigInteger s)
        {
            var parameters = _key.Parameters;
            var q          = parameters.Q;
            var m          = CalculateE(q, message);

            if (r.SignValue <= 0 || q.CompareTo(r) <= 0)
            {
                return(false);
            }

            if (s.SignValue <= 0 || q.CompareTo(s) <= 0)
            {
                return(false);
            }

            var w = s.ModInverse(q);

            var u1 = m.Multiply(w).Mod(q);
            var u2 = r.Multiply(w).Mod(q);

            var p = parameters.P;

            u1 = parameters.G.ModPow(u1, p);
            u2 = ((DsaPublicKeyParameters)_key).Y.ModPow(u2, p);

            var v = u1.Multiply(u2).Mod(p).Mod(q);

            return(v.Equals(r));
        }
 public ElGamalParameter(
     IBigInteger	p,
     IBigInteger	g)
 {
     this.p = new DerInteger(p);
     this.g = new DerInteger(g);
 }
        /// <summary>
        /// Creates a ECDH public key parameters from the given encoded point.
        /// </summary>
        /// <param name="encodedPoint">The encoded point.</param>
        /// <param name="publicKeyParamSet">The public key param set.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm.</param>
        /// <returns></returns>
        public static ECDHPublicKeyParameters Create(IBigInteger encodedPoint, DerObjectIdentifier publicKeyParamSet, 
            HashAlgorithmTag hashAlgorithm, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm)
        {
            var curve = ECKeyPairGenerator.FindECCurveByOid(publicKeyParamSet);
            var point = curve.Curve.DecodePoint(encodedPoint.ToByteArrayUnsigned());

            return new ECDHPublicKeyParameters(point, publicKeyParamSet, hashAlgorithm, symmetricKeyAlgorithm);
        }
        public ElGamalPublicKeyParameters(IBigInteger y, ElGamalParameters parameters)
            : base(false, parameters)
        {
            if (y == null)
                throw new ArgumentNullException("y");

            _y = y;
        }
        /**
         * Generates client's credentials given the client's salt, identity and password
         * @param salt The salt used in the client's verifier.
         * @param identity The user's identity (eg. username)
         * @param password The user's password
         * @return Client's public value to send to server
         */
        public virtual IBigInteger GenerateClientCredentials(byte[] salt, byte[] identity, byte[] password)
        {
            this.x = Srp6Utilities.CalculateX(digest, N, salt, identity, password);
            this.privA = SelectPrivateValue();
            this.pubA = g.ModPow(privA, N);

            return pubA;
        }
        public DerInteger(
            IBigInteger value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            bytes = value.ToByteArray();
        }
        /**
        * Constructor for <code>SimpleBigDecimal</code>. The value of the
        * constructed <code>SimpleBigDecimal</code> Equals <code>bigInt /
        * 2<sup>scale</sup></code>.
        * @param bigInt The <code>bigInt</code> value parameter.
        * @param scale The scale of the constructed <code>SimpleBigDecimal</code>.
        */
        public SimpleBigDecimal(IBigInteger bigInt, int scale)
        {
            if (scale < 0)
                throw new ArgumentException("scale may not be negative");

            this.bigInt = bigInt;
            this.scale = scale;
        }
        public static IBigInteger GeneratePrivateValue(IDigest digest, IBigInteger N, IBigInteger g, SecureRandom random)
        {
            int minBits = System.Math.Min(256, N.BitLength / 2);
            IBigInteger min = BigInteger.One.ShiftLeft(minBits - 1);
            IBigInteger max = N.Subtract(BigInteger.One);

            return BigIntegers.CreateRandomInRange(min, max, random);
        }
        public ECPrivateKeyParameters(string algorithm, IBigInteger d, ECDomainParameters parameters)
            : base(algorithm, true, parameters)
        {
            if (d == null)
                throw new ArgumentNullException("d");

            _d = d;
        }
        public ECPrivateKeyParameters(string algorithm, IBigInteger d, DerObjectIdentifier publicKeyParamSet)
            : base(algorithm, true, publicKeyParamSet)
        {
            if (d == null)
                throw new ArgumentNullException("d");

            _d = d;
        }
        /**
         * Generates client's verification message given the server's credentials
         * @param serverB The server's credentials
         * @return Client's verification message for the server
         * @throws CryptoException If server's credentials are invalid
         */
        public virtual IBigInteger CalculateSecret(IBigInteger serverB)
        {
            this.B = Srp6Utilities.ValidatePublicValue(N, serverB);
            this.u = Srp6Utilities.CalculateU(digest, N, pubA, B);
            this.S = CalculateS();

            return S;
        }
        public ECPrivateKeyParameters(IBigInteger d, DerObjectIdentifier publicKeyParamSet)
            : base("ECGOST3410", true, publicKeyParamSet)
        {
            if (d == null)
                throw new ArgumentNullException("d");

            _d = d;
        }
        /**
         * Processes the client's credentials. If valid the shared secret is generated and returned.
         * @param clientA The client's credentials
         * @return A shared secret BigInteger
         * @throws CryptoException If client's credentials are invalid
         */
        public virtual IBigInteger CalculateSecret(IBigInteger clientA)
        {
            this.A = Srp6Utilities.ValidatePublicValue(N, clientA);
            this.u = Srp6Utilities.CalculateU(digest, N, A, pubB);
            this.S = CalculateS();

            return S;
        }
        public DHParameters(
            IBigInteger p,
            IBigInteger g,
            IBigInteger q,
			int			l)
            : this(p, g, q, GetDefaultMParam(l), l, null, null)
        {
        }
        /**
         * Generates the server's credentials that are to be sent to the client.
         * @return The server's public value to the client
         */
        public virtual IBigInteger GenerateServerCredentials()
        {
            IBigInteger k = Srp6Utilities.CalculateK(digest, N, g);
            this.privB = SelectPrivateValue();
            this.pubB = k.Multiply(v).Mod(N).Add(g.ModPow(privB, N)).Mod(N);

            return pubB;
        }
 public X9ECParameters(
     ECCurve		curve,
     ECPoint		g,
     IBigInteger n,
     IBigInteger h)
     : this(curve, g, n, h, null)
 {
 }