public static X509Certificate2 Load(Stream stream, string password) { var loadStore = new Pkcs12Store(); loadStore.Load(stream, password?.ToCharArray()); string keyAlias = loadStore.Aliases.Cast <string> ().FirstOrDefault(loadStore.IsKeyEntry); if (keyAlias == null) { throw new NotImplementedException("Alias"); } var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); var saveStore = builder.Build(); var chain = new X509CertificateEntry(loadStore.GetCertificate(keyAlias).Certificate); saveStore.SetCertificateEntry("Alias", chain); saveStore.SetKeyEntry("Alias", new AsymmetricKeyEntry((RsaPrivateCrtKeyParameters)loadStore.GetKey(keyAlias).Key), new [] { chain }); using (var saveStream = new MemoryStream()) { saveStore.Save(saveStream, new char[0], new SecureRandom()); return(new X509Certificate2(Pkcs12Utilities.ConvertToDefiniteLength(saveStream.ToArray()))); } }
public static X509Certificate2 CreateSelfSignedClientCertificate(string commonNameValue, RavenServer.CertificateHolder certificateHolder, out byte[] certBytes) { var serverCertBytes = certificateHolder.Certificate.Export(X509ContentType.Cert); var readCertificate = new X509CertificateParser().ReadCertificate(serverCertBytes); CreateSelfSignedCertificateBasedOnPrivateKey( commonNameValue, readCertificate.SubjectDN, (certificateHolder.PrivateKey.Key, readCertificate.GetPublicKey()), true, false, 5, out certBytes); ValidateNoPrivateKeyInServerCert(serverCertBytes); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); var serverCert = DotNetUtilities.FromX509Certificate(certificateHolder.Certificate); store.Load(new MemoryStream(certBytes), Array.Empty <char>()); store.SetCertificateEntry(serverCert.SubjectDN.ToString(), new X509CertificateEntry(serverCert)); var memoryStream = new MemoryStream(); store.Save(memoryStream, Array.Empty <char>(), GetSeededSecureRandom()); certBytes = memoryStream.ToArray(); var cert = new X509Certificate2(certBytes, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); return(cert); }
internal void ReplaceServerCertificateAssignmentTest(ParametersValidation validationRequest, out StepType stepType, out SoapException exc, out int timeout) { int special; VoidCommand("ReplaceServerCertificateAssignment", ReplaceServerCertificateAssignment, validationRequest, true, out stepType, out exc, out timeout, out special); if (1 == special) { HTTPSServer.getInstance(true).Run(new X509Certificate2(m_UploadPKCS12), 1000); } if (2 == special) { HTTPSServer.getInstance(true).Run(new X509Certificate2(TestCommon.ReadBinary(TestCommon.TLSCertificate1Uri), "1234"), 1000); } if (3 == special) { HTTPSServer.getInstance(true).Run(new X509Certificate2(m_X509CertificateFromGet), 1000); } if (4 == special) { var keyStore = new Pkcs12StoreBuilder().SetUseDerEncoding(true).Build(); keyStore.SetKeyEntry("KeyAlias", new AsymmetricKeyEntry(m_RSAKeyPair.Private), new[] { new X509CertificateEntry(m_X509CertificateSS) }); using (var stream = new MemoryStream()) { keyStore.Save(stream, "".ToCharArray(), new SecureRandom()); HTTPSServer.getInstance(true).Run(new X509Certificate2(stream.ToArray(), ""), 1000); } } if (-1 == special) { HTTPSServer.getInstance(true).Run(new X509Certificate2(m_UploadPKCS12), -1); } }
public void Save(PFXSaveConfig config, string newCertificate) { TextReader sr = new StringReader(newCertificate); PemReader pemReader = new PemReader(sr); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); List <object> pemChains = new List <object>(); object o; while ((o = pemReader.ReadObject()) != null) { pemChains.Add(o); } X509CertificateEntry[] chain = pemChains.OfType <X509Certificate>().Select(c => new X509CertificateEntry(c)).ToArray(); AsymmetricCipherKeyPair privKey = pemChains.OfType <AsymmetricCipherKeyPair>().FirstOrDefault(); store.SetKeyEntry(config.Alias, new AsymmetricKeyEntry(privKey.Private), chain); FileStream p12file = File.Create(config.Path); store.Save(p12file, config.Password.ToCharArray(), new SecureRandom()); p12file.Close(); }
static byte[] GetPfxCertificateByteArray(ref string certString, ref string privateKey) { byte[] certArray = Convert.FromBase64String(certString); byte[] privateKeyArray = Convert.FromBase64String(privateKey); //Translate to Pkcs#12 var store = new Pkcs12StoreBuilder().Build(); Org.BouncyCastle.X509.X509Certificate certTranslate = new X509CertificateParser().ReadCertificate(certArray); var certEntry = new X509CertificateEntry(certTranslate); var pk = PrivateKeyFactory.CreateKey(privateKeyArray); var keyEntry = new AsymmetricKeyEntry(pk); store.SetKeyEntry("", keyEntry, new X509CertificateEntry[] { certEntry }); MemoryStream stream = new MemoryStream(); store.Save(stream, new char[] { }, new SecureRandom()); stream.Dispose(); //FromString byte[] pfxByteArray = stream.ToArray(); return(pfxByteArray); }
internal static (X509Certificate2, IEnumerable <X509Certificate2>) ParseCertificateAndKey(string certificateWithChain, string privateKey) { IEnumerable <string> pemCerts = ParsePemCerts(certificateWithChain); if (pemCerts.FirstOrDefault() == null) { throw new InvalidOperationException("Certificate is required"); } IEnumerable <X509Certificate2> certsChain = GetCertificatesFromPem(pemCerts.Skip(1)); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); IList <X509CertificateEntry> chain = new List <X509CertificateEntry>(); // note: the seperator between the certificate and private key is added for safety to delinate the cert and key boundary var sr = new StringReader(pemCerts.First() + "\r\n" + privateKey); var pemReader = new PemReader(sr); AsymmetricKeyParameter keyParams = null; object certObject = pemReader.ReadObject(); while (certObject != null) { if (certObject is X509Certificate x509Cert) { chain.Add(new X509CertificateEntry(x509Cert)); } // when processing certificates generated via openssl certObject type is of AsymmetricCipherKeyPair if (certObject is AsymmetricCipherKeyPair keyPair) { certObject = keyPair.Private; } if (certObject is RsaPrivateCrtKeyParameters rsaParameters) { keyParams = rsaParameters; } else if (certObject is ECPrivateKeyParameters ecParameters) { keyParams = ecParameters; } certObject = pemReader.ReadObject(); } if (keyParams == null) { throw new InvalidOperationException("Private key is required"); } store.SetKeyEntry("Edge", new AsymmetricKeyEntry(keyParams), chain.ToArray()); using (var p12File = new MemoryStream()) { store.Save(p12File, new char[] { }, new SecureRandom()); var cert = new X509Certificate2(p12File.ToArray()); return(cert, certsChain); } }
private static string SignEnvelop(string signCert, string password, string envelopCert, string orgData) { var pkcs12StoreBuilder = new Pkcs12StoreBuilder(); var pkcs12Store = pkcs12StoreBuilder.Build(); pkcs12Store.Load(new MemoryStream(Convert.FromBase64String(signCert)), password.ToCharArray()); var aliases = pkcs12Store.Aliases; var enumerator = aliases.GetEnumerator(); enumerator.MoveNext(); var alias = enumerator.Current.ToString(); var privKey = pkcs12Store.GetKey(alias); var x509Cert = pkcs12Store.GetCertificate(alias).Certificate; var sha1Signer = SignerUtilities.GetSigner("SHA1withRSA"); sha1Signer.Init(true, privKey.Key); var gen = new CmsSignedDataGenerator(); gen.AddSignerInfoGenerator(new SignerInfoGeneratorBuilder().Build(new Asn1SignatureFactory("SHA1withRSA", privKey.Key), x509Cert)); gen.AddCertificates(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(new ArrayList { x509Cert }))); var sigData = gen.Generate(new CmsProcessableByteArray(Encoding.UTF8.GetBytes(orgData)), true); var signData = sigData.GetEncoded(); var certificate = DotNetUtilities.FromX509Certificate(new X509Certificate2(Convert.FromBase64String(envelopCert))); var rst = Convert.ToBase64String(EncryptEnvelop(certificate, signData)); return(rst); }
public static void ExportToP12(CngKey key, X509Certificate cert, string outputFile, string password, string name) { // Normalise the name string nName = name.Replace(' ', '_'); // Use the FIPS-140 system prng SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator()); // Build PKCS#12 Pkcs12StoreBuilder p12 = new Pkcs12StoreBuilder(); Pkcs12Store pkcs = p12.Build(); byte[] privateKey = key.Export(CngKeyBlobFormat.EccPrivateBlob); ECPrivateKeyParameters privateParams = EccKeyBlob.UnpackEccPrivateBlob(privateKey); pkcs.SetKeyEntry(nName, new AsymmetricKeyEntry(privateParams), new X509CertificateEntry[] { new X509CertificateEntry(cert) }); Stream stream = new FileStream(outputFile, FileMode.Create); pkcs.Save(stream, password.ToCharArray(), random); stream.Close(); }
public static byte[] ExportPfx(byte[] pemCert, byte[] pemPrivateKey) { var parsedCert = new X509CertificateParser().ReadCertificate(pemCert); using var privateStream = new MemoryStream(pemPrivateKey); using var privateReader = new StreamReader(privateStream); var reader = new PemReader(privateReader); var keyPair = reader.ReadObject() as AsymmetricCipherKeyPair; if (keyPair == null) { throw new Exception("Could not read key pair from provided private key bytes"); } var x509Name = new X509Name(parsedCert.SubjectDN.ToString()); var alias = (x509Name.GetValueList(X509Name.CN)?[0] ?? parsedCert.SubjectDN.ToString()) as string; var store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry(alias, new AsymmetricKeyEntry(keyPair.Private), new[] { new X509CertificateEntry(parsedCert) }); using var ms = new MemoryStream(); store.Save(ms, new char[0], new SecureRandom()); ms.Seek(0, SeekOrigin.Begin); return(ms.ToArray()); }
private void DoTestCertsOnly() { Pkcs12Store pkcs12 = new Pkcs12StoreBuilder().Build(); pkcs12.Load(new MemoryStream(certsOnly, false), null); IsTrue(pkcs12.ContainsAlias("alias")); MemoryStream bOut = new MemoryStream(); pkcs12.Save(bOut, null, Random); pkcs12 = new Pkcs12StoreBuilder().Build(); pkcs12.Load(new MemoryStream(bOut.ToArray(), false), null); IsTrue(pkcs12.ContainsAlias("alias")); try { pkcs12.Load(new MemoryStream(certsOnly, false), "1".ToCharArray()); Fail("no exception"); } catch (IOException e) { IsEquals("password supplied for keystore that does not require one", e.Message); } // TODO Modify environment variables in tests? //System.setProperty(Pkcs12Store.IgnoreUselessPasswordProperty, "true"); //pkcs12.Load(new MemoryStream(certsOnly, false), "1".ToCharArray()); //System.setProperty(Pkcs12Store.IgnoreUselessPasswordProperty, "false"); }
private static void Teste(AsymmetricCipherKeyPair keys) { string certSubjectName = "UShadow_RSA"; var certName = new X509Name("CN=" + certSubjectName); var serialNo = Org.BouncyCastle.Math.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("sha256WithRSA"); 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 }); }
private static X509Certificate2 withPrivateKey(X509Certificate certificate, AsymmetricKeyParameter privateKey) { const string password = "******"; Pkcs12Store store; if (RunTime.IsRunningOnMono) { var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); store = builder.Build(); } else { store = new Pkcs12Store(); } var entry = new X509CertificateEntry(certificate); store.SetCertificateEntry(certificate.SubjectDN.ToString(), entry); store.SetKeyEntry(certificate.SubjectDN.ToString(), new AsymmetricKeyEntry(privateKey), new[] { entry }); using (var ms = new MemoryStream()) { store.Save(ms, password.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator())); return(new X509Certificate2(ms.ToArray(), password, X509KeyStorageFlags.Exportable)); } }
private static void SavePkcs12Certificate(CertificateChainWithPrivateKey certChainWithKey, string?password, string certFilePath, bool chain) { if (File.Exists(certFilePath)) { throw new ArgumentException("Cert file already exists. Please remove it or switch directories."); } var store = new Pkcs12StoreBuilder().Build(); // cert chain var chainLen = 1; if (chain) { chainLen = certChainWithKey.Certificates.Length; } for (var i = 0; i < chainLen; i++) { var cert = certChainWithKey.Certificates[i]; var certEntry = new X509CertificateEntry(cert); store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); } // private key var primaryCert = certChainWithKey.PrimaryCertificate; var keyEntry = new AsymmetricKeyEntry(certChainWithKey.PrivateKey); store.SetKeyEntry(primaryCert.SubjectDN.ToString(), keyEntry, new[] { new X509CertificateEntry(primaryCert) }); using var stream = File.OpenWrite(certFilePath); store.Save(stream, password?.ToCharArray(), new SecureRandom()); }
public StreamDecoder(Stream source, Stream p12, string storePass, string keyPass, bool isBase64) { Pkcs12Store pkcs12Store = new Pkcs12StoreBuilder().Build(); pkcs12Store.Load(p12, storePass.ToCharArray()); string alias = null; foreach (string alias2 in pkcs12Store.Aliases) { if (pkcs12Store.IsKeyEntry(alias2)) { alias = alias2; break; } } if (isBase64) { StreamReader streamReader = new StreamReader(source); b = new MemoryStream(); Base64.Decode(streamReader.ReadToEnd(), b); b.Position = 0L; } else { b = source; } c = pkcs12Store.GetCertificate(alias); d = pkcs12Store.GetKey(alias); }
private void init(string aPfxFilePath, string aPassword) { FileStream fin = new FileStream(aPfxFilePath, FileMode.Open, FileAccess.Read); Pkcs12StoreBuilder storeBuilder = new Pkcs12StoreBuilder(); Pkcs12Store pkcs12Store = storeBuilder.Build(); pkcs12Store.Load(fin, aPassword.ToCharArray()); fin.Close(); IEnumerable aliases = pkcs12Store.Aliases; IEnumerator aliasesEnumerator = aliases.GetEnumerator(); while (aliasesEnumerator.MoveNext()) { string alias = (string)aliasesEnumerator.Current; signingBouncyCert = pkcs12Store.GetCertificate(alias); X509Certificate x509Certificate = signingBouncyCert.Certificate; ECertificate cert = new ECertificate(x509Certificate.GetEncoded()); EKeyUsage eKeyUsage = cert.getExtensions().getKeyUsage(); bool isDigitalSignature = eKeyUsage.isDigitalSignature(); if (isDigitalSignature) { signingBouncyKeyEntry = pkcs12Store.GetKey(alias); signingCertificate = cert; break; } } }
internal static void ExportToP12(CspParameters cspParam, X509Certificate cert, string outputFile, string password, string name) { // Normalise the name string nName = name.Replace(' ', '_'); // Use the FIPS-140 system prng SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator()); // Build PKCS#12 Pkcs12StoreBuilder p12 = new Pkcs12StoreBuilder(); Pkcs12Store pkcs = p12.Build(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParam)) { if (!rsa.CspKeyContainerInfo.Exportable) { throw new CryptoException("Private key not exportable"); } pkcs.SetKeyEntry(nName, new AsymmetricKeyEntry(DotNetUtilities.GetRsaKeyPair(rsa).Private), new X509CertificateEntry[] { new X509CertificateEntry(cert) }); } Stream stream = new FileStream(outputFile, FileMode.Create); pkcs.Save(stream, password.ToCharArray(), random); stream.Close(); }
/// <summary> /// Create a X509Certificate2 with a private key by combining /// a bouncy castle X509Certificate and a private key /// </summary> private static X509Certificate2 CreateCertificateWithPrivateKey( Org.BouncyCastle.X509.X509Certificate certificate, string friendlyName, AsymmetricKeyParameter privateKey, SecureRandom random) { // create pkcs12 store for cert and private key 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(certificate); if (string.IsNullOrEmpty(friendlyName)) { friendlyName = GetCertificateCommonName(certificate); } pkcsStore.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), chain); pkcsStore.Save(pfxData, passcode.ToCharArray(), random); // merge into X509Certificate2 return(CreateCertificateFromPKCS12(pfxData.ToArray(), passcode)); } }
public SHA256WithRSA(string pkcs12path, string password) { using (FileStream fs = new FileStream(pkcs12path, FileMode.Open, FileAccess.Read)) { KeyStore = new Pkcs12StoreBuilder().Build(); KeyStore.Load(fs, password.ToCharArray()); List <string> keys = new List <string>(); foreach (string alias in KeyStore.Aliases) { if (string.IsNullOrEmpty(alias)) { continue; } X509CertificateEntry[] chain = KeyStore.GetCertificateChain(alias); if (chain == null) { continue; } foreach (X509CertificateEntry entry in chain) { X509Certificate cert = entry.Certificate; byte[] encoded = cert.GetEncoded(); string base64cert = Convert.ToBase64String(encoded); keys.Add(base64cert); } Alias = alias; Base64KeyChain = keys.ToArray(); } } }
public static void CreatePfxFile( IReadOnlyList <X509Certificate> certChain, AsymmetricKeyParameter privateKey, string unsecurePassword, Stream output) { new { certChain }.Must().NotBeNullNorEmptyEnumerableNorContainAnyNulls(); new { privateKey }.Must().NotBeNull(); new { privateKey.IsPrivate }.Must().BeTrue(); new { unsecurePassword }.Must().NotBeNullNorWhiteSpace(); new { output }.Must().NotBeNull(); new { output.CanWrite }.Must().BeTrue(); certChain = certChain.OrderCertChainFromLowestToHighestLevelOfTrust(); var store = new Pkcs12StoreBuilder().Build(); var certEntries = new List <X509CertificateEntry>(); foreach (var cert in certChain) { var certEntry = new X509CertificateEntry(cert); certEntries.Add(certEntry); var certSubjectAttributes = cert.GetX509SubjectAttributes(); var certStoreKey = certSubjectAttributes[X509SubjectAttributeKind.CommonName]; store.SetCertificateEntry(certStoreKey, certEntry); } var keyEntry = new AsymmetricKeyEntry(privateKey); var firstCert = certChain.First(); var firstCertSubjectAttributes = firstCert.GetX509SubjectAttributes(); store.SetKeyEntry(firstCertSubjectAttributes[X509SubjectAttributeKind.CommonName], keyEntry, certEntries.ToArray()); store.Save(output, unsecurePassword.ToCharArray(), new SecureRandom()); }
public void IssueClientFromCA() { // get CA string caCn = "MyCA CommonName"; char[] caPass = "******".ToCharArray(); using (System.IO.Stream caCertFile = System.IO.File.OpenRead(string.Format(@"{0}\{1}", _certificatesDir, "MyCAFile.pfx"))) { Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.Load(caCertFile, caPass); Org.BouncyCastle.X509.X509Certificate caCert = store.GetCertificate(caCn).Certificate; Org.BouncyCastle.Crypto.AsymmetricKeyParameter caPrivKey = store.GetKey(caCn).Key; byte[] clientCert = GenerateDsaCertificateAsPkcs12( "My Client FriendlyName", "My Client SubjectName", "GT", new System.DateTime(2011, 9, 19), new System.DateTime(2014, 9, 18), "PFXPASS", caCert, caPrivKey); string saveAS = string.Format(@"{0}\{1}", _certificatesDir, "clientCertFile.pfx"); System.IO.File.WriteAllBytes(saveAS, clientCert); } }
/// <summary> /// Generate Pkcs#12 certificate. /// </summary> /// <param name="privateKey">Asymmetric private key.</param> /// <param name="privateKeyAlias">The alias of private key.</param> /// <param name="namedCerts">Certificate collection with alias set.</param> /// <param name="password">Password.</param> /// <returns></returns> /// <exception cref="Exception"/> public static Pkcs12Store GeneratePkcs12(AsymmetricKeyParameter privateKey, string privateKeyAlias, Dictionary <string, X509Certificate> namedCerts, string password) { if (privateKey is null) { throw new ArgumentNullException(nameof(privateKey)); } if (privateKeyAlias is null) { throw new ArgumentNullException(nameof(privateKeyAlias)); } if (namedCerts is null) { throw new ArgumentNullException(nameof(namedCerts)); } using (MemoryStream ms = new MemoryStream()) { Pkcs12Store store = new Pkcs12StoreBuilder().Build(); List <X509CertificateEntry> certEntries = new List <X509CertificateEntry>(); foreach (KeyValuePair <string, X509Certificate> namedCert in namedCerts) { X509CertificateEntry certEntry = new X509CertificateEntry(namedCert.Value); store.SetCertificateEntry(namedCert.Key, certEntry); certEntries.Add(certEntry); } store.SetKeyEntry(privateKeyAlias, new AsymmetricKeyEntry(privateKey), certEntries.ToArray()); char[] pass = string.IsNullOrWhiteSpace(password) ? null : password.ToCharArray(); store.Save(ms, pass, Common.ThreadSecureRandom.Value); ms.Flush(); return(new Pkcs12Store(ms, pass)); } }
private static byte[] CreatePfxFile(Org.BouncyCastle.X509.X509Certificate certificate, AsymmetricKeyParameter privateKey, string password = null) { // create certificate entry var certEntry = new X509CertificateEntry(certificate); string friendlyName = certificate.SubjectDN.ToString(); // get bytes of private key. PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); byte[] keyBytes = keyInfo.ToAsn1Object().GetEncoded(); var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); var store = builder.Build(); // create store entry store.SetKeyEntry("", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry }); byte[] pfxBytes = null; using (MemoryStream stream = new MemoryStream()) { store.Save(stream, password?.ToCharArray(), new SecureRandom()); pfxBytes = stream.ToArray(); } var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes); return(result); }
/// <summary> /// Builds the PFX with specified friendly name. /// </summary> /// <param name="friendlyName">The friendly name.</param> /// <param name="password">The password.</param> /// <returns>The PFX data.</returns> public byte[] Build(string friendlyName, string password) { var keyPair = LoadKeyPair(); var store = new Pkcs12StoreBuilder().Build(); var entry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, entry); if (FullChain && !certificate.IssuerDN.Equivalent(certificate.SubjectDN)) { var certChain = FindIssuers(); var certChainEntries = certChain.Select(c => new X509CertificateEntry(c)).ToList(); certChainEntries.Add(entry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), certChainEntries.ToArray()); } else { store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), new[] { entry }); } using (var buffer = new MemoryStream()) { store.Save(buffer, password.ToCharArray(), new SecureRandom()); return(buffer.ToArray()); } }
/// <summary> /// Generates pfx from client configuration /// </summary> /// <param name="config">Kuberentes Client Configuration</param> /// <returns>Generated Pfx Path</returns> public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config) { byte[] keyData = null; byte[] certData = null; if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData)) { keyData = Convert.FromBase64String(config.ClientCertificateKeyData); } if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath)) { keyData = File.ReadAllBytes(config.ClientKeyFilePath); } if (keyData == null) { throw new KubeConfigException("certData is empty"); } if (!string.IsNullOrWhiteSpace(config.ClientCertificateData)) { certData = Convert.FromBase64String(config.ClientCertificateData); } if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath)) { certData = File.ReadAllBytes(config.ClientCertificateFilePath); } if (certData == null) { throw new KubeConfigException("certData is empty"); } var cert = new X509CertificateParser().ReadCertificate(new MemoryStream(certData)); object obj; using (var reader = new StreamReader(new MemoryStream(keyData))) { obj = new PemReader(reader).ReadObject(); var key = obj as AsymmetricCipherKeyPair; if (key != null) { var cipherKey = key; obj = cipherKey.Private; } } var rsaKeyParams = (RsaPrivateCrtKeyParameters)obj; var store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(rsaKeyParams), new[] { new X509CertificateEntry(cert) }); using (var pkcs = new MemoryStream()) { store.Save(pkcs, new char[0], new SecureRandom()); return(new X509Certificate2(pkcs.ToArray())); } }
internal static CertContainer IssueSignerCertificate(X509Name dnName, int keySize = DefaultKeySize) { CertContainer issuerCert = IntermediateCa; RsaKeyPairGenerator keyPairGen = new RsaKeyPairGenerator(); keyPairGen.Init(new KeyGenerationParameters(_secureRandom, keySize)); AsymmetricCipherKeyPair keyPair = keyPairGen.GenerateKeyPair(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(issuerCert.Certificate.SubjectDN); certGen.SetNotBefore(DateTime.Now); certGen.SetNotAfter(DateTime.Now.AddYears(1)); certGen.SetSubjectDN(dnName); certGen.SetPublicKey(keyPair.Public); certGen.SetSignatureAlgorithm("SHA256withRSA"); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert.Certificate.GetPublicKey())); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.NonRepudiation | X509KeyUsage.DigitalSignature)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public)); certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth)); // Add CRL endpoint Uri currentBaseUri = new Uri("https://localhost/"); Uri crlUri = new Uri(currentBaseUri, IntermediateCrlPath); GeneralName generalName = new GeneralName(GeneralName.UniformResourceIdentifier, crlUri.ToString()); GeneralNames generalNames = new GeneralNames(generalName); DistributionPointName distPointName = new DistributionPointName(generalNames); DistributionPoint distPoint = new DistributionPoint(distPointName, null, null); certGen.AddExtension(X509Extensions.CrlDistributionPoints, false, new CrlDistPoint(new DistributionPoint[] { distPoint })); // Add OCSP endpoint Uri ocspUri = new Uri(currentBaseUri, OcspPath); AccessDescription ocsp = new AccessDescription(AccessDescription.IdADOcsp, new GeneralName(GeneralName.UniformResourceIdentifier, ocspUri.ToString())); Asn1EncodableVector aiaASN = new Asn1EncodableVector(); aiaASN.Add(ocsp); certGen.AddExtension(X509Extensions.AuthorityInfoAccess, false, new DerSequence(aiaASN)); X509Certificate generatedCert = certGen.Generate(issuerCert.PrivateKey); Pkcs12StoreBuilder pfxBuilder = new Pkcs12StoreBuilder(); Pkcs12Store pfxStore = pfxBuilder.Build(); X509CertificateEntry certEntry = new X509CertificateEntry(generatedCert); pfxStore.SetCertificateEntry(generatedCert.SubjectDN.ToString(), certEntry); pfxStore.SetKeyEntry(generatedCert.SubjectDN + "_key", new AsymmetricKeyEntry(keyPair.Private), new X509CertificateEntry[] { certEntry }); return(new CertContainer(pfxStore, issuerCert.GetIssuerChain(true))); }
public PKCS12KeyStore(string keyAlias, RSAKeyPair keyPair, X509CertificateBase certificate) { m_KeyStore = new Pkcs12StoreBuilder().SetUseDerEncoding(true).Build(); m_KeyStore.SetKeyEntry(keyAlias, new AsymmetricKeyEntry(PrivateKeyFactory.CreateKey(keyPair.PrivateKey)), new[] { new X509CertificateEntry(new X509CertificateParser().ReadCertificate(certificate.GetEncoded())) }); }
public KeyStoreViewModel(SystemX509.StoreName storeName, SystemX509.StoreLocation storeLocation) { var storeBuilder = new Pkcs12StoreBuilder(); _store = storeBuilder.Build(); Name = String.Format("System KeyStore: [{0} : {1}]", storeLocation.ToString(), storeName.ToString()); Load(storeName, storeLocation); }
/// <summary> /// Genera el archivo pfx y devuelve el resultado con su contraseña /// </summary> /// <param name="rutaArchivoCer"></param> /// <param name="rutaArchivoKey"></param> /// <param name="secretArchivoKey"></param> /// <param name="rutaGuardado"></param> /// <param name="nombreArchivoPfx"></param> /// <param name="secretArchivoPfx"></param> /// <param name="conservarArchivo"></param> /// <returns>Pfx</returns> public static CfdiPfx generarArchivoPfx(string rutaArchivoCer, string rutaArchivoKey, string secretArchivoKey, string rutaGuardado, string nombreArchivoPfx, string secretArchivoPfx, Boolean conservarArchivo) { try { string rutaArchivoPfx = Path.Combine(rutaGuardado, nombreArchivoPfx); if (!Directory.Exists(rutaGuardado)) { Directory.CreateDirectory(rutaGuardado); } if (File.Exists(rutaArchivoPfx)) { File.Delete(rutaArchivoPfx); } X509Certificate2 certificado = new X509Certificate2(rutaArchivoCer); Org.BouncyCastle.X509.X509Certificate certificate = DotNetUtilities.FromX509Certificate(certificado); byte[] bytesArchivoKey = File.ReadAllBytes(rutaArchivoKey); AsymmetricKeyParameter privateKey = PrivateKeyFactory.DecryptKey(secretArchivoKey.ToCharArray(), bytesArchivoKey); var certEntry = new X509CertificateEntry(certificate); string friendlyName = certificate.SubjectDN.ToString(); PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); byte[] keyBytes = keyInfo.ToAsn1Object().GetEncoded(); var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); var store = builder.Build(); store.SetKeyEntry("PrivateKeyAlias", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry }); byte[] pfxBytes = null; using (MemoryStream stream = new MemoryStream()) { store.Save(stream, secretArchivoPfx.ToCharArray(), new SecureRandom()); pfxBytes = stream.ToArray(); // Este sirve para la cancelacion } var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes); if (conservarArchivo) { File.WriteAllBytes(rutaArchivoPfx, result); } return(new CfdiPfx(result, secretArchivoPfx)); } catch (Exception ex) { throw ex; } }
/// <summary> /// Build a PFX (PKCS12) store containing the specified certificate and private key. /// </summary> /// <param name="certificatePem"> /// A PEM block containing the certificate data. /// </param> /// <param name="keyPem"> /// A PEM block containing the private key data. /// </param> /// <param name="password"> /// The password to use for protecting the exported data. /// </param> /// <returns> /// A byte array containing the exported data. /// </returns> public static byte[] BuildPfx(string certificatePem, string keyPem, string password) { if (String.IsNullOrWhiteSpace(certificatePem)) { throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'certificateData'.", nameof(certificatePem)); } if (String.IsNullOrWhiteSpace(keyPem)) { throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'keyData'.", nameof(keyPem)); } if (String.IsNullOrWhiteSpace(password)) { throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'password'.", nameof(password)); } List <X509CertificateEntry> chain = new List <X509CertificateEntry>(); AsymmetricCipherKeyPair privateKey = null; foreach (object pemObject in EnumeratePemObjects(password, certificatePem, keyPem)) { if (pemObject is BCX509Certificate certificate) { chain.Add(new X509CertificateEntry(certificate)); } else if (pemObject is AsymmetricCipherKeyPair keyPair) { privateKey = keyPair; } } if (chain.Count == 0) { throw new CryptographicException("Cannot find X.509 certificate in PEM data."); } if (privateKey == null) { throw new CryptographicException("Cannot find private key in PEM data."); } string certificateSubject = chain[0].Certificate.SubjectDN.ToString(); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry(certificateSubject, new AsymmetricKeyEntry(privateKey.Private), chain.ToArray()); using (MemoryStream pfxData = new MemoryStream()) { store.Save(pfxData, password.ToCharArray(), new SecureRandom()); return(pfxData.ToArray()); } }
public static X509Certificate2 LoadFromUnencryptedPEM(string pem) { //Extract certificate var pattern = new Regex(@"^[-]{5}BEGIN CERTIFICATE[-]{5}(?<certificate>([^-]*))[-]{5}END CERTIFICATE[-]{5}", RegexOptions.Multiline); var pvk_pattern = new Regex(@"[-]{5}BEGIN(?<encrypted>( ENCRYPTED)?) PRIVATE KEY[-]{5}(?<key>([^-]*))[-]{5}END( ENCRYPTED)? PRIVATE KEY[-]{5}", RegexOptions.Multiline); if (!pattern.IsMatch(pem)) { throw new ArgumentException("Certificate malformed. (No certitficates found)"); } if (!pvk_pattern.IsMatch(pem)) { throw new ArgumentException("Certificate malformed. (No private key found)"); } //Read all certificates to a jagged byte array MatchCollection mc = pattern.Matches(pem); var certificates = new byte[mc.Count][]; var index = 0; foreach (Match match in mc) { certificates[index] = Convert.FromBase64String(match.Groups["certificate"].ToString().Trim(Environment.NewLine.ToCharArray())); index++; } //If the private key is encrypted (check on "encrypted" group) then that need to be handled in future, probably never. Match pvk_match = pvk_pattern.Match(pem); string pvk = pvk_match.Groups["key"].ToString(); var parser = new X509CertificateParser(); var parsedCertificate = parser.ReadCertificate(Combine(certificates)); var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); var inputKeyStore = builder.Build(); inputKeyStore.SetCertificateEntry("Alias", new X509CertificateEntry(parsedCertificate)); inputKeyStore.SetKeyEntry("Alias", new AsymmetricKeyEntry((RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(pvk))), new [] { new X509CertificateEntry(parsedCertificate) }); string keyAlias = inputKeyStore.Aliases.Cast <string> ().FirstOrDefault(inputKeyStore.IsKeyEntry); if (keyAlias == null) { throw new InvalidKeyException("Alias"); } using (var stream = new MemoryStream()) { //There is no password inputKeyStore.Save(stream, new char[0], new SecureRandom()); return(new X509Certificate2(Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray()))); } }
public static void Main( string[] args) { // Security.addProvider(new BouncyCastleProvider()); // // personal keys // // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( RsaKeyParameters pubKey = new RsaKeyParameters(false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); // RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // intermediate keys. // // RSAPublicKeySpec intPubKeySpec = new RSAPublicKeySpec( RsaKeyParameters intPubKey = new RsaKeyParameters(false, new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16)); // RSAPrivateCrtKeySpec intPrivKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters intPrivKey = new RsaPrivateCrtKeyParameters( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16), new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16), new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16), new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16), new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16), new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16), new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16)); // // ca keys // // RSAPublicKeySpec caPubKeySpec = new RSAPublicKeySpec( RsaKeyParameters caPubKey = new RsaKeyParameters(false, new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16)); // RSAPrivateCrtKeySpec caPrivKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters caPrivKey = new RsaPrivateCrtKeyParameters( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16), new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16), new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16), new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16), new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16), new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16), new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16)); // // set up the keys // // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); // PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec); // PublicKey caPubKey = fact.generatePublic(caPubKeySpec); // PrivateKey intPrivKey = fact.generatePrivate(intPrivKeySpec); // PublicKey intPubKey = fact.generatePublic(intPubKeySpec); // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); X509CertificateEntry[] chain = new X509CertificateEntry[3]; chain[2] = CreateMasterCert(caPubKey, caPrivKey); chain[1] = CreateIntermediateCert(intPubKey, caPrivKey, chain[2].Certificate); chain[0] = CreateCert(pubKey, intPrivKey, intPubKey); // // add the friendly name for the private key // // PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; IDictionary bagAttr = new Hashtable(); // // this is also optional - in the sense that if you leave this // out the keystore will add it automatically, note though that // for the browser to recognise which certificate the private key // is associated with you should at least use the pkcs_9_localKeyId // OID and set it to the same as you do for the private key's // corresponding certificate. // // bagAttr.setBagAttribute( // PKCSObjectIdentifiers.pkcs_9_at_friendlyName, // new DERBMPString("Eric's Key")); // bagAttr.setBagAttribute( // PKCSObjectIdentifiers.pkcs_9_at_localKeyId, // new SubjectKeyIdentifierStructure(pubKey)); bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id, new DerBmpString("Eric's Key")); bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id, new SubjectKeyIdentifierStructure(pubKey)); // // store the key and the certificate chain // // KeyStore store = KeyStore.getInstance("PKCS12", "BC"); // store.load(null, null); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); // // if you haven't set the friendly name and local key id above // the name below will be the name of the key // store.SetKeyEntry("Eric's Key", new AsymmetricKeyEntry(privKey, bagAttr), chain); // FileOutputStream fOut = new FileOutputStream("id.p12"); // // store.store(fOut, passwd); FileStream fOut = File.Create("id.p12"); store.Save(fOut, passwd, new SecureRandom()); fOut.Close(); }