示例#1
0
        /**
         * FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test
         *
         * Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases.
         *
         * @param candidate
         *            the {@link BigInteger} instance to test for primality.
         * @param random
         *            the source of randomness to use to choose bases.
         * @param iterations
         *            the number of randomly-chosen bases to perform the test for.
         * @return <code>false</code> if any witness to compositeness is found amongst the chosen bases
         *         (so <code>candidate</code> is definitely NOT prime), or else <code>true</code>
         *         (indicating primality with some probability dependent on the number of iterations
         *         that were performed).
         */
        public static bool IsMRProbablePrime(BigInteger candidate, SecureRandom random, int iterations)
        {
            CheckCandidate(candidate, "candidate");

            if (random == null)
            {
                throw new ArgumentException("cannot be null", "random");
            }
            if (iterations < 1)
            {
                throw new ArgumentException("must be > 0", "iterations");
            }

            if (candidate.BitLength == 2)
            {
                return(true);
            }
            if (!candidate.TestBit(0))
            {
                return(false);
            }

            BigInteger w       = candidate;
            BigInteger wSubOne = candidate.Subtract(One);
            BigInteger wSubTwo = candidate.Subtract(Two);

            int        a = wSubOne.GetLowestSetBit();
            BigInteger m = wSubOne.ShiftRight(a);

            for (int i = 0; i < iterations; ++i)
            {
                BigInteger b = BigIntegers.CreateRandomInRange(Two, wSubTwo, random);

                if (!ImplMRProbablePrimeToBase(w, wSubOne, m, a, b))
                {
                    return(false);
                }
            }

            return(true);
        }
示例#2
0
        private void ImplSqrtTest(ECCurve c)
        {
            if (ECAlgorithms.IsFpCurve(c))
            {
                BigInteger p                = c.Field.Characteristic;
                BigInteger pMinusOne        = p.Subtract(BigInteger.One);
                BigInteger legendreExponent = p.ShiftRight(1);

                int count = 0;
                while (count < 10)
                {
                    BigInteger nonSquare = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusOne, secRand);
                    if (!nonSquare.ModPow(legendreExponent, p).Equals(BigInteger.One))
                    {
                        ECFieldElement root = c.FromBigInteger(nonSquare).Sqrt();
                        Assert.IsNull(root);
                        ++count;
                    }
                }
            }
        }
示例#3
0
        public bool Read(Stream stream)
        {
            if (stream.Length - stream.Position < 74)
            {
                return(false);
            }

            var aBytes  = new byte[32];
            var m1Bytes = new byte[20];

            stream.Read(aBytes, 0, aBytes.Length);
            stream.Read(m1Bytes, 0, m1Bytes.Length);

            // skip remaining stuff
            stream.Seek(22, SeekOrigin.Current);

            A  = BigIntegers.FromUnsignedByteArray(aBytes);
            M1 = BigIntegers.FromUnsignedByteArray(m1Bytes);

            return(true);
        }
示例#4
0
        public static void CreateSelfSignedCertificate(Certificate certInfo,
                                                       string certificateFile, string keyFile)
        {
            var rndGen = new CryptoApiRandomGenerator();
            var rnd    = new SecureRandom(rndGen);

            var keyGenParams = new KeyGenerationParameters(rnd, 2048);
            var keyPairGen   = new RsaKeyPairGenerator();

            // var keyGenParams = new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, rnd);
            // var keyPairGen = new ECKeyPairGenerator();
            keyPairGen.Init(keyGenParams);
            var keyPair = keyPairGen.GenerateKeyPair();

            var certGen  = new X509V3CertificateGenerator();
            var serialNo = BigIntegers.CreateRandomInRange(
                BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), rnd);

            certGen.SetSerialNumber(serialNo);
            certGen.SetSubjectDN(certInfo.X509Name());
            certGen.SetIssuerDN(certInfo.X509Name());
            var now = DateTime.UtcNow.Date;

            certGen.SetNotBefore(now);
            certGen.SetNotAfter(now.AddDays(certInfo.ValidDays));
            certGen.SetPublicKey(keyPair.Public);

            var sigFac = new Asn1SignatureFactory("SHA256WithRSA", keyPair.Private, rnd);
            var cert   = certGen.Generate(sigFac);

            using (var w = new StreamWriter(certificateFile, false, Encoding.ASCII)) {
                var pemWriter = new PemWriter(w);
                pemWriter.WriteObject(cert);
            }
            using (var w = new StreamWriter(keyFile, false, Encoding.ASCII))
            {
                var pemWriter = new PemWriter(w);
                pemWriter.WriteObject(keyPair);
            }
        }
