public Init ( |
||
parameters | ||
Результат | void |
public HttpResponseMessage Get(string smsNumber, string code) { RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 2048)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); string publicKeyPath = Path.Combine(Path.GetTempPath(), "publicKey.key"); if (File.Exists(publicKeyPath)) { File.Delete(publicKeyPath); } using (TextWriter textWriter = new StreamWriter(publicKeyPath, false)) { PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keys.Public); pemWriter.Writer.Flush(); } string certSubjectName = "UShadow_RSA"; var certName = new X509Name("CN=" + certSubjectName); var serialNo = BigInteger.ProbablePrime(120, new Random()); X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator(); gen2.SetSerialNumber(serialNo); gen2.SetSubjectDN(certName); gen2.SetIssuerDN(new X509Name(true, "CN=UShadow")); gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0))); gen2.SetNotAfter(DateTime.Now.AddYears(2)); gen2.SetSignatureAlgorithm("sha512WithRSA"); gen2.SetPublicKey(keys.Public); Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(keys.Private); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); X509CertificateEntry certEntry = new X509CertificateEntry(newCert); store.SetCertificateEntry(newCert.SubjectDN.ToString(), certEntry); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private); store.SetKeyEntry(newCert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); using (MemoryStream ms = new MemoryStream()) { store.Save(ms, "Password".ToCharArray(), new SecureRandom()); var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; resp.Content.Headers.Add("Content-Type", "application/x-pkcs12"); return resp; } }
public static X509Certificate2 GenerateSelfSigned(TimeSpan lifetime) { Guid guid = Guid.NewGuid(); DateTime now = DateTime.UtcNow; SecureRandom rand = new SecureRandom(); //Generate a key pair RsaKeyPairGenerator keyGen = new RsaKeyPairGenerator(); keyGen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(rand, 1024)); AsymmetricCipherKeyPair key = keyGen.GenerateKeyPair(); //Generate a certificate X509Name dn = new X509Name("CN=" + guid.ToString()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetIssuerDN(dn); certGen.SetSerialNumber(new BigInteger(1, guid.ToByteArray())); certGen.SetSignatureAlgorithm("SHA1WITHRSA"); certGen.SetSubjectDN(dn); certGen.SetPublicKey(key.Public); certGen.SetNotBefore(now); certGen.SetNotAfter(now.Add(lifetime)); Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(key.Private); //Save it as pkcs12 MemoryStream p12Stream = new MemoryStream(); Pkcs12Store p12 = new Pkcs12Store(); p12.SetKeyEntry("sts", new AsymmetricKeyEntry(key.Private), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) }); p12.Save(p12Stream, p12TmpPwd.ToCharArray(), rand); //Load the pkcs12 as .Net Certificate return new X509Certificate2(p12Stream.ToArray(), p12TmpPwd, X509KeyStorageFlags.DefaultKeySet); }
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); }
//OLD CODE// /// <summary> /// This generates an RSA Key Pair using a hijacked BouncyCastle approach. /// </summary> /// <param name="keyGen"></param> /// <param name="keySize"></param> /// <returns></returns> public static AsymmetricCipherKeyPair GenerateKeyPair2(IBasylKeyGenerator keyGen, int keySize) { RsaKeyPairGenerator rsaGenerator = new RsaKeyPairGenerator(); rsaGenerator.Init(new KeyGenerationParameters(new BasylSecureRandom(keyGen), keySize)); AsymmetricCipherKeyPair keys = rsaGenerator.GenerateKeyPair(); return keys; }
/// <summary> /// Generate a cert/key pair /// </summary> private void GenerateCertKeyPair() { // Generate RSA key pair RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); keyPair = r.GenerateKeyPair(); // Generate the X509 certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name dnName = new X509Name("CN=NVIDIA GameStream Client"); certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond)); certGen.SetSubjectDN(dnName); certGen.SetIssuerDN(dnName); // use the same // Expires in 20 years certGen.SetNotBefore(DateTime.Now); certGen.SetNotAfter(DateTime.Now.AddYears(20)); certGen.SetPublicKey(keyPair.Public); certGen.SetSignatureAlgorithm("SHA1withRSA"); try { cert = certGen.Generate(keyPair.Private); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); } Task.Run(async () => await SaveCertKeyPair()).Wait(); }
private static AsymmetricCipherKeyPair GenerateKeyPair() { var secureRandom = new SecureRandom(new DigestRandomGenerator(new Sha512Digest())); var keyGenerationParameters = new KeyGenerationParameters(secureRandom, RsaKeySize); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); return keyPairGenerator.GenerateKeyPair(); }
public static AsymmetricCipherKeyPair GenerateKeyPair() { SecureRandom sr = new SecureRandom(); BigInteger pubExp = new BigInteger("10001", 16); RsaKeyGenerationParameters RSAKeyGenPara = new RsaKeyGenerationParameters(pubExp, sr, 1024, 80); RsaKeyPairGenerator RSAKeyPairGen = new RsaKeyPairGenerator(); RSAKeyPairGen.Init(RSAKeyGenPara); return RSAKeyPairGen.GenerateKeyPair(); }
public Key(int strength) { var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), strength)); _keyPair = generator.GenerateKeyPair(); _rsaKey = _keyPair.Private as RsaPrivateCrtKeyParameters; PublicKey = new PublicKey(_keyPair.Public as RsaKeyParameters); }
public static AsymmetricCipherKeyPair GetKeyPair() { var randomGenerator = new CryptoApiRandomGenerator(); var secureRandom = new SecureRandom(randomGenerator); var keyGenerationParameters = new KeyGenerationParameters(secureRandom, 2048); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); return keyPairGenerator.GenerateKeyPair(); }
public static X509Certificate2 GenerateSelfSignedCert() { 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); const string signatureAlgorithm = "SHA1WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var subjectDN = new X509Name("CN=simpletorrent"); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); var notBefore = DateTime.UtcNow.Date.AddHours(-24); var notAfter = notBefore.AddYears(1000); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); const int strength = 4096; 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(); string friendlyName = certificate.SubjectDN.ToString(); var certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); string password = "******"; var stream = new MemoryStream(); store.Save(stream, password.ToCharArray(), random); //mono bug #1660 fix -> convert to definite-length encoding byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray()); var convertedCertificate = new X509Certificate2( pfx, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return convertedCertificate; }
public KeyPair GenerateKeyPair(BitStrengths bitStrength) { KeyPair kp = new KeyPair(); RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), 768)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); kp.PublicKey = RsaPublicKeyToString((RsaKeyParameters)keys.Public); kp.PrivateKey = RsaPrivateKeyToString((RsaPrivateCrtKeyParameters)keys.Private); return kp; }
GenerateCertificate(string subjectName, out AsymmetricCipherKeyPair kp) { var kpgen = new RsaKeyPairGenerator(); // certificate strength 1024 bits kpgen.Init(new KeyGenerationParameters( new SecureRandom(new CryptoApiRandomGenerator()), 1024)); kp = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); var serialNo = BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotAfter(DateTime.Now.AddYears(100)); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA1withRSA"); gen.SetPublicKey(kp.Public); gen.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(certName)), serialNo)); /* 1.3.6.1.5.5.7.3.1 - id_kp_serverAuth 1.3.6.1.5.5.7.3.2 - id_kp_clientAuth 1.3.6.1.5.5.7.3.3 - id_kp_codeSigning 1.3.6.1.5.5.7.3.4 - id_kp_emailProtection 1.3.6.1.5.5.7.3.5 - id-kp-ipsecEndSystem 1.3.6.1.5.5.7.3.6 - id-kp-ipsecTunnel 1.3.6.1.5.5.7.3.7 - id-kp-ipsecUser 1.3.6.1.5.5.7.3.8 - id_kp_timeStamping 1.3.6.1.5.5.7.3.9 - OCSPSigning */ gen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth })); var newCert = gen.Generate(kp.Private); return newCert; }
public static X509Certificate2 GenerateNewCertificate(string name) { var kpGen = new RsaKeyPairGenerator(); kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certificateName = new X509Name("CN=" + name); BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(serialNumber); gen.SetSubjectDN(certificateName); gen.SetIssuerDN(certificateName); gen.SetNotAfter(DateTime.Now.AddYears(100)); gen.SetNotBefore(DateTime.Now.AddDays(-1)); gen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); gen.SetPublicKey(keyPair.Public); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public), new GeneralNames(new GeneralName(certificateName)), serialNumber)); X509Certificate newCert = gen.Generate(keyPair.Private); var newStore = new Pkcs12Store(); var certEntry = new X509CertificateEntry(newCert); newStore.SetCertificateEntry( Environment.MachineName, certEntry ); newStore.SetKeyEntry( Environment.MachineName, new AsymmetricKeyEntry(keyPair.Private), new[] {certEntry} ); var memoryStream = new MemoryStream(); newStore.Save( memoryStream, new char[0], new SecureRandom(new CryptoApiRandomGenerator()) ); return new X509Certificate2(memoryStream.ToArray()); }
/// <summary> /// Erstellt die für die PKCS#10-Datei notwendigen Daten /// </summary> /// <returns>Die für die PKCS#10-Datei notwendigen Daten</returns> public Pkcs10Data CreateRequest() { var sigAlgoName = "SHA256WITHRSA"; var subject = new X509Name( true, $"CN={Requester.Surname}, OU={Requester.Number}, OU={Requester.CompanyName}, O={"ITSG TrustCenter fuer Arbeitgeber"}, C={"DE"}", new Pkcs.X509ItsgEntryConverter() ); var rng = new SecureRandom(); var rsaKeyPair = RSA; if (rsaKeyPair == null) { var keyPairGen = new RsaKeyPairGenerator(); keyPairGen.Init(new KeyGenerationParameters(rng, 2048)); rsaKeyPair = keyPairGen.GenerateKeyPair(); } var csr = new Pkcs10CertificationRequest(sigAlgoName, subject, rsaKeyPair.Public, null, rsaKeyPair.Private); var outputCsrPem = new StringWriter(); { var pemWriter = new PemWriter(outputCsrPem); pemWriter.WriteObject(csr); } var outputPrivateKeyPem = new StringWriter(); { var pemWriter = new PemWriter(outputPrivateKeyPem); if (string.IsNullOrEmpty(Password)) { pemWriter.WriteObject(rsaKeyPair.Private); } else { pemWriter.WriteObject( rsaKeyPair.Private, "des-ede3-cbc", Password.ToCharArray(), rng ); } } var rsaPubKey = (RsaKeyParameters)rsaKeyPair.Public; var rawPubKeyData = OstcUtils.CalculatePublicKeyHash(rsaPubKey); return new Pkcs10Data(csr.GetEncoded(), outputCsrPem.ToString(), outputPrivateKeyPem.ToString(), rawPubKeyData); }
/// <summary> /// Generate a new key with the given length. /// </summary> /// <param name="length">Length of the key to be generated. Usually given in bits, but depends on the algorithm.</param> /// <returns>New RSAPrivateKey with the PublicKey-property set to the corresponding RSAPublicKey.</returns> public Key generateKey(short length) { Debug.Assert(length >= 2048, "The key must be at least 2048 bits in length."); Debug.Assert(((length % 1024) == 0), "The key must be a power of 1024."); RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), length)); AsymmetricCipherKeyPair pair = generator.GenerateKeyPair(); RSAPrivateKey privateKey = new RSAPrivateKey(pair.Private); RSAPublicKey publicKey = new RSAPublicKey(pair.Public); privateKey.PublicKey = publicKey; return privateKey; }
public static byte[] Init() { AsymmetricCipherKeyPair keyPair = null; string path = "proxy/session-key"; try { AsymmetricKeyParameter keyPub = PublicKeyFactory.CreateKey(File.ReadAllBytes(path + ".pub")); AsymmetricKeyParameter KeyPriv = PrivateKeyFactory.CreateKey(File.ReadAllBytes(path + ".priv")); keyPair = new AsymmetricCipherKeyPair(keyPub, KeyPriv); Debug.WriteLine("Loaded session.key"); } catch (Exception e) { Log.WriteServer(e); Debug.WriteLine("Generating session.key..."); var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); keyPair = generator.GenerateKeyPair(); Debug.WriteLine("Generated, saving..."); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); byte[] bytePub = publicKeyInfo.ToAsn1Object().GetDerEncoded(); Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path + ".pub", bytePub); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); byte[] bytePriv = privateKeyInfo.ToAsn1Object().GetDerEncoded(); File.WriteAllBytes(path + ".priv", bytePriv); Debug.WriteLine("Saved session.key"); } //Old method /*var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); var keyPair = generator.GenerateKeyPair(); */ keyParameters = (RsaKeyParameters)keyPair.Private; SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); return info.GetEncoded(); }
static X509Certificate2 AttemptToGenerate(string fullName) { var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(Random, 2048)); var cerKp = kpgen.GenerateKeyPair(); IDictionary attrs = new Hashtable(); attrs[X509Name.E] = ""; attrs[X509Name.CN] = fullName; attrs[X509Name.O] = fullName; attrs[X509Name.C] = fullName; IList ord = new ArrayList(); ord.Add(X509Name.E); ord.Add(X509Name.CN); ord.Add(X509Name.O); ord.Add(X509Name.C); var certGen = new X509V3CertificateGenerator(); var serial = new byte[32]; Random.NextBytes(serial); certGen.SetSerialNumber(new BigInteger(serial).Abs()); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0))); certGen.SetNotAfter(DateTime.Today.AddYears(100)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(cerKp.Public); certGen.SetSignatureAlgorithm("SHA1WithRSA"); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cerKp.Public))); var x509 = certGen.Generate(cerKp.Private); var x509Certificate = DotNetUtilities.ToX509Certificate(x509); return new X509Certificate2(x509Certificate) { PrivateKey = AddPrivateKey(cerKp) }; }
public AsymmetricCipherKeyPair BuildKey(byte[] seed, byte[] payload) { var publicExponent = new BigInteger("10001", 16); var keygen = new RsaKeyPairGenerator(); keygen.Init(new RsaKeyGenerationParameters(publicExponent, new SecureRandom(new SeededGenerator(seed)), 2048, 80)); var pair = keygen.GenerateKeyPair(); var paramz = ((RsaPrivateCrtKeyParameters) pair.Private); var modulus = paramz.Modulus.ToByteArray(); Replace(modulus, payload, 80); var p = paramz.P; var n = new BigInteger(modulus); var preQ = n.Divide(p); var q = preQ.NextProbablePrime(); return ComposeKeyPair(p, q, publicExponent); }
public void GenAkey() { //RSA密钥对的构造器 RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); //RSA密钥构造器的参数 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters( Org.BouncyCastle.Math.BigInteger.ValueOf(3), new Org.BouncyCastle.Security.SecureRandom(), 1024, //密钥长度 25); //用参数初始化密钥构造器 keyGenerator.Init(param); //产生密钥对 AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); //获取公钥和密钥 AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private; _Uk.TbPass.Text = publicKey.ToString(); _Uk.TbSalt.Text = privateKey.ToString(); }
public override void PerformTest() { testSig(1, pub1, prv1, slt1a, msg1a, sig1a); testSig(2, pub1, prv1, slt1b, msg1b, sig1b); testSig(3, pub2, prv2, slt2a, msg2a, sig2a); testSig(4, pub2, prv2, slt2b, msg2b, sig2b); testSig(5, pub4, prv4, slt4a, msg4a, sig4a); testSig(6, pub4, prv4, slt4b, msg4b, sig4b); testSig(7, pub8, prv8, slt8a, msg8a, sig8a); testSig(8, pub8, prv8, slt8b, msg8b, sig8b); testSig(9, pub9, prv9, slt9a, msg9a, sig9a); testSig(10, pub9, prv9, slt9b, msg9b, sig9b); // // loop test // int failed = 0; byte[] data = new byte[DATA_LENGTH]; SecureRandom random = new SecureRandom(); RsaKeyParameters[] kprv ={prv1, prv2, prv4, prv8, prv9}; RsaKeyParameters[] kpub ={pub1, pub2, pub4, pub8, pub9}; for (int j = 0, i = 0; j < NUM_TESTS; j++, i++) { if (i == kprv.Length) { i = 0; } if (!isProcessingOkay(kpub[i], kprv[i], data, random)) { failed++; } } if (failed != 0) { Fail("loop test failed - failures: " + failed); } // // key generation test // RsaKeyPairGenerator pGen = new RsaKeyPairGenerator(); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25); pGen.Init(genParam); failed = 0; for (int k = 0; k < NUM_TESTS_WITH_KEY_GENERATION; k++) { AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); for (int j = 0; j < NUM_TESTS; j++) { if (!isProcessingOkay((RsaKeyParameters)pair.Public, (RsaKeyParameters)pair.Private, data, random)) { failed++; } } } if (failed != 0) { Fail("loop test with key generation failed - failures: " + failed); } }
/// <summary> /// Build a PGP key pair /// </summary> /// <param name="bits">number of bits in key, e.g. 2048</param> /// <param name="identifier">key identifier, e.g. "Your Name <*****@*****.**>" </param> /// <param name="password">key password or null</param> /// <param name="privateKey">returned ascii private key</param> /// <param name="publicKey">returned ascii public key</param> public static void PGPGenerateKey(int bits, string identifier, string password, out string privateKey, out string publicKey) { // generate a new RSA keypair RsaKeyPairGenerator gen = new RsaKeyPairGenerator(); gen.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x101), new Org.BouncyCastle.Security.SecureRandom(), bits, 80)); AsymmetricCipherKeyPair pair = gen.GenerateKeyPair(); // create PGP subpacket PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator(); hashedGen.SetKeyFlags(true, PgpKeyFlags.CanCertify | PgpKeyFlags.CanSign | PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage); hashedGen.SetPreferredCompressionAlgorithms(false, new int[] { (int)CompressionAlgorithmTag.Zip }); hashedGen.SetPreferredHashAlgorithms(false, new int[] { (int)HashAlgorithmTag.Sha1 }); hashedGen.SetPreferredSymmetricAlgorithms(false, new int[] { (int)SymmetricKeyAlgorithmTag.Cast5 }); PgpSignatureSubpacketVector sv = hashedGen.Generate(); PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator(); // create the PGP key PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, pair.Public, pair.Private, DateTime.Now, identifier, SymmetricKeyAlgorithmTag.Cast5, (password != null ? password.ToCharArray() : null), hashedGen.Generate(), unhashedGen.Generate(), new Org.BouncyCastle.Security.SecureRandom()); // extract the keys using (MemoryStream ms = new MemoryStream()) { using (ArmoredOutputStream ars = new ArmoredOutputStream(ms)) { secretKey.Encode(ars); } privateKey = Encoding.ASCII.GetString(ms.ToArray()); } using (MemoryStream ms = new MemoryStream()) { using (ArmoredOutputStream ars = new ArmoredOutputStream(ms)) { secretKey.PublicKey.Encode(ars); } publicKey = Encoding.ASCII.GetString(ms.ToArray()); } }
/// <summary> /// Static method used to create a certificate and return as a .net object /// </summary> public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false, string exportDirectory = null) { // generate a key pair using RSA var generator = new RsaKeyPairGenerator(); // keys have to be a minimum of 2048 bits for Azure generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair(); // get a copy of the private key AsymmetricKeyParameter privateKey = cerKp.Private; // create the CN using the name passed in and create a unique serial number for the cert var certName = new X509Name("CN=" + name); BigInteger serialNo = BigInteger.ProbablePrime(120, new Random()); // start the generator and set CN/DN and serial number and valid period var x509Generator = new X509V3CertificateGenerator(); x509Generator.SetSerialNumber(serialNo); x509Generator.SetSubjectDN(certName); x509Generator.SetIssuerDN(certName); x509Generator.SetNotBefore(start); x509Generator.SetNotAfter(end); // add the server authentication key usage var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment); x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object()); var extendedKeyUsage = new ExtendedKeyUsage(new[] {KeyPurposeID.IdKPServerAuth}); x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object()); // algorithm can only be SHA1 ?? x509Generator.SetSignatureAlgorithm("sha1WithRSA"); // Set the key pair x509Generator.SetPublicKey(cerKp.Public); X509Certificate certificate = x509Generator.Generate(cerKp.Private); // export the certificate bytes byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword); // build the key parameter and the certificate entry var keyEntry = new AsymmetricKeyEntry(privateKey); var entry = new X509CertificateEntry(certificate); // build the PKCS#12 store to encapsulate the certificate var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption); builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption); builder.Build(); // create a memorystream to hold the output var stream = new MemoryStream(10000); // create the individual store and set two entries for cert and key var store = new Pkcs12Store(); store.SetCertificateEntry("Created by Fluent Management", entry); store.SetKeyEntry("Created by Fluent Management", keyEntry, new[] { entry }); store.Save(stream, userPassword.ToCharArray(), new SecureRandom()); // Create the equivalent C# representation var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable); // set up the PEM writer too if (exportDirectory != null) { var textWriter = new StringWriter(); var pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(cerKp.Private, "DESEDE", userPassword.ToCharArray(), new SecureRandom()); pemWriter.Writer.Flush(); string privateKeyPem = textWriter.ToString(); using (var writer = new StreamWriter(Path.Combine(exportDirectory, cert.Thumbprint + ".pem"))) { writer.WriteLine(privateKeyPem); } // also export the certs - first the .pfx byte[] privateKeyBytes = cert.Export(X509ContentType.Pfx, userPassword); using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".pfx"), FileMode.OpenOrCreate, FileAccess.Write)) { writer.Write(privateKeyBytes, 0, privateKeyBytes.Length); } // also export the certs - then the .cer byte[] publicKeyBytes = cert.Export(X509ContentType.Cert); using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".cer"), FileMode.OpenOrCreate, FileAccess.Write)) { writer.Write(publicKeyBytes, 0, publicKeyBytes.Length); } } // if specified then this add this certificate to the store if (addtoStore) AddToMyStore(cert); return cert; }
// 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); }
/// <summary> /// Static method used to create a certificate and return as a .net object /// </summary> public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false) { // generate a key pair using RSA var generator = new RsaKeyPairGenerator(); // keys have to be a minimum of 2048 bits for Azure generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair(); // get a copy of the private key AsymmetricKeyParameter privateKey = cerKp.Private; // create the CN using the name passed in and create a unique serial number for the cert var certName = new X509Name("CN=" + name); BigInteger serialNo = BigInteger.ProbablePrime(120, new Random()); // start the generator and set CN/DN and serial number and valid period var x509Generator = new X509V3CertificateGenerator(); x509Generator.SetSerialNumber(serialNo); x509Generator.SetSubjectDN(certName); x509Generator.SetIssuerDN(certName); x509Generator.SetNotBefore(start); x509Generator.SetNotAfter(end); // add the server authentication key usage var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment); x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object()); var extendedKeyUsage = new ExtendedKeyUsage(new[] {KeyPurposeID.IdKPServerAuth}); x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object()); // algorithm can only be SHA1 ?? x509Generator.SetSignatureAlgorithm("sha1WithRSA"); // Set the key pair x509Generator.SetPublicKey(cerKp.Public); X509Certificate certificate = x509Generator.Generate(cerKp.Private); // export the certificate bytes byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword); // build the key parameter and the certificate entry var keyEntry = new AsymmetricKeyEntry(privateKey); var entry = new X509CertificateEntry(certificate); // build the PKCS#12 store to encapsulate the certificate var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption); builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption); builder.Build(); // create a memorystream to hold the output var stream = new MemoryStream(2000); // create the individual store and set two entries for cert and key var store = new Pkcs12Store(); store.SetCertificateEntry("Elastacloud Test Certificate", entry); store.SetKeyEntry("Elastacloud Test Certificate", keyEntry, new[] {entry}); store.Save(stream, userPassword.ToCharArray(), new SecureRandom()); // Create the equivalent C# representation var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable); // if specified then this add this certificate to the store if (addtoStore) AddToMyStore(cert); return cert; }
private static void GenerateSigningCertificate(ICertificatePolicy certificatePolicy, out string thumbprint, out string pemPublicCert, out byte[] pkcs12Data, out System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); X509Name certName; if (certificatePolicy.X509NameDictionary == null || !certificatePolicy.X509NameDictionary.Any()) { certName = new X509Name("CN=" + certificatePolicy.CommonName); } else { var list = new Dictionary<string, string>(); AddSubjectNameItem(list, "CN", certificatePolicy.CommonName); foreach (var item in certificatePolicy.X509NameDictionary) { AddSubjectNameItem(list, item.Key, item.Value); } certName = new X509Name(GetSubjectNameItemString(list)); } BigInteger serialNo; serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotBefore(DateTime.UtcNow.AddHours(-2)); // go back 2 hours just to be safe gen.SetNotAfter(DateTime.UtcNow.AddDays(certificatePolicy.ValidForDays)); gen.SetSignatureAlgorithm("SHA256WithRSA"); gen.SetPublicKey(subjectKeyPair.Public); gen.AddExtension( X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); gen.AddExtension(X509Extensions.KeyUsage.Id, true, new KeyUsage(KeyUsage.DigitalSignature)); // handle our key purposes if (!certificatePolicy.AllPurposes) { var purposes = new List<KeyPurposeID>(); if (certificatePolicy.ServerAuthentication) { purposes.Add(KeyPurposeID.IdKPServerAuth); } if (certificatePolicy.ClientAuthentication) { purposes.Add(KeyPurposeID.IdKPClientAuth); } if (certificatePolicy.CodeSigning) { purposes.Add(KeyPurposeID.IdKPCodeSigning); } if (purposes.Any()) { gen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(purposes.ToArray())); } } var certificate = gen.Generate(subjectKeyPair.Private, random); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); // this is exportable to get the bytes of the key to our file system in an encrypted manner RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.PersistKeyInCsp = false; // do not persist rsaKey.ImportParameters(rsaParameters); var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); x509.PrivateKey = rsaKey; // this is non-exportable CspParameters cspParametersNoExport = new CspParameters(); cspParametersNoExport.KeyContainerName = Guid.NewGuid().ToString(); cspParametersNoExport.Flags = CspProviderFlags.UseNonExportableKey; RSACryptoServiceProvider rsaKey2 = new RSACryptoServiceProvider(2048, cspParametersNoExport); rsaKey2.PersistKeyInCsp = false; // do not persist rsaKey2.ImportParameters(rsaParameters); x509Certificate2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); x509Certificate2.PrivateKey = rsaKey2; //// Generating Random Numbers //var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; //var rnd = new Random(); //password = new string( // Enumerable.Repeat(chars, 15) // .Select(s => s[rnd.Next(s.Length)]) // .ToArray()); thumbprint = x509.Thumbprint.ToLower(); var publicKeyPem = new StringBuilder(); var utf8WithoutBom = new System.Text.UTF8Encoding(false); var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom)); publicKeyPemWriter.WriteObject(certificate); publicKeyPemWriter.Writer.Flush(); pemPublicCert = publicKeyPem.ToString(); pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx); }
public void generateCSR(string electoralEampaign, string user, string password) { X509Name name = new X509Name("C=PL, ST=Mazowieckie, L=Warszawa, O=KBW, E=-, OU=" + electoralEampaign + ", CN=" + user); RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 2048, 25); keyGenerator.Init(param); AsymmetricCipherKeyPair ackp = keyGenerator.GenerateKeyPair(); Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, null, ackp.Private); System.Text.StringBuilder CSRPem = new System.Text.StringBuilder(); PemWriter CSRPemWriter = new PemWriter(new System.IO.StringWriter(CSRPem)); CSRPemWriter.WriteObject(csr); CSRPemWriter.Writer.Flush(); this.generatedCSR = CSRPem.ToString(); System.Text.StringBuilder PrivateKeyPem = new System.Text.StringBuilder(); PemWriter PrivateKeyPemWriter = new PemWriter(new System.IO.StringWriter(PrivateKeyPem)); PrivateKeyPemWriter.WriteObject(ackp.Private); CSRPemWriter.Writer.Flush(); this.keys = PrivateKeyPem.ToString(); AsymmetricKeyParameter publicKey = ackp.Public; AsymmetricKeyParameter privateKey = ackp.Private; System.IO.StringWriter sw = new System.IO.StringWriter(); PemWriter pw = new PemWriter(sw); pw.WriteObject(privateKey, "AES-256-CBC", password.ToCharArray(), new SecureRandom()); pw.Writer.Close(); this.keys = sw.ToString(); if (!System.IO.Directory.Exists(this.path + "\\Licenses")) { try { System.IO.Directory.CreateDirectory(this.path + "\\Licenses"); } catch (System.ArgumentNullException) { MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error"); } catch (System.ArgumentException) { MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error"); } catch (System.UnauthorizedAccessException) { MessageBox.Show("Nie masz uprawnień do tworzenia katalogów. Otwórz aplikacje jako adnimistrator.", "Uwaga"); } catch (System.IO.PathTooLongException) { MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error"); } catch (System.IO.DirectoryNotFoundException) { MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error"); } catch (System.NotSupportedException) { MessageBox.Show("Nieprawidłowy format ścieżki. Nie można utworzyć katalogu \"Licenses\"", "Error"); } catch (System.IO.IOException) { MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error"); } } string namefile = ""; try { int tmp = System.IO.Directory.GetFiles(this.path + "\\Licenses", electoralEampaign.Replace("/", "_") + "_" + user + "*.csr").Length + 1; if (tmp > 1) { string num = tmp.ToString(); namefile = string.Concat(new string[] { electoralEampaign.Replace("/", "_"), "_", user, " ", num }); } else { namefile = electoralEampaign.Replace("/", "_") + "_" + user; } } catch (System.Exception) { namefile = electoralEampaign.Replace("/", "_") + "_" + user; } try { System.IO.StreamWriter sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".csr", false); sw2.Write(this.generatedCSR); sw2.Close(); sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".key", false); sw2.Write(this.keys); sw2.Close(); } catch (System.ArgumentNullException) { MessageBox.Show("Błędna ścieżka", "Error"); } catch (System.ArgumentException) { MessageBox.Show("Błędna ścieżka", "Error"); } catch (System.IO.DirectoryNotFoundException) { MessageBox.Show("Nie znaleziono katalogu", "Error"); } catch (System.IO.PathTooLongException) { MessageBox.Show("Zbyt długa ścieżka do katalogu", "Error"); } catch (System.IO.IOException) { MessageBox.Show("Podano ścieżke do pliku zamiast katalogu", "Error"); } catch (System.UnauthorizedAccessException) { MessageBox.Show("Program nie posiada uprawnień do zapisywania plików. Otwórz aplikacje jako Administrator", "Error"); } catch (System.Exception e) { MessageBox.Show("Nie można zapisać pliku. Orginal error: " + e.Message, "Error"); } }
private bool Initialize() { if (!Usable) return false; ErrorCode EC = ErrorCode.None; int nBytesWritten, nBytesRead; try { // Flush the device by reading until there's nothing left to read. byte[] byBuffer = new byte[1024]; while (true) { iPhoneEndpointReader.Read(byBuffer, 10, out nBytesRead); if (nBytesRead == 0 || EC != ErrorCode.None) break; } Global.Log("Saying hi to device... "); EC = iPhoneEndpointWriter.Write(iPhoneVersionHeader(), nDefaultTimeout, out nBytesWritten); if (EC != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString); if (nBytesWritten != 20) throw new Exception("<20 bytes written. 20 expected."); EC = iPhoneEndpointReader.Read(byBuffer, nDefaultTimeout, out nBytesRead); if (EC != ErrorCode.None) { Global.Log("failed! Is the device currently locked by a passcode? If not, replug it.\n", true); throw new Exception(UsbDevice.LastErrorString); } if (nBytesRead != 20) { Global.Log("failed!\n", true); throw new Exception("Device won't talk. Re-plug it."); } Global.Log("success!\n", true); int nTemp = 0; MemoryStream MS = new MemoryStream(byBuffer); BinaryReader BR = new BinaryReader(MS); MS.Seek(8, SeekOrigin.Begin); nTemp = System.Net.IPAddress.NetworkToHostOrder(BR.ReadInt32()); if (nTemp != 1) throw new Exception("iPhone major version != 1"); nTemp = System.Net.IPAddress.NetworkToHostOrder(BR.ReadInt32()); if (nTemp != 0) throw new Exception("iPhone minor version != 1"); BR.Close(); MS.Close(); } catch (Exception ex) { Global.Log((EC != ErrorCode.None ? EC + ":" : String.Empty) + ex.Message + "\n"); return false; } Global.Log("Starting up lockdownd... "); try { Lockdown = new LockdownConnection(this); } catch (Exception e) { Global.Log("failed!\n", true); throw e; } MUXConnections.Add(Lockdown); Global.Log("success!\n", true); _DeviceName = Lockdown.GetDeviceName(); _UniqueDeviceID = Lockdown.GetUniqueDeviceID(); #region Preparation of cryptography stuff if (LoadCryptoStuffFromRegistry() == false) { Global.Log("Haven't seen this device before. Creating new RSA keys.\n"); // First generate "root" and "host" private keys and X.509 certificates. X509V3CertificateGenerator RootCG = new X509V3CertificateGenerator(); Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator RootRKPG = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator(); RootRKPG.Init(new KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 1024)); Global.Log("Generating RSA key pair for root... "); RootKey = RootRKPG.GenerateKeyPair(); Global.Log("success!\n", true); // Outdated certificate preparation, was not compatible with iOS4 /*System.Security.Cryptography.X509Certificates.X509Certificate C = new System.Security.Cryptography.X509Certificates.X509Certificate(); RootCG.SetPublicKey(RootKey.Public); RootCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.One); RootCG.SetNotBefore(StartTime); RootCG.SetNotAfter(new DateTime(StartTime.Ticks + ((long)10000000 * 60 * 60 * 24 * 365 * 10))); // Issuer and subject stuff are irrelevant but BouncyCastle won't accept null inputs. RootCG.SetIssuerDN(new Org.BouncyCastle.Asn1.X509.X509Name(new ArrayList(), new ArrayList())); RootCG.SetSubjectDN(new Org.BouncyCastle.Asn1.X509.X509Name(new ArrayList(), new ArrayList())); RootCG.SetSignatureAlgorithm("SHA1WithRSAEncryption"); RootCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(true)); //Org.BouncyCastle.Asn1.X509.SubjectKeyIdentifier RootSKI = new Org.BouncyCastle.X509.Extension.SubjectKeyIdentifierStructure(RootKey.Public); //RootCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.SubjectKeyIdentifier, false, RootSKI); RootCertificate = RootCG.Generate(RootKey.Private);*/ System.Security.Cryptography.X509Certificates.X509Certificate C = new System.Security.Cryptography.X509Certificates.X509Certificate(); RootCG.SetPublicKey(RootKey.Public); RootCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero); RootCG.SetNotBefore(StartTime); RootCG.SetNotAfter(new DateTime(StartTime.Ticks + ((long)10000000 * 60 * 60 * 24 * 365 * 10))); RootCG.SetSignatureAlgorithm("SHA1WithRSAEncryption"); RootCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(true)); RootCertificate = RootCG.Generate(RootKey.Private); X509V3CertificateGenerator HostCG = new X509V3CertificateGenerator(); Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator HostRKPG = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator(); HostRKPG.Init(new KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 1024)); Global.Log("Generating RSA key pair for host... "); HostKey = HostRKPG.GenerateKeyPair(); Global.Log("success!\n", true); HostCG.SetPublicKey(HostKey.Public); HostCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero); HostCG.SetNotBefore(RootCertificate.NotBefore); HostCG.SetNotAfter(RootCertificate.NotAfter); HostCG.SetSignatureAlgorithm("SHA1WithRSAEncryption"); HostCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false)); HostCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage, true, new Org.BouncyCastle.Asn1.X509.KeyUsage(Org.BouncyCastle.Asn1.X509.KeyUsage.KeyEncipherment | Org.BouncyCastle.Asn1.X509.KeyUsage.DigitalSignature)); HostCertificate = HostCG.Generate(RootKey.Private); } else Global.Log("Loaded RSA stuff from registry.\n"); #endregion try { Lockdown.Authenticate(); } catch (Exception e) { Global.Log("Exception encountered during authentication:\n" + e); Shutdown(false); return false; } return true; }
public static AsymmetricCipherKeyPair GenerateRSAKeys(int KeySize) { Debug.WriteLine(KeySize); RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), KeySize)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); return keys; }
/* * creates a certificate and a private key and installs into windows registry */ public static void CreateCertificateKey( string subjectName, string issuerName, string signatureAlgorithm, int strength, DateTime begin, DateTime end, string subjectCountryCode, string subjectOrganization, string subjectTitle, string issuerCountryCode, string issuerOrganization, string issuerTitle, string subjectCommonName, string issuerCommonName) { RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(new CryptoApiRandomGenerator()); keyPairGenerator.Init(new KeyGenerationParameters(secureRandom, strength)); AsymmetricCipherKeyPair asCipherKeyPair = keyPairGenerator.GenerateKeyPair(); AsymmetricKeyParameter publicKey = asCipherKeyPair.Public; RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)asCipherKeyPair.Private; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), secureRandom); certificateGenerator.SetSerialNumber(serialNumber); string subjectNameString = "E=" + subjectName; if (subjectCommonName != null) subjectNameString += ", CN=" + subjectCommonName; if (subjectCountryCode != null) subjectNameString += ", C=" + subjectCountryCode; if (subjectOrganization != null) subjectNameString += ", O=" + subjectOrganization; if (subjectTitle != null) subjectNameString += ", T=" + subjectTitle; certificateGenerator.SetSubjectDN(new X509Name(subjectNameString)); string issuerNameString = "E=" + issuerName; if (issuerCommonName != null) issuerNameString += ", CN=" + issuerCommonName; if (issuerCountryCode != null) issuerNameString += ", C=" + issuerCountryCode; if (issuerOrganization != null) issuerNameString += ", O=" + issuerOrganization; if (issuerTitle != null) issuerNameString += ", T=" + issuerTitle; certificateGenerator.SetIssuerDN(new X509Name(issuerNameString)); certificateGenerator.SetNotBefore(begin); certificateGenerator.SetNotAfter(end); certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); certificateGenerator.SetPublicKey(publicKey); X509Certificate certificate = certificateGenerator.Generate(privateKey); sys.X509Certificate2 windowsCertificate = new sys.X509Certificate2(DotNetUtilities.ToX509Certificate(certificate)); windowsCertificate.PrivateKey = ConvertToSystemKey(privateKey); InstallIntoRegistry(windowsCertificate); }
public void RsaKeysGenerate(string PrivateKeyFilename, string PublicKeyFilename, string passw) { RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 1024, 25); keyGenerator.Init(param); AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private; SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); Asn1Object aobject = publicKeyInfo.ToAsn1Object(); byte[] pubInfoByte = aobject.GetEncoded(); System.IO.FileStream fs = new System.IO.FileStream(PublicKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(pubInfoByte, 0, pubInfoByte.Length); fs.Close(); string alg = "1.2.840.113549.1.12.1.3"; byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int count = 1000; char[] password = passw.ToCharArray(); EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password, salt, count, privateKey); byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded(); fs = new System.IO.FileStream(PrivateKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(priInfoByte, 0, priInfoByte.Length); fs.Close(); }
public static int Read() { Info = new HostInfo(); if (System.IO.File.Exists(SimpleMesh.Service.Runner.ConfigFile) == true) { string[] lines = System.IO.File.ReadAllLines(SimpleMesh.Service.Runner.ConfigFile); SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", SimpleMesh.Service.Runner.ConfigFile + " Contents:"); foreach (string line in lines) { string[] chunks = line.Split('!'); switch (chunks[0]) { case "HOSTUUID": SimpleMesh.Service.Runner.Info.UUID = new UUID(chunks[1]); if (chunks.Length > 2) { SimpleMesh.Service.Runner.Info.Description = chunks[2]; } SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\tUUID:\t\t" + SimpleMesh.Service.Runner.Info.UUID.ToString()); SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\tDescription:\t\t" + SimpleMesh.Service.Runner.Info.Description); break; case "HOSTKEY": SimpleMesh.Service.Runner.Info.Key = new Key(); SimpleMesh.Service.Runner.Info.Key.Decode(line.Replace("HOSTKEY!","")); SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\tHost Key:\t\t" + SimpleMesh.Service.Runner.Info.Key.ToString()); break; case "PORT": SimpleMesh.Service.Runner.Info.Ports.Add(chunks[1]); break; case "PROTOCOL": SimpleMesh.Service.Runner.Info.Protocols.Add(chunks[1]); break; } } } else { // Get info from the actual client. HostInfo scratch = HostInfoCallback(); DateTime Start = DateTime.Now; SimpleMesh.Service.Runner.Info = scratch; SimpleMesh.Service.Runner.Info.Key.Type = "RSA"; SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "Generating " + SimpleMesh.Service.Runner.Info.Key.Length.ToString() + " bit RSA key pair starting on: " + DateTime.Now.ToString()); RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), SimpleMesh.Service.Runner.Info.Key.Length)); AsymmetricCipherKeyPair test = r.GenerateKeyPair(); SimpleMesh.Service.Runner.Info.Key.PrivateKey = test.Private; SimpleMesh.Service.Runner.Info.Key.PublicKey = test.Public; List<string> file = new List<string>(); file.Add("I!1.1!!!"); file.Add("HOSTUUID!" + Info.UUID.ToString() + "!" + SimpleMesh.Service.Runner.Info.Description); file.Add("HOSTKEY!" + Info.Key.Encode(true)); foreach(string port in Info.Ports) { file.Add("PORT!" + port); } foreach (string protocol in Info.Protocols) { file.Add("PROTOCOL!" + protocol); } SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", SimpleMesh.Service.Runner.ConfigFile + " Contents:"); foreach (string line in file) { SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\t" + line); } if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(SimpleMesh.Service.Runner.ConfigFile)) == false) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(SimpleMesh.Service.Runner.ConfigFile)); } System.IO.File.WriteAllLines(SimpleMesh.Service.Runner.ConfigFile, file.ToArray()); } return 0; }
public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, 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 = "SHA1WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); // 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 = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key AsymmetricCipherKeyPair subjectKeyPair; var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Generating the Certificate var issuerKeyPair = subjectKeyPair; // selfsign certificate var certificate = certificateGenerator.Generate(issuerPrivKey, random); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { //throw new PemException("malformed sequence in RSA private key"); return(null); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); WriteKeytoFile(subjectName.Substring(3), WriteKeyAsPem(subjectKeyPair, 0), 0); WriteKeytoFile(subjectName.Substring(3), WriteKeyAsPem(subjectKeyPair, 1), 1); WriteCertificatetoFile(subjectName.Substring(3), WriteCertificateAsPem(x509)); Console.WriteLine(WriteKeyAsPem(subjectKeyPair, 0)); Console.WriteLine(WriteKeyAsPem(subjectKeyPair, 1)); Console.WriteLine(WriteCertificateAsPem(x509)); return(x509); }