public DsaKeyGenerationParameters( SecureRandom random, DsaParameters parameters) : base(random, parameters.P.BitLength - 1) { this.parameters = parameters; }
internal BigInteger CalculatePrivate( BigInteger p, SecureRandom random, int limit) { // // calculate the private key // BigInteger pSub2 = p.Subtract(BigInteger.Two); BigInteger x; if (limit == 0) { x = createInRange(pSub2, random); } else { do { // TODO Check this (should the generated numbers always be odd, // and length 'limit'?) x = new BigInteger(limit, 0, random); } while (x.SignValue == 0); } return x; }
public void Init( bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; if (forSigning) { if (parameters is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom) parameters; this.random = rParam.Random; parameters = rParam.Parameters; } else { this.random = new SecureRandom(); } if (!(parameters is ECPrivateKeyParameters)) throw new InvalidKeyException("EC private key required for signing"); this.key = (ECPrivateKeyParameters) parameters; } else { if (!(parameters is ECPublicKeyParameters)) throw new InvalidKeyException("EC public key required for verification"); this.key = (ECPublicKeyParameters) parameters; } }
/// <summary> /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use. /// </summary> /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param> /// <param name="random">The Secure Random you want to use.</param> /// <returns>An X509Certificate.</returns> public X509Certificate Generate( IAsymmetricKeyParameter privateKey, SecureRandom random) { TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate(); byte[] signature; try { signature = X509Utilities.GetSignatureForObject( sigOID, signatureAlgorithm, privateKey, random, tbsCert); } catch (Exception e) { // TODO // throw new ExtCertificateEncodingException("exception encoding TBS cert", e); throw new CertificateEncodingException("exception encoding TBS cert", e); } try { return GenerateJcaObject(tbsCert, signature); } catch (CertificateParsingException e) { // TODO // throw new ExtCertificateEncodingException("exception producing certificate object", e); throw new CertificateEncodingException("exception producing certificate object", e); } }
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; }
private static X509Certificate GenerateCertificate(Org.BouncyCastle.Security.SecureRandom random, string subjectName, AsymmetricCipherKeyPair subjectKeyPair, BigInteger subjectSerialNumber, string[] subjectAlternativeNames, string issuerName, AsymmetricCipherKeyPair issuerKeyPair, BigInteger issuerSerialNumber, bool isCertificateAuthority, KeyPurposeID[] usages, int expiresIn) { var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSerialNumber(subjectSerialNumber); // Set the signature algorithm. This is used to generate the thumbprint which is then signed // with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong. const string signatureAlgorithm = "SHA256WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); // Note: The subject can be omitted if you specify a subject alternative name (SAN). var subjectDN = new X509Name(subjectName); certificateGenerator.SetSubjectDN(subjectDN); // Our certificate needs valid from/to values. var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(expiresIn); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // The subject's public key goes in the certificate. certificateGenerator.SetPublicKey(subjectKeyPair.Public); certificateGenerator.AddAuthorityKeyIdentifier(issuerDN, issuerKeyPair, issuerSerialNumber); certificateGenerator.AddSubjectKeyIdentifier(subjectKeyPair); certificateGenerator.AddBasicConstraints(isCertificateAuthority); if (usages != null && usages.Any()) { certificateGenerator.AddExtendedKeyUsage(usages); } if (subjectAlternativeNames != null && subjectAlternativeNames.Any()) { certificateGenerator.AddSubjectAlternativeNames(subjectAlternativeNames); } // The certificate is signed with the issuer's private key. var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random); return(certificate); }
/** * Return a random BigInteger 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 BigInteger value in the range [min,max] */ public static BigInteger CreateRandomInRange( BigInteger min, BigInteger max, // TODO Should have been just Random class SecureRandom 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) { BigInteger 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 void Init( ICipherParameters parameters) { AsymmetricKeyParameter kParam; if (parameters is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)parameters; this.random = rParam.Random; kParam = (AsymmetricKeyParameter)rParam.Parameters; } else { this.random = new SecureRandom(); kParam = (AsymmetricKeyParameter)parameters; } if (!(kParam is DHPrivateKeyParameters)) { throw new ArgumentException("DHEngine expects DHPrivateKeyParameters"); } this.key = (DHPrivateKeyParameters)kParam; this.dhParams = key.Parameters; }
private void doWrapTest( int id, IBlockCipher engine, byte[] kek, byte[] iv, SecureRandom rand, byte[] inBytes, byte[] outBytes) { IWrapper wrapper = new Rfc3211WrapEngine(engine); wrapper.Init(true, new ParametersWithRandom( new ParametersWithIV(new KeyParameter(kek), iv), rand)); byte[] cText = wrapper.Wrap(inBytes, 0, inBytes.Length); if (!AreEqual(cText, outBytes)) { Fail("failed Wrap test " + id + " expected " + Hex.ToHexString(outBytes) + " got " + Hex.ToHexString(cText)); } wrapper.Init(false, new ParametersWithIV(new KeyParameter(kek), iv)); byte[] pText = wrapper.Unwrap(outBytes, 0, outBytes.Length); if (!AreEqual(pText, inBytes)) { Fail("rfailed Unwrap test " + id + " expected " + Hex.ToHexString(inBytes) + " got " + Hex.ToHexString(pText)); } }
public void Init( bool forSigning, ICipherParameters parameters) { if (forSigning) { if (parameters is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)parameters; this.random = rParam.Random; // this.key = (Gost3410PrivateKeyParameters)rParam.Parameters; parameters = rParam.Parameters; } else { this.random = new SecureRandom(); // this.key = (Gost3410PrivateKeyParameters)parameters; } if (!(parameters is Gost3410PrivateKeyParameters)) throw new InvalidKeyException("GOST3410 private key required for signing"); this.key = (Gost3410PrivateKeyParameters) parameters; } else { if (!(parameters is Gost3410PublicKeyParameters)) throw new InvalidKeyException("GOST3410 public key required for signing"); this.key = (Gost3410PublicKeyParameters) parameters; } }
/// <summary> /// Creates ECDSA from imported data /// </summary> /// <param name="type">0 or 1 (1 faster)</param> /// <param name="forSign">if created for signing, otherwise for verifying</param> /// <param name="import">Imporeted public or private key</param> public ECDSAWrapper(int type, bool forSign, byte[] import) { this.initCurveandParams(type); if (forSign) { try { //import - D (BigInteger) SecureRandom random = new SecureRandom(); BigInteger Drec = new BigInteger(import); ECPrivateKeyParameters ecPrivImported = new ECPrivateKeyParameters(Drec, this.parameters); ParametersWithRandom ecPrivImportedpwr = new ParametersWithRandom(ecPrivImported, random); this.ecdsa.Init(true, ecPrivImportedpwr); } catch (Exception ex) { throw new Exception("Error while creating ECDSAWrapper from import for signing", ex); } } else { try { //import - Q (ECPoint) ECPoint Qrec = this.ecCurve.DecodePoint(import); ECPublicKeyParameters recPub = new ECPublicKeyParameters(Qrec, this.parameters); this.ecdsa.Init(false, recPub); } catch (Exception ex) { throw new Exception("Error while creating ECDSAWrapperfom import for verifying", ex); } } }
static EcKey() { // All clients must agree on the curve to use by agreement. BitCoin uses secp256k1. var @params = SecNamedCurves.GetByName("secp256k1"); _ecParams = new ECDomainParameters(@params.Curve, @params.G, @params.N, @params.H); _secureRandom = new SecureRandom(); }
internal X931SecureRandom(SecureRandom randomSource, X931Rng drbg, bool predictionResistant) : base((IRandomGenerator)null) { this.mRandomSource = randomSource; this.mDrbg = drbg; this.mPredictionResistant = predictionResistant; }
public static byte[] GenerateEncryptedPreMasterSecret(SecureRandom random, RsaKeyParameters rsaServerPublicKey, Stream output) { /* * Choose a PremasterSecret and send it encrypted to the server */ byte[] premasterSecret = new byte[48]; random.NextBytes(premasterSecret); TlsUtilities.WriteVersion(premasterSecret, 0); Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine()); encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, random)); try { byte[] keData = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length); TlsUtilities.WriteOpaque16(keData, output); } catch (InvalidCipherTextException) { /* * This should never happen, only during decryption. */ throw new TlsFatalAlert(AlertDescription.internal_error); } return premasterSecret; }
public DHKeyGenerationParameters( SecureRandom random, DHParameters parameters) : base(random, GetStrength(parameters)) { this.parameters = parameters; }
internal BigInteger CalculatePrivate( DHParameters dhParams, SecureRandom random) { int limit = dhParams.L; if (limit != 0) { return new BigInteger(limit, random).SetBit(limit - 1); } BigInteger min = BigInteger.Two; int m = dhParams.M; if (m != 0) { min = BigInteger.One.ShiftLeft(m - 1); } BigInteger max = dhParams.P.Subtract(BigInteger.Two); BigInteger q = dhParams.Q; if (q != null) { max = q.Subtract(BigInteger.Two); } return BigIntegers.CreateRandomInRange(min, max, random); }
public virtual byte[] CalculateRawSignature(SecureRandom random, IAsymmetricKeyParameter privateKey, byte[] md5andsha1) { ISigner s = MakeSigner(new NullDigest(), true, new ParametersWithRandom(privateKey, random)); s.BlockUpdate(md5andsha1, 0, md5andsha1.Length); return s.GenerateSignature(); }
public ECKeyGenerationParameters( DerObjectIdentifier publicKeyParamSet, SecureRandom random) : this(LookupParameters(publicKeyParamSet), random) { this.publicKeyParamSet = publicKeyParamSet; }
public ECKeyGenerationParameters( ECDomainParameters domainParameters, SecureRandom random) : base(random, domainParameters.N.BitLength) { this.domainParams = domainParameters; }
private static Org.BouncyCastle.Security.SecureRandom GetSecureRandom() { var randomGenerator = new CryptoApiRandomGenerator(); var random = new Org.BouncyCastle.Security.SecureRandom(randomGenerator); return(random); }
public virtual void Init(bool forSigning, ICipherParameters parameters) { SecureRandom providedRandom = null; if (forSigning) { if (parameters is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)parameters; providedRandom = rParam.Random; parameters = rParam.Parameters; } if (!(parameters is DsaPrivateKeyParameters)) throw new InvalidKeyException("DSA private key required for signing"); this.key = (DsaPrivateKeyParameters)parameters; } else { if (!(parameters is DsaPublicKeyParameters)) throw new InvalidKeyException("DSA public key required for verification"); this.key = (DsaPublicKeyParameters)parameters; } this.random = InitSecureRandom(forSigning && !kCalculator.IsDeterministic, providedRandom); }
public virtual void Init( bool forSigning, ICipherParameters parameters) { if (parameters is ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom) parameters; parameters = p.Parameters; random = p.Random; } else { if (forSigning) { random = new SecureRandom(); } } cipher.Init(forSigning, parameters); RsaKeyParameters kParam; if (parameters is RsaBlindingParameters) { kParam = ((RsaBlindingParameters) parameters).PublicKey; } else { kParam = (RsaKeyParameters) parameters; } emBits = kParam.Modulus.BitLength - 1; block = new byte[(emBits + 7) / 8]; }
public static X509Certificate GenCert(CertInfo info) { RsaKeyPairGenerator _rsa = new RsaKeyPairGenerator(); SecureRandom _random = new SecureRandom(); _rsa.Init(new KeyGenerationParameters(_random, info.rsa_strength)); AsymmetricCipherKeyPair _pair = _rsa.GenerateKeyPair(); X509Name _cert_name = new X509Name("CN=" + info.name); BigInteger _serialnumber = BigInteger.ProbablePrime(120, new Random()); X509V3CertificateGenerator _cert = new X509V3CertificateGenerator(); _cert.SetSerialNumber(_serialnumber); _cert.SetSubjectDN(_cert_name); _cert.SetIssuerDN(_cert_name); _cert.SetNotBefore(info.begin_date); _cert.SetNotAfter(info.expire_date); _cert.SetSignatureAlgorithm("SHA1withRSA"); _cert.SetPublicKey(_pair.Public); _cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pair.Public), new GeneralNames(new GeneralName(_cert_name)), _serialnumber)); _cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth })); return _cert.Generate(_pair.Private); }
protected DtlsProtocol(SecureRandom secureRandom) { if (secureRandom == null) throw new ArgumentNullException("secureRandom"); this.mSecureRandom = secureRandom; }
public virtual byte[] GenerateRawSignature(SecureRandom random, AsymmetricKeyParameter privateKey, byte[] md5AndSha1) { IAsymmetricBlockCipher engine = CreateRsaImpl(); engine.Init(true, new ParametersWithRandom(privateKey, random)); return engine.ProcessBlock(md5AndSha1, 0, md5AndSha1.Length); }
/// <summary>Initialise the generator for signing.</summary> public void InitSign( int sigType, PgpPrivateKey key, SecureRandom random) { this.privKey = key; this.signatureType = sigType; try { ICipherParameters cp = key.Key; if (random != null) { cp = new ParametersWithRandom(key.Key, random); } sig.Init(true, cp); } catch (InvalidKeyException e) { throw new PgpException("invalid key.", e); } dig.Reset(); lastb = 0; }
public Gost3410KeyGenerationParameters( SecureRandom random, Gost3410Parameters parameters) : base(random, parameters.P.BitLength - 1) { this.parameters = parameters; }
/** * 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(BigInteger N, BigInteger g, IDigest digest, SecureRandom random) { this.N = N; this.g = g; this.digest = digest; this.random = random; }
public Gost3410KeyGenerationParameters( SecureRandom random, DerObjectIdentifier publicKeyParamSet) : this(random, LookupParameters(publicKeyParamSet)) { this.publicKeyParamSet = publicKeyParamSet; }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID); IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName); // Note: In Java build, the IV is automatically generated in JCE layer int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16; byte[] iv = new byte[ivLength]; random.NextBytes(iv); ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv); keyWrapper.Init(true, new ParametersWithRandom(parameters, random)); Asn1OctetString encryptedKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); DerSequence seq = new DerSequence( new DerObjectIdentifier(keyEncryptionKeyOID), new DerOctetString(iv)); AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier( PkcsObjectIdentifiers.IdAlgPwriKek, seq); return new RecipientInfo(new PasswordRecipientInfo( keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey)); }
/** * initialise the ElGamal engine. * * @param forEncryption true if we are encrypting, false otherwise. * @param param the necessary ElGamal key parameters. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom) parameters; this.key = (ElGamalKeyParameters) p.Parameters; this.random = p.Random; } else { this.key = (ElGamalKeyParameters) parameters; this.random = new SecureRandom(); } this.forEncryption = forEncryption; this.bitSize = key.Parameters.P.BitLength; if (forEncryption) { if (!(key is ElGamalPublicKeyParameters)) { throw new ArgumentException("ElGamalPublicKeyParameters are required for encryption."); } } else { if (!(key is ElGamalPrivateKeyParameters)) { throw new ArgumentException("ElGamalPrivateKeyParameters are required for decryption."); } } }
public ElGamalKeyGenerationParameters( SecureRandom random, ElGamalParameters parameters) : base(random, GetStrength(parameters)) { this.parameters = parameters; }
public static RsaKeyPair RsaKeysFromPassword(string Password, byte[] Salt) { byte[] pass = System.Text.Encoding.UTF32.GetBytes(Password); if (Salt == null) { RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); byte[] salt = new byte[24]; provider.GetBytes(salt); Salt = salt; } else if (Salt.Length < 24) // Pad the salt with 0x00 { byte[] salt = new byte[24]; Array.Copy(Salt, salt, Salt.Length); Salt = salt; } else if (Salt.Length > 24) // Truncate the salt to 24 bytes { byte[] salt = new byte[24]; Array.Copy(Salt, salt, salt.Length); Salt = salt; } // Generate the hash Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(pass, Salt, 100000); pass = pbkdf2.GetBytes(24); RsaKeyPairGenerator rsaGenerator = new RsaKeyPairGenerator(); var rng = new Org.BouncyCastle.Security.SecureRandom(pass); rsaGenerator.Init(new KeyGenerationParameters(rng, 2048)); var keyPair = rsaGenerator.GenerateKeyPair(); string privatePem = ""; string publicPem = ""; using (TextWriter privateKeyTextWriter = new StringWriter()) { PemWriter pemWriter = new PemWriter(privateKeyTextWriter); pemWriter.WriteObject(keyPair.Private); pemWriter.Writer.Flush(); privatePem = privateKeyTextWriter.ToString(); } using (TextWriter publicKeyTextWriter = new StringWriter()) { PemWriter pemWriter = new PemWriter(publicKeyTextWriter); pemWriter.WriteObject(keyPair.Public); pemWriter.Writer.Flush(); publicPem = publicKeyTextWriter.ToString(); } return(new RsaKeyPair() { PublicKey = publicPem, PrivateKey = privatePem, Timestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds }); }
/// <summary> /// The certificate needs a serial number. This is used for revocation, /// and usually should be an incrementing index (which makes it easier to revoke a range of certificates). /// Since we don't have anywhere to store the incrementing index, we can just use a random number. /// </summary> /// <param name="random"></param> /// <returns></returns> private static BigInteger GenerateSerialNumber(Org.BouncyCastle.Security.SecureRandom random) { var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); return(serialNumber); }
/// <summary> /// Generate a key pair. /// </summary> /// <param name="random">The random number generator.</param> /// <param name="strength">The key length in bits. For RSA, 2048 bits should be considered the minimum acceptable these days.</param> /// <returns></returns> private static AsymmetricCipherKeyPair GenerateKeyPair(Org.BouncyCastle.Security.SecureRandom random, int strength) { var keyGenerationParameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); return(subjectKeyPair); }
internal AbstractTlsContext(Org.BouncyCastle.Security.SecureRandom secureRandom, Org.BouncyCastle.Crypto.Tls.SecurityParameters securityParameters) { IDigest digest = TlsUtilities.CreateHash((byte)4); byte[] buffer = new byte[digest.GetDigestSize()]; secureRandom.NextBytes(buffer); this.mNonceRandom = new DigestRandomGenerator(digest); this.mNonceRandom.AddSeedMaterial(NextCounterValue()); this.mNonceRandom.AddSeedMaterial(Times.NanoTime()); this.mNonceRandom.AddSeedMaterial(buffer); this.mSecureRandom = secureRandom; this.mSecurityParameters = securityParameters; }
public static Asn1Encodable GenerateParameters( DerObjectIdentifier algID, SecureRandom random) { return(GenerateParameters(algID.Id, random)); }
// http://stackoverflow.com/questions/36942094/how-can-i-generate-a-self-signed-cert-without-using-obsolete-bouncycastle-1-7-0 public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateX509Cert2(string certName) { var keypairgen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator(); keypairgen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters( new Org.BouncyCastle.Security.SecureRandom( new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator() ) , 1024 //, 512 ) ); Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair(); // --- Until here we generate a keypair var random = new Org.BouncyCastle.Security.SecureRandom( new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator() ); // SHA1WITHRSA // SHA256WITHRSA // SHA384WITHRSA // SHA512WITHRSA // SHA1WITHECDSA // SHA224WITHECDSA // SHA256WITHECDSA // SHA384WITHECDSA // SHA512WITHECDSA Org.BouncyCastle.Crypto.ISignatureFactory signatureFactory = new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory("SHA512WITHRSA", keypair.Private, random) ; var gen = new Org.BouncyCastle.X509.X509V3CertificateGenerator(); var CN = new Org.BouncyCastle.Asn1.X509.X509Name("CN=" + certName); var SN = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(SN); gen.SetSubjectDN(CN); gen.SetIssuerDN(CN); gen.SetNotAfter(DateTime.Now.AddYears(1)); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetPublicKey(keypair.Public); // -- Are these necessary ? // public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35"); // OID value: 2.5.29.35 // OID description: id-ce-authorityKeyIdentifier // This extension may be used either as a certificate or CRL extension. // It identifies the public key to be used to verify the signature on this certificate or CRL. // It enables distinct keys used by the same CA to be distinguished (e.g., as key updating occurs). // http://stackoverflow.com/questions/14930381/generating-x509-certificate-using-bouncy-castle-java gen.AddExtension( Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier.Id, false, new Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier( Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public), new Org.BouncyCastle.Asn1.X509.GeneralNames(new Org.BouncyCastle.Asn1.X509.GeneralName(CN)), SN )); // OID value: 1.3.6.1.5.5.7.3.1 // OID description: Indicates that a certificate can be used as an SSL server certificate. gen.AddExtension( Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage.Id, false, new Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage( new System.Collections.Generic.List <object>() { new Org.BouncyCastle.Asn1.DerObjectIdentifier("1.3.6.1.5.5.7.3.1") } ) ); gen.AddExtension( new Org.BouncyCastle.Asn1.DerObjectIdentifier("2.5.29.19"), false, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false) // true if it is allowed to sign other certs ); gen.AddExtension( new Org.BouncyCastle.Asn1.DerObjectIdentifier("2.5.29.15"), true, new Org.BouncyCastle.X509.X509KeyUsage( Org.BouncyCastle.X509.X509KeyUsage.DigitalSignature | Org.BouncyCastle.X509.X509KeyUsage.NonRepudiation | Org.BouncyCastle.X509.X509KeyUsage.KeyEncipherment | Org.BouncyCastle.X509.X509KeyUsage.DataEncipherment) ); // -- End are these necessary ? Org.BouncyCastle.X509.X509Certificate bouncyCert = gen.Generate(signatureFactory); // Org.BouncyCastle.X509.X509Certificate bouncyCert = gen.Generate(keypair.Private); bouncyCert.GetPublicKey(); byte[] ba = bouncyCert.GetEncoded(); using (System.IO.TextWriter textWriter = new System.IO.StringWriter()) { Org.BouncyCastle.OpenSsl.PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter); pemWriter.WriteObject(bouncyCert); pemWriter.WriteObject(keypair.Private); pemWriter.Writer.Flush(); string privateKey = textWriter.ToString(); System.Console.WriteLine(privateKey); } // End Using textWriter string certFile = @"D:\mycert.cert"; using (System.IO.FileStream fs = System.IO.File.OpenWrite(certFile)) { using (System.IO.TextWriter textWriter = new System.IO.StreamWriter(fs)) { Org.BouncyCastle.OpenSsl.PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter); pemWriter.WriteObject(bouncyCert); pemWriter.WriteObject(keypair.Private); pemWriter.Writer.Flush(); string privateKey = textWriter.ToString(); System.Console.WriteLine(privateKey); } // End Using textWriter } // End Using fs // https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs // https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs // System.Security.Cryptography.X509Certificates.X509Certificate2 msCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(ba); System.Security.Cryptography.X509Certificates.X509Certificate2 msCert = new System.Security.Cryptography.X509Certificates .X509Certificate2(ba, null , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.PersistKeySet | // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.MachineKeySet | // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.Exportable ); msCert = new X509Certificate2(certFile, null, X509KeyStorageFlags.MachineKeySet); object obj = msCert.GetRSAPrivateKey(); System.Console.WriteLine(obj); if (msCert.HasPrivateKey) { Console.WriteLine(msCert.HasPrivateKey); } return(msCert); }
private static Asn1OctetString CreateIVOctetString( SecureRandom random, int ivLength) { return(new DerOctetString(CreateIV(random, ivLength))); }
public static Asn1Encodable GenerateParameters( string algorithm, SecureRandom random) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } string canonical = GetCanonicalAlgorithmName(algorithm); if (canonical == null) { throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); } switch (canonical) { // TODO These algorithms support an IV (see GetCipherParameters) // but JCE doesn't seem to provide an AlgorithmParametersGenerator for them // case "RIJNDAEL": // case "SKIPJACK": // case "TWOFISH": case "AES": case "AES128": case "AES192": case "AES256": return(CreateIVOctetString(random, 16)); case "BLOWFISH": return(CreateIVOctetString(random, 8)); case "CAMELLIA": case "CAMELLIA128": case "CAMELLIA192": case "CAMELLIA256": return(CreateIVOctetString(random, 16)); case "CAST5": return(new Cast5CbcParameters(CreateIV(random, 8), 128)); case "DES": case "DESEDE": case "DESEDE3": return(CreateIVOctetString(random, 8)); #if INCLUDE_IDEA case "IDEA": return(new IdeaCbcPar(CreateIV(random, 8))); #endif case "NOEKEON": return(CreateIVOctetString(random, 16)); case "RC2": return(new RC2CbcParameter(CreateIV(random, 8))); case "SEED": return(CreateIVOctetString(random, 16)); } throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); }
public static byte[] GetNextBytes(SecureRandom secureRandom, int length) { byte[] result = new byte[length]; secureRandom.NextBytes(result); return(result); }