示例#5
0
        public virtual byte[] ProcessBlock(byte[] inBuf, int inOff, int inLen)
        {
            //IL_000d: Unknown result type (might be due to invalid IL or missing references)
            //IL_00cb: Unknown result type (might be due to invalid IL or missing references)
            if (key == null)
            {
                throw new InvalidOperationException("RSA engine not initialised");
            }
            BigInteger bigInteger = core.ConvertInput(inBuf, inOff, inLen);
            BigInteger bigInteger4;

            if (key is RsaPrivateCrtKeyParameters)
            {
                RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)key;
                BigInteger publicExponent = rsaPrivateCrtKeyParameters.PublicExponent;
                if (publicExponent != null)
                {
                    BigInteger modulus     = rsaPrivateCrtKeyParameters.Modulus;
                    BigInteger bigInteger2 = BigIntegers.CreateRandomInRange(BigInteger.One, modulus.Subtract(BigInteger.One), random);
                    BigInteger input       = bigInteger2.ModPow(publicExponent, modulus).Multiply(bigInteger).Mod(modulus);
                    BigInteger bigInteger3 = core.ProcessBlock(input);
                    BigInteger val         = bigInteger2.ModInverse(modulus);
                    bigInteger4 = bigInteger3.Multiply(val).Mod(modulus);
                    if (!bigInteger.Equals(bigInteger4.ModPow(publicExponent, modulus)))
                    {
                        throw new InvalidOperationException("RSA engine faulty decryption/signing detected");
                    }
                }
                else
                {
                    bigInteger4 = core.ProcessBlock(bigInteger);
                }
            }
            else
            {
                bigInteger4 = core.ProcessBlock(bigInteger);
            }
            return(core.ConvertOutput(bigInteger4));
        }
示例#6
0
        public static AsymmetricKeyParameter CreatePrivateKeyResource(string subjectName = "CN=root")
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = subjectDn;

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(70);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            return(subjectKeyPair.Private);
        }
