/// <summary> /// Creates new certificate /// </summary> /// <returns></returns> public static void CreateSelfSignedCertificate(string subjectDirName, DateTime startDate, DateTime endDate, int signatureBits, int keyStrength, string password, string fileName) { string signatureAlgorithm; switch (signatureBits) { case 160: signatureAlgorithm = "SHA1withRSA"; break; case 224: signatureAlgorithm = "SHA224withRSA"; break; case 256: signatureAlgorithm = "SHA256withRSA"; break; case 384: signatureAlgorithm = "SHA384withRSA"; break; case 512: signatureAlgorithm = "SHA512withRSA"; break; default: throw new ArgumentException("Invalid signature bit size.", "signatureBits"); } // Generating Random Numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); // Generate public/private keys. AsymmetricCipherKeyPair encryptionKeys; KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); encryptionKeys = keyPairGenerator.GenerateKeyPair(); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); certificateGenerator.SetIssuerDN(new X509Name(subjectDirName)); certificateGenerator.SetSubjectDN(new X509Name(subjectDirName)); certificateGenerator.SetNotBefore(startDate); certificateGenerator.SetNotAfter(endDate); certificateGenerator.SetPublicKey(encryptionKeys.Public); // self-sign certificate Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(encryptionKeys.Private, random); Pkcs12Store store = new Pkcs12Store(); string friendlyName = certificate.SubjectDN.ToString(); X509CertificateEntry certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(encryptionKeys.Private), new[] { certificateEntry }); MemoryStream stream = new MemoryStream(); store.Save(stream, password.ToCharArray(), random); //Verify that the certificate is valid. _ = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); //Write the file. File.WriteAllBytes(fileName, stream.ToArray()); File.WriteAllBytes(Path.ChangeExtension(fileName, ".cer"), certificate.GetEncoded()); }
private ICipherParameters GetPrivateKey(Pkcs12Store store, string alias) { return(store.GetKey(alias).Key); }
public void UpdateCertificate(Pkcs12Store store) { _installer.UpdateCertificate(store); }
/// <summary> /// Create the actual certificate /// </summary> public static bool CreateCertificate(ICertificateSettings settings, Action <string> log, out string thumbprint, out string errorMessage) { errorMessage = string.Empty; thumbprint = string.Empty; try { var keyStore = new Pkcs12Store(); log(Strings.GeneratingKeys); var pGen = new RsaKeyPairGenerator(); var genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 10); pGen.Init(genParam); var keyPair = pGen.GenerateKeyPair(); log(Strings.GeneratingCertificate); var attrs = new Dictionary <DerObjectIdentifier, string>(); var oids = new List <DerObjectIdentifier> { X509Name.O, X509Name.L, X509Name.C, X509Name.CN, X509Name.EmailAddress, X509Name.OU, X509Name.ST }; oids.Reverse(); if (!string.IsNullOrEmpty(settings.OrgName)) { attrs.Add(X509Name.O, settings.OrgName); } else { oids.Remove(X509Name.O); } if (!string.IsNullOrEmpty(settings.OrgUnit)) { attrs.Add(X509Name.OU, settings.OrgUnit); } else { oids.Remove(X509Name.OU); } if (!string.IsNullOrEmpty(settings.City)) { attrs.Add(X509Name.L, settings.City); } else { oids.Remove(X509Name.L); } if (!string.IsNullOrEmpty(settings.CountryCode)) { attrs.Add(X509Name.C, settings.CountryCode); } else { oids.Remove(X509Name.C); } if (!string.IsNullOrEmpty(settings.State)) { attrs.Add(X509Name.ST, settings.State); } else { oids.Remove(X509Name.ST); } if (!string.IsNullOrEmpty(settings.Email)) { attrs.Add(X509Name.EmailAddress, settings.Email); } else { oids.Remove(X509Name.EmailAddress); } if (!string.IsNullOrEmpty(settings.UserName)) { attrs.Add(X509Name.CN, settings.UserName); } else { oids.Remove(X509Name.CN); } var certGen = new X509V3CertificateGenerator(); var random = new SecureRandom(); certGen.SetSerialNumber(BigInteger.ValueOf(Math.Abs(random.NextInt()))); certGen.SetIssuerDN(new X509Name(oids, attrs)); certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0))); var years = Math.Min(settings.MaxYears, 50); certGen.SetNotAfter(DateTime.Today.AddYears(years)); certGen.SetSubjectDN(new X509Name(oids, attrs)); certGen.SetPublicKey(keyPair.Public); certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); var cert = certGen.Generate(keyPair.Private); // Save log(Strings.SavingCertificate); var keyEntry = new AsymmetricKeyEntry(keyPair.Private); var certEntry = new X509CertificateEntry(cert); const string alias = "alias"; keyStore.SetKeyEntry(alias, keyEntry, new[] { certEntry }); var password = settings.Password; var memoryStream = new MemoryStream(); keyStore.Save(memoryStream, password.ToCharArray(), random); memoryStream.Position = 0; // Save certificate var path = settings.Path; var folder = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(folder)) { Directory.CreateDirectory(folder); } // Set path in finished page. using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { memoryStream.WriteTo(fileStream); } if (settings.ImportInCertificateStore) { log("Importing certificate in My Certificates store"); var certificate = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); thumbprint = certificate.Thumbprint; var x509Store2 = new X509Store(StoreName.My, StoreLocation.CurrentUser); try { x509Store2.Open(OpenFlags.ReadWrite); x509Store2.Add(certificate); x509Store2.Close(); } catch (Exception ex) { errorMessage = string.Format("Failed to import certificate because: {0}", ex.Message); return(false); } } if (years < 30) { log("Certificate is intended for evaluation purposes. It cannot be used to deploy to the market."); } return(true); } catch (Exception ex) { ErrorLog.DumpError(ex); errorMessage = string.Format("Failed to create certificate because {0}.", ex.Message); return(false); } }
private static X509Certificate2 CreateSelfSignedCertificateBasedOnPrivateKey(string commonNameValue, string issuerSubjectName, AsymmetricKeyParameter issuerPrivKey, bool isClientCertificate, int yearsUntilExpiration) { const int keyStrength = 2048; // Generating Random Numbers var random = GetSeededSecureRandom(); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); var extendedKeyUsage = isClientCertificate ? new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth) : new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, extendedKeyUsage); // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name X509Name subjectDN = new X509Name("CN=" + commonNameValue); X509Name issuerDN = new X509Name(issuerSubjectName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For DateTime notBefore = DateTime.UtcNow.Date.AddDays(-7); DateTime notAfter = notBefore.AddYears(yearsUntilExpiration); 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); X509Certificate certificate = certificateGenerator.Generate(signatureFactory); 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 }); var stream = new MemoryStream(); store.Save(stream, new char[0], random); var convertedCertificate = new X509Certificate2( stream.ToArray(), (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); stream.Position = 0; return(convertedCertificate); }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="NativePkcs7EncryptionHandler"/> Klasse. /// </summary> /// <param name="senderCertificate">Das X509-Zertifikat des Absenders (PKCS#12)</param> /// <param name="receiverCertificate">Das X509-Zertifikat des Empfängers</param> /// <param name="oldSenderCertificates">Die abgelaufenen X509-Zertifikate des Absenders</param> public NativePkcs7EncryptionHandler(Pkcs12Store senderCertificate, X509Certificate receiverCertificate, IEnumerable <Pkcs12Store> oldSenderCertificates = null) : this(ConvertToCertificate2(senderCertificate), ConvertToCertificate2(receiverCertificate), oldSenderCertificates?.Select(ConvertToCertificate2)) { }
public static void WriteCertificateAsPem(string name, byte[] rawBytes, string exportPassword, ZipArchive archive) { var a = new Pkcs12Store(); a.Load(new MemoryStream(rawBytes), Array.Empty <char>()); X509CertificateEntry entry = null; AsymmetricKeyEntry key = null; foreach (var alias in a.Aliases) { var aliasKey = a.GetKey(alias.ToString()); if (aliasKey != null) { entry = a.GetCertificate(alias.ToString()); key = aliasKey; break; } } if (entry == null) { throw new InvalidOperationException("Could not find private key."); } var zipEntryCrt = archive.CreateEntry(name + ".crt"); zipEntryCrt.ExternalAttributes = ((int)(FilePermissions.S_IRUSR | FilePermissions.S_IWUSR)) << 16; using (var stream = zipEntryCrt.Open()) using (var writer = new StreamWriter(stream)) { var pw = new PemWriter(writer); pw.WriteObject(entry.Certificate); } var zipEntryKey = archive.CreateEntry(name + ".key"); zipEntryKey.ExternalAttributes = ((int)(FilePermissions.S_IRUSR | FilePermissions.S_IWUSR)) << 16; using (var stream = zipEntryKey.Open()) using (var writer = new StreamWriter(stream)) { var pw = new PemWriter(writer); object privateKey; if (exportPassword != null) { privateKey = new MiscPemGenerator( key.Key, "DES-EDE3-CBC", exportPassword.ToCharArray(), CertificateUtils.GetSeededSecureRandom()) .Generate(); } else { privateKey = key.Key; } pw.WriteObject(privateKey); writer.Flush(); } }
public void Save(CertificateInfo input) { _log.Information("Exporting .pem files to {folder}", _path); try { // Base certificate var certificateExport = input.Certificate.Export(X509ContentType.Cert); var exportString = _pemService.GetPem("CERTIFICATE", certificateExport); // Rest of the chain var chain = new X509Chain(); chain.Build(input.Certificate); for (var i = 1; i < chain.ChainElements.Count; i++) { var chainCertificate = chain.ChainElements[i].Certificate; // Do not include self-signed certificates, root certificates // are supposed to be known already by the client. if (chainCertificate.Subject != chainCertificate.Issuer) { var chainCertificateExport = chainCertificate.Export(X509ContentType.Cert); exportString += _pemService.GetPem("CERTIFICATE", chainCertificateExport); } } // Determine name var name = input.SubjectName.Replace("*", "_"); // Save complete chain File.WriteAllText(Path.Combine(_path, $"{name}-chain.pem"), exportString); // Private key var pkPem = ""; var store = new Pkcs12Store(input.CacheFile.OpenRead(), input.CacheFilePassword.ToCharArray()); var alias = store.Aliases.OfType <string>().FirstOrDefault(p => store.IsKeyEntry(p)); var entry = store.GetKey(alias); var key = entry.Key; if (key.IsPrivate) { pkPem = _pemService.GetPem(entry.Key); } if (!string.IsNullOrEmpty(pkPem)) { File.WriteAllText(Path.Combine(_path, $"{name}-key.pem"), pkPem); } else { _log.Error("Unable to read private key"); } input.StoreInfo.Add(GetType(), new StoreInfo() { Name = PemFilesOptions.PluginName, Path = _path }); } catch (Exception ex) { _log.Error(ex, "Error exporting .pem files to folder"); } }
/// <summary> /// Sign (fill) named field in the document hard way (touch file descriptor, create and close stamper) /// </summary> /// <param name="fileName">PDF file</param> /// <param name="fieldName">Field to be signed</param> /// <param name="reason">Sign reason</param> /// <param name="location">Sign location</param> /// <param name="graphics">Sign graphic</param> /// <param name="certFile">PFX certificate</param> /// <param name="certPassword">password of certificate</param> /// <param name="renderingMode">SignatureRender renderingMode</param> /// <param name="certificationLevel">PdfSignatureAppearance Certification Level</param> /// <returns>Successfull or not</returns> public static bool SignField(string fileName, string fieldName, string reason, string location, Bitmap graphics, string certFile, string certPassword, PdfSignatureAppearance.SignatureRender renderingMode = PdfSignatureAppearance.SignatureRender.GraphicAndDescription, int certificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { bool result = false; try { PdfReader reader = new PdfReader(fileName); if (reader.AcroFields.Fields.ContainsKey(fieldName)) { string tempFile = Path.GetTempFileName(); FileStream fs = new FileStream(tempFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0'); PdfSignatureAppearance psa = GetPSA(fieldName, stamper, graphics, reason, location, renderingMode, certificationLevel); Pkcs12Store store = new Pkcs12Store(new FileStream(certFile, FileMode.Open), certPassword.ToCharArray()); string alias = ""; ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry ake = store.GetKey(alias); foreach (X509CertificateEntry c in store.GetCertificateChain(alias)) { chain.Add(c.Certificate); } RsaPrivateCrtKeyParameters parameters = ake.Key as RsaPrivateCrtKeyParameters; psa.SetCrypto(parameters, chain.ToArray(), null, PdfSignatureAppearance.WINCER_SIGNED); stamper.Close(); reader.Close(); File.Copy(tempFile, fileName, true); result = true; } else { result = false; } } catch (Exception e) { Console.WriteLine(e.Message); result = false; } return(result); }
/// <summary> /// Erstellt ein ein asymmetrisches Schlüsselpaar, ein Passwort für den privaten Teil des Zertifikates und generiert /// aus diesen erstellten Bestandteilen ein Zertifikat entsprechend der übergebenen Schlüsselstärke. Nach Bedarf können die /// Bestandteile (Zertifikat, KeyStore, Passwort) auf dem Dateisystem gespeichert werden /// </summary> /// <param name="hashtype">Algorithmus des Hashtyps</param> /// <param name="antragsteller">Antragssteller (Subject DN)</param> /// <param name="aussteller">Austeller (Issuer DN)</param> /// <param name="passwortKeyStore">Passwort für den KeyStore, ist es leer wird eins geniert, ist es nicht leer wird das übertragene verwendet</param> /// <param name="keyStore">Rückgabe des generierten KeyStores als Objekt</param> /// <param name="gueltigVon">Ab wann ist das Zertifikat gültig</param> /// <param name="gueltiBis">Bis wann ist das Zertifikat gültig</param> /// <param name="keyStrength">Schlüsselstärke</param> /// <param name="zertifikatSpeicherPfad">Soll das Zertifikat auf einem Laufwerk gespeichert werden, wird hier der Ordner angegeben</param> /// <param name="dateiname">Namen der Dateien für das Passwort, das öffentliche Zertifikat und den KeyStore</param> /// <param name="zertifikatImPfadSpeichern">Soll das Zertifikat in dem angegebenen Pfad gespeichert werden (.der)</param> /// <param name="keyStoreImPfadSpeicher">Soll der KeyStore in dem angebeneen Pfad gespeichert werden (.pfx)</param> /// <param name="passwortImPfadSpeichern">Soll das Passwort in dem angegebenen Pfad gespeichert werden (.pas)</param> /// <returns></returns> public static X509Certificate CreateCertificateAndKeyStore(Standards.HashType hashtype, string antragsteller, string aussteller, ref string passwortKeyStore, out Pkcs12Store keyStore, DateTime gueltigVon, DateTime gueltiBis, KeyHelper.KeyStrength keyStrength = KeyHelper.KeyStrength.ks2048, string zertifikatSpeicherPfad = null, string dateiname = null, bool zertifikatImPfadSpeichern = false, bool keyStoreImPfadSpeicher = false, bool passwortImPfadSpeichern = false) { //Erstellen eines Schlüsselpaares: AsymmetricCipherKeyPair schluesselPaar = KeyHelper.CreateAsymmetricKeyPair(keyStrength); //Erstellen eines Passwortes für den privaten Teil des Zertifikates: if (string.IsNullOrEmpty(passwortKeyStore)) { passwortKeyStore = KeyHelper.CreateRSAPasswort(); } //Erstellen des Zertifikates: X509Certificate certificate = CreateX509Certificate(schluesselPaar.Public, schluesselPaar.Private, hashtype, antragsteller, aussteller, gueltigVon, gueltiBis); //Erstelle KeyStore: keyStore = CreatePkcs12Store(certificate, schluesselPaar, antragsteller); //Falls ein Pfad angegeben ist und das Speichern der Zertifikatsinformationen gewünscht ist, werden diese //im Pfad als PKcs12 und DER Format gespeichert, das Passwort falls gewünscht in einer Textfile if (!string.IsNullOrEmpty(zertifikatSpeicherPfad)) { if (string.IsNullOrEmpty(dateiname)) { dateiname = aussteller + "_" + antragsteller + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"); } string speicherPfad = zertifikatSpeicherPfad + "\\" + dateiname; //Speichern des Zertifikates if (zertifikatImPfadSpeichern) { SaveCertAsDER(certificate, speicherPfad); } //Speichern des KeyStores if (keyStoreImPfadSpeicher) { SaveCertAsPkcs12(keyStore, speicherPfad, passwortKeyStore); } //Speichern des Passwortes: if (passwortImPfadSpeichern) { ParseHelper.WriteTextToFile(speicherPfad + ".pas", passwortKeyStore); } } return(certificate); }
/// <summary> /// Konvertierung eines KeyStores in einen Base64String /// </summary> /// <param name="store">KeyStore im PKCS12 Format</param> /// <param name="passwort">Passwort des KeyStores</param> /// <returns></returns> public static string ConvertPkcs12ToBase64String(Pkcs12Store store, string passwort) { return(Convert.ToBase64String(ConvertPkcs12ToByteArray(store, passwort))); }
public CertificateTrustIT(CertificateTrustIntegrationTestFixture fixture) { Server = fixture.StandAlone; Pkcs12 = fixture.Pkcs12; }
public byte[] GenerirajPotpisaniDokument(byte[] document, string documentName, string signingReason, string signingLocation) { try { string alias = ""; List <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>(); var location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath ?? ""); //var destinationPath = $@"Data\{documentName}"; //destinationPath = Path.Combine(location, destinationPath); var destinationPath = iConfig["DocumentDestinationPath"] + documentName; var certPath = @"C:\Users\Crega\Source\Repos\PdfSigner\PdfSigner\bin\Debug\netcoreapp3.0\certifikat.pfx"; certPath = Path.Combine(location, certPath); var cert = File.ReadAllBytes(certPath); Stream certStream = new MemoryStream(cert); Pkcs12Store store = new Pkcs12Store(certStream, "12345".ToCharArray()); // searching for private key foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry pk = store.GetKey(alias); foreach (X509CertificateEntry c in store.GetCertificateChain(alias)) { chain.Add(c.Certificate); } RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters; Stream documentStream = new MemoryStream(document); PdfReader reader = new PdfReader(documentStream); FileStream os = new FileStream(destinationPath, FileMode.Create); StampingProperties sp = new StampingProperties(); iText.Signatures.PdfSigner signer = new iText.Signatures.PdfSigner(reader, os, sp); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(signingReason); appearance.SetLocation(signingLocation); appearance.SetContact("*****@*****.**"); //appearance.SetPageRect(new iText.Kernel.Geom.Rectangle(36, 748, 144, 780)); appearance.SetPageNumber(1); appearance.SetCertificate(chain[0]); // Creating the signature IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain.ToArray(), null, null, null, 0, iText.Signatures.PdfSigner.CryptoStandard.CADES); //MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); os.Close(); certStream.Close(); var documentToReturn = File.ReadAllBytes(destinationPath); File.Delete(destinationPath); return(documentToReturn); } catch (Exception ex) { } return(null); }
public X509Context(Pkcs12Store store) { this.store = store; }
public static Pkcs12Store CreateCert(string commonName, DateTime notBefore, DateTime notAfter, IEnumerable <string> dnsAltNames, IEnumerable <string> ipAddressAltNames, Pkcs12Store signBy) { var keyPairGen = new RsaKeyPairGenerator(); keyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); var keyPair = keyPairGen.GenerateKeyPair(); var certGenerator = new X509V3CertificateGenerator(); certGenerator.SetSubjectDN(new X509Name("CN=" + commonName)); if (signBy == null) { certGenerator.SetIssuerDN(new X509Name("CN=" + commonName)); } else { certGenerator.SetIssuerDN(GetCert(signBy).SubjectDN); } certGenerator.SetSerialNumber(BigInteger.ProbablePrime(64, new Random())); certGenerator.SetNotBefore(notBefore); certGenerator.SetNotAfter(notAfter); certGenerator.SetPublicKey(keyPair.Public); if ((dnsAltNames?.Any() ?? false) || (ipAddressAltNames?.Any() ?? false)) { var alternativeNames = new List <Asn1Encodable>(); alternativeNames.AddRange(dnsAltNames?.Select(name => new GeneralName(GeneralName.DnsName, name)) ?? Enumerable.Empty <Asn1Encodable>()); alternativeNames.AddRange(ipAddressAltNames?.Select(ip => new GeneralName(GeneralName.IPAddress, ip)) ?? Enumerable.Empty <Asn1Encodable>()); certGenerator.AddExtension( X509Extensions.SubjectAlternativeName, false, new DerSequence(alternativeNames.ToArray()) ); } var signatureKeyPair = signBy != null ? new AsymmetricCipherKeyPair(GetCert(signBy).GetPublicKey(), GetKey(signBy)) : keyPair; var signer = new Asn1SignatureFactory("SHA256WITHRSA", signatureKeyPair.Private); var certificate = certGenerator.Generate(signer); return(ToPkcs12(certificate, keyPair.Private)); }
private void cmdOK_Click(object sender, EventArgs e) { X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); IDictionary attrs = new Hashtable(); attrs[X509Name.CN] = txtCN.Text; attrs[X509Name.O] = txtCompany.Text; attrs[X509Name.C] = txtCC.Text; attrs[X509Name.ST] = txtProvince.Text; attrs[X509Name.OU] = txtOU.Text; attrs[X509Name.L] = txtCity.Text; IList ord = new ArrayList(); ord.Add(X509Name.CN); ord.Add(X509Name.O); ord.Add(X509Name.C); ord.Add(X509Name.ST); ord.Add(X509Name.OU); ord.Add(X509Name.L); X509Name CN = new X509Name(ord, attrs); Org.BouncyCastle.X509.X509Certificate newCert; certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random())); certGen.SetIssuerDN(CN); certGen.SetNotAfter(new DateTime(DT.Value.Year, DT.Value.Month, DT.Value.Day, 0, 0, 0, 0)); certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); certGen.SetSubjectDN(CN); CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random; AsymmetricCipherKeyPair keypair; if (txtSPKI.Text == "") { RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator(); keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); keypair = keypairgen.GenerateKeyPair(); certGen.SetPublicKey(keypair.Public); random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random); newCert = certGen.Generate(signatureFactory); } else { RsaPublicKeyStructure rsaPubStructure = RsaPublicKeyStructure.GetInstance(Asn1Object.FromByteArray(File.ReadAllBytes(txtSPKI.Text))); AsymmetricKeyParameter extpublickey = (AsymmetricKeyParameter)(new RsaKeyParameters(false, rsaPubStructure.Modulus, rsaPubStructure.PublicExponent)); certGen.SetPublicKey(extpublickey); RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator(); keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); keypair = keypairgen.GenerateKeyPair(); random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random); newCert = certGen.Generate(signatureFactory); } byte[] PlainCer = newCert.GetEncoded(); SaveFileDialog save = new SaveFileDialog(); if (lstOutput.SelectedIndex == 0) { save.Filter = "Certificate|*.cer"; save.DefaultExt = ".cer"; save.Title = "Save CER file"; } if (lstOutput.SelectedIndex == 1) { save.Filter = "Certificate|*.der"; save.DefaultExt = ".der"; save.Title = "Save DER file"; } if (lstOutput.SelectedIndex == 2) { save.Filter = "Certificate|*.p12"; save.DefaultExt = ".p12"; save.Title = "Save P12 file"; } if (save.ShowDialog(this) != System.Windows.Forms.DialogResult.OK) { return; } if (lstOutput.SelectedIndex == 0) { File.WriteAllBytes(save.FileName, PlainCer); } if (lstOutput.SelectedIndex == 1) { TextWriter txt = new StreamWriter(save.FileName, false, Encoding.ASCII); PemWriter text = new PemWriter(txt); text.WriteObject(newCert); txt.Close(); } if (lstOutput.SelectedIndex == 2) { Pkcs12Store pkcs = new Pkcs12Store(); pkcs.SetCertificateEntry(txtCN.Text, new X509CertificateEntry(newCert)); AsymmetricKeyEntry keyentry = new AsymmetricKeyEntry(keypair.Private); pkcs.SetKeyEntry(txtCN.Text, keyentry, new[] { new X509CertificateEntry(newCert) }); MemoryStream mem = new MemoryStream(); pkcs.Save(mem, txtPassword.Text.ToCharArray(), random); PlainCer = newCert.GetEncoded(); File.WriteAllBytes(save.FileName, mem.GetBuffer()); } this.Close(); }
/// <summary> /// Creates a cert with the connectionstring (token) and stores it in the given cert store. /// </summary> public async static Task WriteAsync(string name, string connectionString, string storeType, string storePath) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentException("Token not found in X509Store and no new token provided!"); } SecureRandom random = new SecureRandom(); KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair(); ArrayList nameOids = new ArrayList(); nameOids.Add(X509Name.CN); ArrayList nameValues = new ArrayList(); nameValues.Add(name); X509Name subjectDN = new X509Name(nameOids, nameValues); X509Name issuerDN = subjectDN; X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); cg.SetIssuerDN(issuerDN); cg.SetSubjectDN(subjectDN); cg.SetNotBefore(DateTime.Now); cg.SetNotAfter(DateTime.Now.AddMonths(12)); cg.SetPublicKey(keys.Public); cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment)); // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and // "hide" it in the instruction code cert extension RSA rsa = RSA.Create(); RSAParameters rsaParams = new RSAParameters(); RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public; rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length]; keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0); rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length]; keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0); rsa.ImportParameters(rsaParams); if (rsa != null) { byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1); if (bytes != null) { cg.AddExtension(X509Extensions.InstructionCode, false, bytes); } else { throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!"); } } // sign the cert with the private key ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random); Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory); // create a PKCS12 store for the cert and its private key X509Certificate2 certificate = null; using (MemoryStream pfxData = new MemoryStream()) { Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); Pkcs12Store pkcsStore = builder.Build(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; string passcode = Guid.NewGuid().ToString(); chain[0] = new X509CertificateEntry(x509); pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain); pkcsStore.Save(pfxData, passcode.ToCharArray(), random); // create X509Certificate2 object from PKCS12 file certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode); // handle each store type differently switch (storeType) { case CertificateStoreType.Directory: { // Add to DirectoryStore using (DirectoryCertificateStore store = new DirectoryCertificateStore()) { store.Open(storePath); X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false); // remove any existing cert with our name from the store foreach (X509Certificate2 cert in certificates) { if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase)) { await store.Delete(cert.Thumbprint).ConfigureAwait(false); } } // add new one await store.Add(certificate).ConfigureAwait(false); } break; } case CertificateStoreType.X509Store: { // Add to X509Store using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); // remove any existing cert with our name from the store foreach (X509Certificate2 cert in store.Certificates) { if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase)) { store.Remove(cert); } } // add new cert to store try { store.Add(certificate); } catch (Exception e) { throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'."); } } break; } default: { throw new Exception($"The requested store type '{storeType}' is not supported. Please change."); } } return; } }
/// <summary> /// Static method used to create a certificate and return as a .net object /// </summary> public X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false) { UserPassword = userPassword ?? String.Empty; // 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)); KeyPair = generator.GenerateKeyPair(); // get a copy of the private key AsymmetricKeyParameter privateKey = KeyPair.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(KeyPair.Public); X509Certificate certificate = x509Generator.Generate(KeyPair.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 DerEncodedCertificate = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // if specified then this add this certificate to the store if (addtoStore) { AddToMyStore(DerEncodedCertificate); } return(DerEncodedCertificate); }
public HyperwaySecureMimeContext( Pkcs12Store store ) : base(new X509Context(store)) { }
public static void DemoServiceAnfrageVerarbeiteAuftrag() { //Laden des Client KeyStores: Pkcs12Store clientkeyStore = CertHelper.LadePkcsStore(zertpfad + "\\" + clientCertDateiname + ".pfx", clientPasswort); rzeLadeRzZertifikatAntwort serviceZertifikatAntwort; //Laden des RzZertifikates: using (FiverxLinkSecurityLib.FiveRxSecurityService.FiveRxLinkSecurityServiceSoapClient client = SecurityServiceComHelper.GetFiveRxServiceSecurityClient(fiveRxServiceAdresse, clientkeyStore, clientPasswort)) { FiverxLinkSecurityLib.FiveRxSecurityService.genericResponseMsg responseladeZertifikat = client.ladeRzZertifikat(new FiverxLinkSecurityLib.FiveRxSecurityService.einParameterRequestMsg()); serviceZertifikatAntwort = ParseHelper.GetObjectFromXML <rzeLadeRzZertifikatAntwort>(responseladeZertifikat.rzeAusgabeDaten); } X509Certificate caCertifikate = CertHelper.ConvertByteArrayToX509Certificate(serviceZertifikatAntwort.rzZertifikat); //Laden des fachliches Dokuments XmlDocument fachlichesDokumentClient = new XmlDocument(); fachlichesDokumentClient.LoadXml(ParseHelper.ReadTextFromFile(pfadAnfrageladeRzVersion)); //Generierung des Serviceanfrage: rzeAnfrage anfrage = ClientHelper.ErstelleRzeAnfrageObjekt(fachlichesDokumentClient, "9998", "303706931", "Testapotheke FiveRxSecurity", "ladeRzVersion", "Musterhersteller", "Mustersoftware", "Musterversion", clientkeyStore, clientPasswort, new SecurityKonfiguration(), caCertifikate); FiverxLinkSecurityLib.FiveRxSecurityService.genericResponseMsg response; using (FiverxLinkSecurityLib.FiveRxSecurityService.FiveRxLinkSecurityServiceSoapClient client = SecurityServiceComHelper.GetFiveRxServiceSecurityClient(fiveRxServiceAdresse, clientkeyStore, clientPasswort)) { FiverxLinkSecurityLib.FiveRxSecurityService.zweiParameterRequestMsg request = new FiverxLinkSecurityLib.FiveRxSecurityService.zweiParameterRequestMsg(); request.rzeEingabeDaten = ParseHelper.GetStringFromXMLObject <rzeAnfrage>(anfrage); request.rzeLadeRzSecurityVersion = "Test"; response = client.verarbeiteAuftrag(request); client.Close(); } //Überprüfung ob Signatur in Ordnung ist: bool istEntschluesselungErfolgreich; bool istSignaturValide; bool istSigniertesXmlValide; X509Certificate signatureCertificate; rzeAntwort serverAntwort = ParseHelper.GetObjectFromXML <rzeAntwort>(response.rzeAusgabeDaten); string xmlAsString = ClientHelper.VerifiziereServerAntwort(serverAntwort.rzDatenBox, clientkeyStore, clientPasswort, out istEntschluesselungErfolgreich, out istSignaturValide, out istSigniertesXmlValide, out signatureCertificate); }
public Boolean Init(ConnectionListener <SNMessage> listener) { if (channel == null) { this._listener = listener; bootstrap = new Bootstrap(); loopGroup = new MultithreadEventLoopGroup(workerThreads); bootstrap.Group(loopGroup); bootstrap.Channel <SocketDatagramChannel>(); UDPClient currClient = this; bootstrap.Handler(new ActionChannelInitializer <SocketDatagramChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (isSecured) { Pkcs12Store keystore = null; if (certificate != null && certificate.Length > 0) { keystore = CertificatesHelper.loadBC(certificate, certificatePassword); } AsyncDtlsClient client = new AsyncDtlsClient(keystore, certificatePassword, null); _clientProtocol = new AsyncDtlsClientProtocol(client, new SecureRandom(), channel, null, currClient, true, ProtocolVersion.DTLSv12); pipeline.AddLast(new DtlsClientHandler(_clientProtocol, this)); } pipeline.AddLast("handler", new SNHandler(listener)); pipeline.AddLast("encoder", new SNEncoder(channel)); pipeline.AddLast(new ExceptionHandler()); })); bootstrap.RemoteAddress(address); try { com.mobius.software.windows.iotbroker.mqtt_sn.net.UDPClient curr = this; Task <IChannel> task = bootstrap.BindAsync(IPEndPoint.MinPort); task.GetAwaiter().OnCompleted(() => { try { channel = task.Result; Task connectTask = channel.ConnectAsync(address); connectTask.GetAwaiter().OnCompleted(() => { if (_clientProtocol == null) { if (channel != null) { listener.Connected(); } else { listener.ConnectFailed(); } } else { startHandhshakeTimer(); _clientProtocol.InitHandshake(null); } }); } catch (Exception) { listener.ConnectFailed(); return; } }); } catch (Exception) { return(false); } } return(true); }
public static void DemoTestAnfrageNARZTestservice() { using (NARZService.FiverxLinkSecurityService_PortTypeClient client = new NARZService.FiverxLinkSecurityService_PortTypeClient()) { NARZService.einParameterRequestMsg anfrageObjectLadeRzSecurityVersion = new NARZService.einParameterRequestMsg(); rzeLadeRzSecurityVersionAnfrage anfrageLadeRzSecurityVersion = ClientHelper.ErstelleRzeLadeRzSecurityVersionAnfrage("9998", "303706931", "Testapotheke FiveRxSecurity", "ladeRzVersion", "Musterhersteller", "Mustersoftware", "Musterversion"); anfrageObjectLadeRzSecurityVersion.rzeEingabeDaten = ParseHelper.GetStringFromXMLObject <rzeLadeRzSecurityVersionAnfrage>(anfrageLadeRzSecurityVersion); NARZService.genericResponseMsg antwortSecurityVersion = client.ladeRzSecurityVersion(anfrageObjectLadeRzSecurityVersion); NARZService.zweiParameterRequestMsg anfrageObjectVerarbeiteAuftrag = new NARZService.zweiParameterRequestMsg(); //Laden des Client KeyStores: Pkcs12Store clientkeyStore = CertHelper.LadePkcsStore(zertpfad + "\\" + clientCertDateiname + ".pfx", clientPasswort); //Laden des Server Zerfifikats (üblich vom Server geladen per Webservice): X509Certificate caCertifikate = CertHelper.Ladex509Certificate(zertpfad + "\\" + rzCertDateiname + ".der"); //Laden des fachliches Dokuments XmlDocument fachlichesDokumentClient = new XmlDocument(); fachlichesDokumentClient.PreserveWhitespace = true; fachlichesDokumentClient.LoadXml(testXmlAnfrage); //Generierung des Serviceanfrage: rzeAnfrage anfrageVerarbeiteAuftrag = ClientHelper.ErstelleRzeAnfrageObjekt(fachlichesDokumentClient, "1111", "111111111", "testapo", "testmethode", "testhersteller", "testsoftware", "testversion", clientkeyStore, clientPasswort, new SecurityKonfiguration(), caCertifikate); anfrageObjectVerarbeiteAuftrag.rzeEingabeDaten = ParseHelper.GetStringFromXMLObject <rzeAnfrage>(anfrageVerarbeiteAuftrag); anfrageObjectVerarbeiteAuftrag.rzeLadeRzSecurityVersion = "Test"; NARZService.genericResponseMsg antwortVerarbeiteAuftrag = client.verarbeiteAuftrag(anfrageObjectVerarbeiteAuftrag); bool istEntschluesselungErfolgreich; bool istSignaturValide; bool istSigniertesXmlValide; X509Certificate signatureCertificate; rzeAntwort serverAntwort = ParseHelper.GetObjectFromXML <rzeAntwort>(antwortVerarbeiteAuftrag.rzeAusgabeDaten); string xmlAsString = ClientHelper.VerifiziereServerAntwort(serverAntwort.rzDatenBox, clientkeyStore, clientPasswort, out istEntschluesselungErfolgreich, out istSignaturValide, out istSigniertesXmlValide, out signatureCertificate); } }
public async Task Save(CertificateInfo input) { _log.Information("Exporting .pem files to {folder}", _path); try { // Determine name var name = input.CommonName.Replace("*", "_"); // Base certificate var certificateExport = input.Certificate.Export(X509ContentType.Cert); var certString = _pemService.GetPem("CERTIFICATE", certificateExport); var chainString = ""; await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-crt.pem"), certString); // Rest of the chain foreach (var chainCertificate in input.Chain) { // Do not include self-signed certificates, root certificates // are supposed to be known already by the client. if (chainCertificate.Subject != chainCertificate.Issuer) { var chainCertificateExport = chainCertificate.Export(X509ContentType.Cert); chainString += _pemService.GetPem("CERTIFICATE", chainCertificateExport); } } // Save complete chain await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-chain.pem"), certString + chainString); await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-chain-only.pem"), chainString); input.StoreInfo.TryAdd( GetType(), new StoreInfo() { Name = PemFilesOptions.PluginName, Path = _path }); // Private key if (input.CacheFile != null) { var pkPem = ""; var store = new Pkcs12Store(input.CacheFile.OpenRead(), input.CacheFilePassword?.ToCharArray()); var alias = store.Aliases.OfType <string>().FirstOrDefault(p => store.IsKeyEntry(p)); if (alias == null) { _log.Warning("No key entries found"); return; } var entry = store.GetKey(alias); var key = entry.Key; if (key.IsPrivate) { pkPem = _pemService.GetPem(entry.Key, _password); } if (!string.IsNullOrEmpty(pkPem)) { await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-key.pem"), pkPem); } else { _log.Warning("No private key found in Pkcs12Store"); } } else { _log.Warning("No private key found in cache"); } } catch (Exception ex) { _log.Error(ex, "Error exporting .pem files to folder"); } }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); // Make a connection to a PreSign servlet to ask to create a document, // then calculate its hash and send it to us HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PRE); request.Method = "POST"; // Upload our self-signed certificate Stream os = request.GetRequestStream(); byte[] data = new byte[256]; int read; using (FileStream fis = new FileStream(CERT, FileMode.Open)) { while ((read = fis.Read(data, 0, data.Length)) != 0) { os.Write(data, 0, read); } } os.Flush(); os.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Use cookies to maintain a session String cookies = response.Headers["Set-Cookie"]; // Receive a hash that needs to be signed Stream istream = response.GetResponseStream(); MemoryStream memoryStream = new MemoryStream(); istream.CopyTo(memoryStream); istream.Close(); byte[] hash = memoryStream.ToArray(); // Load our private key from the key store Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD); // Searching for private key String alias = null; foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry pk = store.GetKey(alias); // Sign the hash received from the server ISigner sig = SignerUtilities.GetSigner("SHA256withRSA"); sig.Init(true, pk.Key); sig.BlockUpdate(hash, 0, hash.Length); data = sig.GenerateSignature(); // Make a connection to the PostSign Servlet request = (HttpWebRequest)WebRequest.Create(POST); request.Headers.Add(HttpRequestHeader.Cookie, cookies.Split(";".ToCharArray(), 2)[0]); request.Method = "POST"; // Upload the signed bytes os = request.GetRequestStream(); os.Write(data, 0, data.Length); os.Flush(); os.Close(); // Receive the signed document response = (HttpWebResponse)request.GetResponse(); istream = response.GetResponseStream(); using (FileStream fos = new FileStream(DEST + RESULT_FILES[0], FileMode.Create)) { data = new byte[256]; while ((read = istream.Read(data, 0, data.Length)) != 0) { fos.Write(data, 0, read); } istream.Close(); } }
/// <summary> /// Imports certificates and keys from a pkcs12-encoded stream. /// </summary> /// <remarks> /// Imports all of the certificates and keys from the pkcs12-encoded stream. /// </remarks> /// <param name="stream">The raw certificate and key data.</param> /// <param name="password">The password to unlock the data.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override void Import(Stream stream, string password) { if (stream == null) { throw new ArgumentNullException("stream"); } if (password == null) { throw new ArgumentNullException("password"); } var pkcs12 = new Pkcs12Store(stream, password.ToCharArray()); var enabledAlgorithms = EnabledEncryptionAlgorithms; X509CertificateRecord record; foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry(alias)) { var chain = pkcs12.GetCertificateChain(alias); var entry = pkcs12.GetKey(alias); int startIndex = 0; if (entry.Key.IsPrivate) { if ((record = dbase.Find(chain[0].Certificate, ImportPkcs12Fields)) == null) { record = new X509CertificateRecord(chain[0].Certificate, entry.Key); record.AlgorithmsUpdated = DateTime.UtcNow; record.Algorithms = enabledAlgorithms; record.IsTrusted = true; dbase.Add(record); } else { record.AlgorithmsUpdated = DateTime.UtcNow; record.Algorithms = enabledAlgorithms; if (record.PrivateKey == null) { record.PrivateKey = entry.Key; } record.IsTrusted = true; dbase.Update(record, ImportPkcs12Fields); } startIndex = 1; } for (int i = startIndex; i < chain.Length; i++) { if ((record = dbase.Find(chain[i].Certificate, X509CertificateRecordFields.Id)) == null) { dbase.Add(new X509CertificateRecord(chain[i].Certificate)); } } } else if (pkcs12.IsCertificateEntry(alias)) { var entry = pkcs12.GetCertificate(alias); if ((record = dbase.Find(entry.Certificate, X509CertificateRecordFields.Id)) == null) { dbase.Add(new X509CertificateRecord(entry.Certificate)); } } } }
/// <summary> /// Antrag versenden /// </summary> /// <param name="application">Antrag</param> /// <param name="p10Data">PKCS#10-Daten</param> /// <param name="certStore">Zertifikat-Speicher für die Bildung der Zertifikatskette und die Abfrage des Empfänger-Zertifikats</param> /// <param name="pfx">Zertifikat für die Verschlüsselung - wenn nicht gesetzt, dann wird ein Erstantrag erstellt</param> /// <returns>Das Ergebnis der Antragstellung</returns> public Task <OstcApplicationResult> SendApplicationAsync([NotNull] OstcAntrag application, [NotNull] Pkcs10Data p10Data, [CanBeNull] IOstcCertificateStore certStore, [CanBeNull] Pkcs12Store pfx) { return(SendApplicationAsync(application, p10Data, certStore, pfx, null)); }
private IList <X509Certificate> GetCertificateChain(Pkcs12Store store, string alias) { return(store.GetCertificateChain(alias) .Select(x => x.Certificate) .ToList()); }
/// <summary> /// Antrag versenden /// </summary> /// <param name="application">Antrag</param> /// <param name="p10Data">PKCS#10-Daten</param> /// <param name="certStore">Zertifikat-Speicher für die Bildung der Zertifikatskette und die Abfrage des Empfänger-Zertifikats</param> /// <param name="pfx">Zertifikat für die Verschlüsselung - wenn nicht gesetzt, dann wird ein Erstantrag erstellt</param> /// <param name="validator">The validator for the OSTC certificate request document</param> /// <returns>Das Ergebnis der Antragstellung</returns> public async Task <OstcApplicationResult> SendApplicationAsync([NotNull] OstcAntrag application, [NotNull] Pkcs10Data p10Data, [CanBeNull] IOstcCertificateStore certStore, [CanBeNull] Pkcs12Store pfx, [CanBeNull] IValidator validator) { var senderId = SenderId.FromBnrOrIk(application.Antragsteller.IK_BN); var applicationData = OstcUtils.Serialize(application, Iso88591); string mimeType; if (pfx == null) { mimeType = "text/xml"; } else { var alias = pfx.Aliases.Cast <string>().FirstOrDefault(pfx.IsKeyEntry); if (alias != null) { var certEntry = pfx.GetCertificate(alias); var keyEntry = pfx.GetKey(alias); var certificate = certEntry.Certificate; var key = keyEntry.Key; if (certStore == null) { throw new ArgumentNullException(nameof(certStore)); } var certChain = certStore.GetChain(certificate).ToList(); Debug.Assert(certChain[0].SubjectDN.Equivalent(certificate.SubjectDN)); certChain.RemoveAt(0); applicationData = OstcUtils.SignData(applicationData, key, certificate, certChain); var receiverCert = certStore.GetCertificate(senderId.CommunicationServerReceiver); applicationData = OstcUtils.EncryptData(applicationData, receiverCert); mimeType = "application/octet-stream"; } else { mimeType = "text/xml"; } } var date = DateTime.ParseExact(application.Antragsinfo.Datum, "dd.MM.yyyy", CultureDe); var p10FileName = $"{senderId.Id}.p10"; var xmlFileName = $"{senderId}_{date:ddMMyyyy}.xml"; var reqSendAppContent = new MultipartFormDataContent { { new StringContent("4000"), "MAX_FILE_SIZE_XML" }, { new ByteArrayContent(applicationData) { Headers = { ContentType = MediaTypeHeaderValue.Parse(mimeType), } }, "xml_Datei", xmlFileName }, { new StringContent("4000"), "MAX_FILE_SIZE_P10" }, { new ByteArrayContent(p10Data.CertRequestDer) { Headers = { ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"), } }, "p10_Datei", p10FileName } }; var requestSendApp = new HttpRequestMessage(HttpMethod.Post, Network.Requests.Upload) { Content = reqSendAppContent, }; var responseSendApp = await _client.SendAsync(requestSendApp); responseSendApp.EnsureSuccessStatusCode(); var responseHtml = DecodeResponse(await responseSendApp.Content.ReadAsStreamAsync()); var responseFileUrl = GetResponseFileUrl(responseHtml); if (responseFileUrl == null) { throw new OstcException("Von der ITSG wurde kein Pfad zu einer Rückmeldungs-Datei geliefert."); } var downloadResponse = await _client.GetAsync(responseFileUrl); downloadResponse.EnsureSuccessStatusCode(); var resultData = await downloadResponse.Content.ReadAsByteArrayAsync(); var resultXml = XDocument.Load(new MemoryStream(resultData)); var trustCenterNode = resultXml .Elements("OSTCAntrag") .Elements("Trustcenter") .FirstOrDefault(); if (trustCenterNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var returnCodeNode = trustCenterNode .Elements("Returncode") .FirstOrDefault(); if (returnCodeNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var returnCode = Convert.ToInt32(returnCodeNode.Value.Trim(), 10); var errorCodeNode = trustCenterNode.Elements("Fehlercode").FirstOrDefault(); if (errorCodeNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var errorCodes = errorCodeNode.Value.Trim() .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => Convert.ToInt32(x.Trim(), 10)) .ToList(); var inputNumberNode = trustCenterNode.Elements("Eingangsnummer").FirstOrDefault(); if (inputNumberNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var inputNumber = inputNumberNode.Value.Trim(); var result = new OstcApplicationResult() { OrderId = inputNumber, ReturnCode = returnCode, ErrorCodes = errorCodes, }; return(result); }
public string CreateAndStoreNewCertificate(string subjectName, string pvkPass, X509Certificate2 issuer, string path = @".\certs\") { var generator = new X509V3CertificateGenerator(); // Generate pseudo random number var randomGen = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGen); // Set certificate serial number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); generator.SetSerialNumber(serialNumber); // Set certificate subject name var subjectDN = new X509Name($"CN={subjectName}"); generator.SetSubjectDN(subjectDN); // Set issuer subject name var issuerDN = new X509Name(issuer.Subject); generator.SetIssuerDN(issuerDN); // Set certificate validity var notBefore = DateTime.UtcNow.Date; generator.SetNotBefore(notBefore); generator.SetNotAfter(notBefore.AddYears(2)); // Generate new RSA key pair for certificate var keyGeneratorParameters = new KeyGenerationParameters(random, RSAKeyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGeneratorParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); // Import public key into generator generator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey); // Get key pair from .net issuer certificate //var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey); var issuerSerialNumber = new BigInteger(issuer.GetSerialNumber()); // Id CA key with serial var caKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, caKeyIdentifier); // Create signature factory to sign new cert ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerKeyPair.Private); // Generate new bouncy castle certificate signed by issuer var newCertificate = generator.Generate(signatureFactory); var store = new Pkcs12Store(); var friendlyName = newCertificate.SubjectDN.ToString().Split('=')[1]; var certificateEntry = new X509CertificateEntry(newCertificate); // Set certificate store.SetCertificateEntry(friendlyName, certificateEntry); // Set private key store.SetKeyEntry( friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); var privatePath = path + $"{friendlyName}.pfx"; var publicPath = path + $"{friendlyName}.cer"; using (var stream = new MemoryStream()) { // Convert bouncy castle cert => .net cert store.Save(stream, pvkPass.ToCharArray(), random); var dotNetCertificate = new X509Certificate2( stream.ToArray(), pvkPass, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Extract public part to store in server storage var publicCert = dotNetCertificate.Export(X509ContentType.Cert); // Extract private parameters to export into .pfx for distribution var privateCert = dotNetCertificate.Export(X509ContentType.Pfx, pvkPass); dotNetCertificate.Reset(); dotNetCertificate.Import(publicCert); // Store public cert info in storage using (var storage = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { storage.Open(OpenFlags.ReadWrite); storage.Add(dotNetCertificate); storage.Close(); } dotNetCertificate.Dispose(); // Write private parameters to .pfx file to install at client File.WriteAllBytes(privatePath, privateCert); File.WriteAllBytes(publicPath, publicCert); } return(privatePath); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } C2_09_SignatureTypes app = new C2_09_SignatureTypes(); app.Sign(SRC, DEST + RESULT_FILES[0], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.NOT_CERTIFIED, "Test 1", "Ghent"); app.Sign(SRC, DEST + RESULT_FILES[1], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, "Test 1", "Ghent"); app.Sign(SRC, DEST + RESULT_FILES[2], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.CERTIFIED_FORM_FILLING, "Test 1", "Ghent"); app.Sign(SRC, DEST + RESULT_FILES[3], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED, "Test 1", "Ghent"); app.AddAnnotation(DEST + RESULT_FILES[0], DEST + RESULT_FILES[4]); app.AddAnnotation(DEST + RESULT_FILES[1], DEST + RESULT_FILES[5]); app.AddAnnotation(DEST + RESULT_FILES[2], DEST + RESULT_FILES[6]); app.AddAnnotation(DEST + RESULT_FILES[3], DEST + RESULT_FILES[7]); app.AddWrongAnnotation(DEST + RESULT_FILES[0], DEST + RESULT_FILES[8]); app.AddText(DEST + RESULT_FILES[0], DEST + RESULT_FILES[9]); app.SignAgain(DEST + RESULT_FILES[0], DEST + RESULT_FILES[10], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); app.SignAgain(DEST + RESULT_FILES[1], DEST + RESULT_FILES[11], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); app.SignAgain(DEST + RESULT_FILES[2], DEST + RESULT_FILES[12], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); app.SignAgain(DEST + RESULT_FILES[3], DEST + RESULT_FILES[13], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); }