示例#7
0
        public virtual byte[] ProcessBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            agree.Init(privParam);

            BigInteger z = agree.CalculateAgreement(pubParam);

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

            try
            {
                return(forEncryption
                    ?   EncryptBlock(input, inOff, inLen, zBytes)
                    :   DecryptBlock(input, inOff, inLen, zBytes));
            }
            finally
            {
                Array.Clear(zBytes, 0, zBytes.Length);
            }
        }
        public static byte[] GetSignedCertificate(AlgParSet parameters, Subj subj)
        {
            X509Certificate root = new X509CertificateParser().ReadCertificate(GetRootCertificate());
            Cert            data = CreateDatabaseInfoFromCertificate(root);

            var    keys   = GenerateKeyPair(parameters);
            string serial = string.Empty;

            do
            {
                serial = BigIntegers.CreateRandomBigInteger(512, new SecureRandom()).ToString();
            }while (DatabaseInstance.GetInstance().Certs.FirstOrDefault(elm => elm.SerialNumber_Cert == serial) != null);

            Cert certificate = new Cert
            {
                Ver_Cert     = DatabaseInstance.GetInstance().Vers.FirstOrDefault(),
                SignAlg_Cert = new SignAlg
                {
                    AlgParSet_SignAlg  = parameters,
                    PrivateKey_SignAlg = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private).ToAsn1Object().GetEncoded(),
                    PublicKey_SignAlg  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public).ToAsn1Object().GetEncoded()
                },
                Issuer_Cert           = data.Issuer_Cert,
                Subj_Cert             = subj,
                SerialNumber_Cert     = serial,
                ValidFrom_Cert        = DateTime.Now,
                ValidBy_Cert          = DateTimeOffset.Now.AddYears(5).UtcDateTime,
                SignSerialNumber_Cert = data.SerialNumber_Cert
            };

            var cert = CreateCertificateFromDatabaseInfo(certificate);

            certificate.SignValue_Cert = string.Join("", BitConverter.ToString(cert.GetSignature()).Split('-'));

            DatabaseInstance.GetInstance().Certs.Add(certificate);
            DatabaseInstance.GetInstance().SaveChanges();

            return(cert.GetEncoded());
        }
        // 5.3 pg 28

        /**
         * Generate a signature for the given message using the key we were
         * initialised with. For conventional DSA the message should be a SHA-1
         * hash of the message of interest.
         *
         * @param message the message that will be verified later.
         */
        public virtual BigInteger[] GenerateSignature(byte[] message)
        {
            ECDomainParameters ec = key.Parameters;
            BigInteger         n  = ec.N;
            BigInteger         e  = CalculateE(n, message);
            BigInteger         d  = ((ECPrivateKeyParameters)key).D;

            if (kCalculator.IsDeterministic)
            {
                kCalculator.Init(n, d, message);
            }
            else
            {
                kCalculator.Init(n, random);
            }

            BigInteger r, s;

            ECMultiplier basePointMultiplier = CreateBasePointMultiplier();

            // 5.3.2
            do // Generate s
            {
                BigInteger k;
                do // Generate r
                {
                    k = kCalculator.NextK();

                    ECPoint p = basePointMultiplier.Multiply(ec.G, k).Normalize();

                    // 5.3.3
                    r = p.AffineXCoord.ToBigInteger().Mod(n);
                }while (r.SignValue == 0);

                s = BigIntegers.ModOddInverse(n, k).Multiply(e.Add(d.Multiply(r))).Mod(n);
            }while (s.SignValue == 0);

            return(new BigInteger[] { r, s });
        }
示例#10
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);
        }
示例#11
0
        public virtual byte[] ProcessBlock(byte[] inBuf, int inOff, int inLen)
        {
            BigInteger integer2;

            if (this.key == null)
            {
                throw new InvalidOperationException("RSA engine not initialised");
            }
            BigInteger val = this.core.ConvertInput(inBuf, inOff, inLen);

            if (this.key is RsaPrivateCrtKeyParameters)
            {
                RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)this.key;
                BigInteger publicExponent      = key.PublicExponent;
                if (publicExponent != null)
                {
                    BigInteger modulus  = key.Modulus;
                    BigInteger integer5 = BigIntegers.CreateRandomInRange(BigInteger.One, modulus.Subtract(BigInteger.One), this.random);
                    BigInteger input    = integer5.ModPow(publicExponent, modulus).Multiply(val).Mod(modulus);
                    BigInteger integer7 = this.core.ProcessBlock(input);
                    BigInteger integer8 = integer5.ModInverse(modulus);
                    integer2 = integer7.Multiply(integer8).Mod(modulus);
                    if (!val.Equals(integer2.ModPow(publicExponent, modulus)))
                    {
                        throw new InvalidOperationException("RSA engine faulty decryption/signing detected");
                    }
                }
                else
                {
                    integer2 = this.core.ProcessBlock(val);
                }
            }
            else
            {
                integer2 = this.core.ProcessBlock(val);
            }
            return(this.core.ConvertOutput(integer2));
        }
        public virtual BigInteger NextK()
        {
            byte[] t = new byte[BigIntegers.GetUnsignedByteLength(n)];

            for (;;)
            {
                int tOff = 0;

                while (tOff < t.Length)
                {
                    hMac.BlockUpdate(V, 0, V.Length);

                    hMac.DoFinal(V, 0);

                    int len = System.Math.Min(t.Length - tOff, V.Length);
                    Array.Copy(V, 0, t, tOff, len);
                    tOff += len;
                }

                BigInteger k = BitsToInt(t);

                if (k.SignValue > 0 && k.CompareTo(n) < 0)
                {
                    return(k);
                }

                hMac.BlockUpdate(V, 0, V.Length);
                hMac.Update((byte)0x00);

                hMac.DoFinal(K, 0);

                hMac.Init(new KeyParameter(K));

                hMac.BlockUpdate(V, 0, V.Length);

                hMac.DoFinal(V, 0);
            }
        }
示例#13
0
        public X509Certificate2 MakeCertificate(string password, string issuedToDomainName, string friendlyName, int validMonths)
        {
            _certificateGenerator.Reset();
            _certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), _random);

            _certificateGenerator.SetSerialNumber(serialNumber);

            _certificateGenerator.SetSubjectDN(new X509Name(issuedToDomainName));
            _certificateGenerator.SetIssuerDN(_issuer);

            var utcNow = DateTime.UtcNow.AddDays(-1);

            _certificateGenerator.SetNotBefore(utcNow);
            _certificateGenerator.SetNotAfter(utcNow.AddMonths(validMonths));
            var keyGenerationParameters = new KeyGenerationParameters(_random, _strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            _certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            var issuerKeyPair = subjectKeyPair;
            var certificate   = _certificateGenerator.Generate(issuerKeyPair.Private, _random);

            var store            = new Pkcs12Store();
            var certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            using (var stream = new MemoryStream())
            {
                store.Save(stream, password.ToCharArray(), _random);
                return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
            }
        }
示例#14
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));
        }
    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);
    }
        internal BigInteger CalculatePrivate(DHParameters dhParams, SecureRandom random)
        {
            int l = dhParams.L;

            if (l != 0)
            {
                int        num = l >> 2;
                BigInteger bigInteger;
                do
                {
                    bigInteger = new BigInteger(l, random).SetBit(l - 1);
                }while (WNafUtilities.GetNafWeight(bigInteger) < num);
                return(bigInteger);
            }
            BigInteger min = BigInteger.Two;
            int        m   = dhParams.M;

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

            if (bigInteger2 == null)
            {
                bigInteger2 = dhParams.P;
            }
            BigInteger bigInteger3 = bigInteger2.Subtract(BigInteger.Two);
            int        num2        = bigInteger3.BitLength >> 2;
            BigInteger bigInteger4;

            do
            {
                bigInteger4 = BigIntegers.CreateRandomInRange(min, bigInteger3, random);
            }while (WNafUtilities.GetNafWeight(bigInteger4) < num2);
            return(bigInteger4);
        }
示例#17
0
        internal BigInteger CalculatePrivate(DHParameters dhParams, SecureRandom random)
        {
            BigInteger integer5;
            int        l = dhParams.L;

            if (l != 0)
            {
                BigInteger integer;
                int        num2 = l >> 2;
                do
                {
                    integer = new BigInteger(l, random).SetBit(l - 1);
                }while (WNafUtilities.GetNafWeight(integer) < num2);
                return(integer);
            }
            BigInteger two = BigInteger.Two;
            int        m   = dhParams.M;

            if (m != 0)
            {
                two = BigInteger.One.ShiftLeft(m - 1);
            }
            BigInteger q = dhParams.Q;

            if (q == null)
            {
                q = dhParams.P;
            }
            BigInteger max  = q.Subtract(BigInteger.Two);
            int        num4 = max.BitLength >> 2;

            do
            {
                integer5 = BigIntegers.CreateRandomInRange(two, max, random);
            }while (WNafUtilities.GetNafWeight(integer5) < num4);
            return(integer5);
        }
示例#18
0
        /// <summary>
        /// Creates a new X509 certificate and returns its data in PEM format.
        ///
        /// <see cref="PatchingCertificatePem"/> is generated using this method.
        /// </summary>
        public string GenerateNewCertificatePem()
        {
            var randomGenerator      = new CryptoApiRandomGenerator();
            var random               = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber         = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // TODO: Figure out ISignatureFactory to avoid these deprecated methods
#pragma warning disable 618
            certificateGenerator.SetSignatureAlgorithm("SHA256WithRSA");
#pragma warning restore 618
            var subjectDn = new X509Name("cn=Unknown");
            var issuerDn  = subjectDn;
            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date.AddYears(-10));
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(50));
            var keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            var keyPairGenerator        = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // TODO: Figure out ISignatureFactory to avoid these deprecated methods
#pragma warning disable 618
            X509Certificate cert = certificateGenerator.Generate(subjectKeyPair.Private);
#pragma warning restore 618

            using var writer = new StringWriter();
            var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(writer);

            pemWriter.WriteObject(new PemObject("CERTIFICATE", cert.GetEncoded()));
            pemWriter.WriteObject(subjectKeyPair.Private);
            return(writer.ToString());
        }
示例#19
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());
        }
示例#20
0
        public static bool IsMRProbablePrime(BigInteger candidate, SecureRandom random, int iterations)
        {
            //IL_0018: Unknown result type (might be due to invalid IL or missing references)
            //IL_002c: Unknown result type (might be due to invalid IL or missing references)
            CheckCandidate(candidate, "candidate");
            if (random == null)
            {
                throw new ArgumentException("cannot be null", "random");
            }
            if (iterations < 1)
            {
                throw new ArgumentException("must be > 0", "iterations");
            }
            if (candidate.BitLength == 2)
            {
                return(true);
            }
            if (!candidate.TestBit(0))
            {
                return(false);
            }
            BigInteger bigInteger   = candidate.Subtract(One);
            BigInteger max          = candidate.Subtract(Two);
            int        lowestSetBit = bigInteger.GetLowestSetBit();
            BigInteger m            = bigInteger.ShiftRight(lowestSetBit);

            for (int i = 0; i < iterations; i++)
            {
                BigInteger b = BigIntegers.CreateRandomInRange(Two, max, random);
                if (!ImplMRProbablePrimeToBase(candidate, bigInteger, m, lowestSetBit, b))
                {
                    return(false);
                }
            }
            return(true);
        }
示例#21
0
        public virtual bool VerifySignature(byte[] signature)
        {
            try
            {
                block = cipher.ProcessBlock(signature, 0, signature.Length);
            }
            catch (Exception)
            {
                return(false);

                IL_0024 :;
            }
            BigInteger bigInteger = new BigInteger(block);
            BigInteger n;

            if ((bigInteger.IntValue & 0xF) == 12)
            {
                n = bigInteger;
            }
            else
            {
                bigInteger = kParam.Modulus.Subtract(bigInteger);
                if ((bigInteger.IntValue & 0xF) != 12)
                {
                    return(false);
                }
                n = bigInteger;
            }
            CreateSignatureBlock();
            byte[] b      = BigIntegers.AsUnsignedByteArray(block.Length, n);
            bool   result = Arrays.ConstantTimeAreEqual(block, b);

            ClearBlock(block);
            ClearBlock(b);
            return(result);
        }
        public static (AsymmetricCipherKeyPair, X509Certificate) GenerateSelfSigned()
        {
            var startDate  = DateTime.Now;
            var expiryDate = DateTime.Now.AddYears(10);

            var serialNumber = BigIntegers.CreateRandomInRange(
                BigInteger.ValueOf(2).Pow(63),
                BigInteger.ValueOf(2).Pow(64),
                new SecureRandom()
                );

            var oid    = ECGost3410NamedCurves.GetOid("Tc26-Gost-3410-12-256-paramSetA");
            var param  = new ECKeyGenerationParameters(oid, new SecureRandom());
            var engine = new ECKeyPairGenerator();

            engine.Init(param);

            var keyPair = engine.GenerateKeyPair();

            var certGen = new X509V1CertificateGenerator();

            var dnName = new X509Name("CN=Test CA Certificate");

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(dnName);
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(expiryDate);
            certGen.SetSubjectDN(dnName);
            certGen.SetPublicKey(keyPair.Public);

            var signer = new GostSignerFactory(keyPair.Private);

            var certificate = certGen.Generate(signer);

            return(keyPair, certificate);
        }
示例#23
0
        private static byte[] GenerateSelfSignedCertificate(string subjectName)
        {
            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // Subject Public Key
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, KeySize);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random));
            certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            certificateGenerator.SetIssuerDN(new X509Name(subjectName));
            certificateGenerator.SetSubjectDN(new X509Name(subjectName));
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date);
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            Org.BouncyCastle.X509.X509Certificate cert = certificateGenerator.Generate(subjectKeyPair.Private, random);
            Pkcs12Store store = new Pkcs12StoreBuilder().SetUseDerEncoding(true).Build();

            store.SetKeyEntry("unused", new AsymmetricKeyEntry(subjectKeyPair.Private), new X509CertificateEntry[] { new X509CertificateEntry(cert) });
            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, new char[0], random);
                return(stream.ToArray());
            }
        }
示例#24
0
        /// <summary>
        /// Creates a self signed application instance certificate.
        /// </summary>
        /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
        /// <param name="storePath">The store path (syntax depends on storeType).</param>
        /// <param name="password">The password to use to protect the certificate.</param>
        /// <param name="applicationUri">The application uri (created if not specified).</param>
        /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
        /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
        /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
        /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
        /// <param name="hashSizeInBits">The hash size in bits.</param>
        /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
        /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
        /// <returns>The certificate with a private key.</returns>
        public static X509Certificate2 CreateCertificate(
            string storeType,
            string storePath,
            string password,
            string applicationUri,
            string applicationName,
            string subjectName,
            IList <String> domainNames,
            ushort keySize,
            DateTime startTime,
            ushort lifetimeInMonths,
            ushort hashSizeInBits,
            bool isCA,
            X509Certificate2 issuerCAKeyCert)
        {
            if (!String.IsNullOrEmpty(storeType) &&
                storeType != CertificateStoreType.Directory)
            {
                throw new NotSupportedException("Cannot create a certificate for a non directory store.");
            }

            if (issuerCAKeyCert != null)
            {
                if (!issuerCAKeyCert.HasPrivateKey)
                {
                    throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
                }

                throw new NotSupportedException("Signing with an issuer CA certificate is currently unsupported.");
            }

            // set default values.
            SetSuitableDefaults(
                ref applicationUri,
                ref applicationName,
                ref subjectName,
                ref domainNames,
                ref keySize,
                ref lifetimeInMonths,
                isCA);

            // cert generators
            SecureRandom random           = new SecureRandom();
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            cg.SetSerialNumber(serialNumber);

            // build name attributes
            var nameOids = new ArrayList();

            nameOids.Add(X509Name.DC);
            nameOids.Add(X509Name.CN);

            var nameValues = new ArrayList();

            nameValues.Add(domainNames[0]);
            nameValues.Add(applicationName);

            // self signed
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // Private/Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier
            var issuerKeyPair      = subjectKeyPair;
            var issuerSerialNumber = serialNumber;

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])
                }));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", subjectKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store            pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.Directory)
                {
                    using (store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        store.Add(certificate);
                        store.Close();
                    }
                }
            }

            // note: this cert has a private key!
            return(certificate);
        }
示例#25
0
        public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
//            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), serialNumber));

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            var x509        = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            // Add CA certificate to Root store
            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)issuerKeyPair.Private;

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            store           = new X509Store("PrivateCertStore", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            return(issuerKeyPair.Private);
        }
示例#26
0
        public async Task <BigInteger> Authenticate(AuthSessionRequest authRequest)
        {
            if (String.IsNullOrEmpty(authRequest.Identity))
            {
                throw new ArgumentNullException(nameof(authRequest.Identity));
            }

            if (seed == 0)
            {
                await Send(new AuthSessionResponse()
                {
                    Response = AuthResponseCode.Failed
                });

                throw new AuthenticationFailedException("cannot authenticate with a server seed of 0");
            }

            var account = GrainFactory.GetGrain <IAccount>(authRequest.Identity);

            if (await account.Exists())
            {
                try
                {
                    var sessionKey = await account.GetSessionKey();

                    using (var sha1 = new Digester(SHA1.Create()))
                    {
                        var serverDigest = BigIntegers.FromUnsignedByteArray(
                            sha1.CalculateDigest(new byte[][]
                        {
                            Encoding.UTF8.GetBytes(authRequest.Identity),
                            new byte[4],
                            BitConverter.GetBytes(authRequest.ClientSeed),
                            BitConverter.GetBytes(seed),
                            sessionKey.ToByteArray(40),
                        })
                            );

                        if (serverDigest == authRequest.ClientDigest)
                        {
                            GetLogger().Info($"{authRequest.Identity} successfully authenticated to {ShardName} {nameof(ShardSession)} {this.GetPrimaryKey()}");

                            // we can't just Send the Success response here, since the client expects the packet cipher to be initialized at this point
                            AuthenticatedIdentity = authRequest.Identity;
                            return(sessionKey);
                        }
                        else
                        {
                            await Send(new AuthSessionResponse()
                            {
                                Response = AuthResponseCode.Failed
                            });

                            throw new AuthenticationFailedException($"account {authRequest.Identity} failed authentication proof");
                        }
                    }
                }
                catch (AccountDoesNotExistException)
                {
                    await Send(new AuthSessionResponse()
                    {
                        Response = AuthResponseCode.UnknownAccount
                    });

                    throw new AuthenticationFailedException($"account {authRequest.Identity} does not exist");
                }
                catch (AccountStateException)
                {
                    GetLogger().Warn($"received {nameof(AuthSessionRequest)} with unauthenticated identity {authRequest.Identity}");
                    await Send(new AuthSessionResponse()
                    {
                        Response = AuthResponseCode.Failed
                    });

                    throw new AuthenticationFailedException($"account {authRequest.Identity} is not authenticated");
                }
            }
            else
            {
                await Send(new AuthSessionResponse()
                {
                    Response = AuthResponseCode.UnknownAccount
                });

                throw new AuthenticationFailedException($"account {authRequest.Identity} does not exist");
            }
        }
示例#27
0
        public static X509Certificate2 IssueCertificate(
            string basename,
            string password,
            DistinguishedName dn,
            CertificateType certtype,
            DateTime notBefore,
            DateTime notAfter)
        {
            var certificateGenerator = new X509V3CertificateGenerator();
            var privateOutputPath    = "";
            var publicOutputPath     = "";

            /* Prepare output directories  */
            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
                publicOutputPath  = AuthorityPublicCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
                publicOutputPath  = ServerPublicCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
                publicOutputPath  = UserPublicCertificatesPath;
            }

            /* Certificate Asymmetric Keys */
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            /* Certificate Serial Number */
            BigInteger serialNumber =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            /* Certificate Date Constrains */
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            /* Certificate Issuer and Subject DN */
            string issuerName = IssuerDN.ToString();

            if (certtype == CertificateType.AuthorityCertificate)
            {
                /* A Certification Authority is a self signed certificate */
                issuerName = dn.ToString();
            }

            certificateGenerator.SetSubjectDN(new X509Name(dn.ToString()));
            certificateGenerator.SetIssuerDN(new X509Name(issuerName));

            /* Certificate Alternative Names */
            if (dn.AlternativeNames != null && dn.AlternativeNames.Any())
            {
                var subjectAlternativeNamesExtension =
                    new DerSequence(
                        dn.AlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                        .ToArray <Asn1Encodable> ());

                certificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }

            /* Certificate Keys Usage  */
            var keyUsageFlags = KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment |
                                KeyUsage.DataEncipherment | KeyUsage.DigitalSignature;

            if (certtype == CertificateType.AuthorityCertificate || certtype == CertificateType.ServerCertificate)
            {
                keyUsageFlags |= KeyUsage.CrlSign | KeyUsage.NonRepudiation;
            }

            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsageFlags));

            /* Certificate Extended Key Usages */
            if (certtype != CertificateType.AuthorityCertificate)
            {
                KeyPurposeID[] extendedUsages = null;

                if (certtype == CertificateType.ServerCertificate)
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPServerAuth,
                    };
                }
                else
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPClientAuth,
                        KeyPurposeID.IdKPEmailProtection,
                    };
                }

                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedUsages));
            }

            /* Certificate Authority Key Identifier */
            /* A Certification Authority is a self signed certificate */
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerKeyPair = DotNetUtilities.GetKeyPair(IssuerCertificate.PrivateKey);
            }

            var issuerPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public);
            var generalNames     = new GeneralNames(
                new GeneralName(new X509Name(issuerName)));

            /* A Certification Authority is a self signed certificate */
            BigInteger issuerSerialNumber = serialNumber;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerSerialNumber = new BigInteger(IssuerCertificate.GetSerialNumber());
            }

            var authorityKIExtension =
                new AuthorityKeyIdentifier(
                    issuerPKIFactory, generalNames, issuerSerialNumber);

            certificateGenerator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKIExtension);

            /* Certificate Subject Key Identifier */
            var subjectPKIFactory  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public);
            var subjectKIExtension = new SubjectKeyIdentifier(subjectPKIFactory);

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id, false, subjectKIExtension);

            /* Certificate Basic constrains */
            bool isCertificateAuthority = false;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                isCertificateAuthority = true;
            }

            var basicConstrains = new BasicConstraints(isCertificateAuthority);

            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, basicConstrains);

            /* Generate BouncyCastle Certificate */
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(
                "SHA512WITHRSA",
                issuerKeyPair.Private,
                random
                );

            /* Generate P12 Certificate Store and write to disk*/
            var store = new Pkcs12Store();

            var certificate      = certificateGenerator.Generate(signatureFactory);
            var certificateEntry = new X509CertificateEntry(certificate);
            var stream           = new MemoryStream();

            store.SetCertificateEntry(dn.ToString(), certificateEntry);
            store.SetKeyEntry(dn.ToString(), new AsymmetricKeyEntry(subjectKeyPair.Private), new [] { certificateEntry });
            store.Save(stream, password.ToCharArray(), random);

            File.WriteAllBytes(privateOutputPath + basename + ".p12", stream.ToArray());

            /* Convert to Microsoft X509Certificate2 and write to disk pfx and der files */
            var convertedCertificate =
                new X509Certificate2(stream.ToArray(),
                                     password,
                                     X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            File.WriteAllBytes(privateOutputPath + basename + ".pfx", convertedCertificate.Export(X509ContentType.Pfx, password));
            File.WriteAllBytes(publicOutputPath + basename + ".crt", convertedCertificate.Export(X509ContentType.Cert, password));

            return(convertedCertificate);
        }
示例#28
0
 public static void WriteECParameter(BigInteger x, Stream output)
 {
     TlsUtilities.WriteOpaque8(BigIntegers.AsUnsignedByteArray(x), output);
 }
示例#29
0
 public static byte[] SerializeECFieldElement(int fieldSize, BigInteger x)
 {
     return(BigIntegers.AsUnsignedByteArray((fieldSize + 7) / 8, x));
 }
示例#30
0
        /// <summary>	Generates a self signed certificate. </summary>
        /// <exception cref="PemException">	Thrown when a Pem error condition occurs. </exception>
        /// <param name="subjectName">      Name of the subject. </param>
        /// <param name="issuerName">       Name of the issuer. </param>
        /// <param name="issuerPrivKey">	The issuer priv key. </param>
        /// <param name="validTill">		The valid till Date/Time. </param>
        /// <param name="keyStrength">      (Optional) The key strength. </param>
        /// <returns>	The self signed certificate. </returns>
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName,
                                                                     AsymmetricKeyParameter issuerPrivKey, DateTime validTill, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = validTill;

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // selfsign certificate
            var signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerPrivKey);
            var certificate      = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded());

            var seq = (Asn1Sequence)info.ParsePrivateKey();

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1,
                rsa.Exponent2,
                rsa.Coefficient);

            x509.PrivateKey = ToDotNetKey(rsaparams);

            return(x509);
        }