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 void WriteCertificateAsPem(byte[] rawBytes, string exportPassword, Stream s) { var a = new Pkcs12Store(); a.Load(new MemoryStream(rawBytes), Array.Empty <char>()); var entry = a.GetCertificate(a.Aliases.Cast <string>().First()); var key = a.Aliases.Cast <string>().Select(a.GetKey).First(x => x != null); using (var writer = new StreamWriter(s, Encoding.ASCII, 1024, leaveOpen: true)) { var pw = new PemWriter(writer); pw.WriteObject(entry.Certificate); object privateKey; if (exportPassword != null) { privateKey = new MiscPemGenerator( key.Key, "AES-128-CBC", exportPassword.ToCharArray(), CertificateUtils.GetSeededSecureRandom()) .Generate(); } else { privateKey = key.Key; } pw.WriteObject(privateKey); writer.Flush(); } }
public static void Main(String[] args) { Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } X509CertificateEntry[] chain = ks.GetCertificateChain(alias); for (int i = 0; i < chain.Length; i++) { X509Certificate cert = chain[i].Certificate; Console.WriteLine("[{0}] {1}", i, cert.SubjectDN); Console.WriteLine(CertificateUtil.GetCRLURL(cert)); } Console.ReadKey(); }
/// <summary> /// To /// </summary> /// <param name="keyStorePath">Path to key store file</param> /// <param name="keyStorePassword">Key store's password</param> /// <returns>Pkcs12 key store object</returns> public Pkcs12Store GetKeyStore(string keyStorePath, string keyStorePassword) { Pkcs12Store keystore = new Pkcs12Store(); // Create Key store keystore.Load(new FileStream(keyStorePath, FileMode.Open), keyStorePassword.ToCharArray()); // Load key using filestream via path and password return(keystore); }
public static void Main(String[] args) { Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyParameter pk = ks.GetKey(alias).Key; ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) { chain.Add(entry.Certificate); } IOcspClient ocspClient = new OcspClientBouncyCastle(); C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, null, 0); }
private static void ValidatePrivateKey(string source, string certificatePassword, byte[] rawData, out AsymmetricKeyEntry pk) { var store = new Pkcs12Store(); store.Load(new MemoryStream(rawData), certificatePassword?.ToCharArray() ?? Array.Empty <char>()); pk = null; foreach (string alias in store.Aliases) { pk = store.GetKey(alias); if (pk != null) { break; } } if (pk == null) { var msg = "Unable to find the private key in the provided certificate from " + source; if (Logger.IsOperationsEnabled) { Logger.Operations(msg); } throw new EncryptionException(msg); } }
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; } } }
private KeyPair FindRightKey() { foreach (X509Certificate2 cert in crypto.Store.Certificates.Select(a => a.X509Certificate2)) { if (cert.HasPrivateKey && cert.FriendlyName == "Hyperledger.Fabric") { byte[] certidata = cert.Export(X509ContentType.Pkcs12, "123"); Pkcs12Store store = new Pkcs12Store(); store.Load(new MemoryStream(certidata), "123".ToCharArray()); AsymmetricKeyEntry parameter = null; List <string> alias = store.Aliases.Cast <string>().ToList(); foreach (string s in alias) { if (store.IsKeyEntry(s)) { parameter = store.GetKey(s); } } if (parameter == null) { return(null); } return(KeyPair.Create(null, parameter.Key)); } } return(null); }
public static X509Certificate ReadCertFromFile(string strCertificatePath, string strCertificatePassword) { try { // Create file stream object to read certificate var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read); // Read certificate using BouncyCastle component var inputKeyStore = new Pkcs12Store(); inputKeyStore.Load(keyStream, strCertificatePassword.ToCharArray()); //Close File stream keyStream.Close(); var keyAlias = inputKeyStore.Aliases.Cast <string>().FirstOrDefault(n => inputKeyStore.IsKeyEntry(n)); // Read Key from Alieases if (keyAlias == null) { throw new NotImplementedException("Alias"); } //Read certificate into 509 format return((X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate); } catch (Exception ex) { Console.WriteLine("So, you wanna make an exception huh! : " + ex.ToString()); Console.ReadKey(); return(null); } }
public static string X509Certificate2ToPEM(X509Certificate2 cert) { try { if (cert.HasPrivateKey) { byte[] pkcsarray = cert.Export(X509ContentType.Pkcs12); if (pkcsarray.Length == 0) { throw new CryptoException("Empty PKCS12 Array"); } X509Certificate certout = null; AsymmetricKeyParameter priv = null; using (MemoryStream ms = new MemoryStream(pkcsarray)) { Pkcs12Store pkstore = new Pkcs12Store(); pkstore.Load(ms, new char[] { }); foreach (string s in pkstore.Aliases.Cast <string>()) { X509CertificateEntry entry = pkstore.GetCertificate(s); if (entry != null) { certout = entry.Certificate; } AsymmetricKeyEntry kentry = pkstore.GetKey(s); if (kentry != null) { priv = kentry.Key; } } if (certout == null) { throw new CryptoException("Certificate not found"); } } using (StringWriter sw = new StringWriter()) { PemWriter pemWriter = new PemWriter(sw); pemWriter.WriteObject(certout); if (priv != null) { pemWriter.WriteObject(priv); } sw.Flush(); return(sw.ToString()); } } X509Certificate c = DotNetUtilities.FromX509Certificate(cert); return(DumpOnePEM(c, null)); // return cert.Export(X509ContentType.SerializedCert).ToUTF8String(); } catch (Exception e) { throw new CryptoException($"Unable to open pkcs12, wrong password?. {e.Message}", e); } }
public static void WriteCertificateAsPem(string name, byte[] rawBytes, string exportPassword, ZipArchive s) { 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."); } using (var stream = s.CreateEntry(name + ".crt").Open()) using (var writer = new StreamWriter(stream)) { var pw = new PemWriter(writer); pw.WriteObject(entry.Certificate); } using (var stream = s.CreateEntry(name + ".key").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 static void Main(String[] args) { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyParameter pk = ks.GetKey(alias).Key; IList <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) { chain.Add(entry.Certificate); } FileStream ins = new FileStream(CRLURL, FileMode.Open); MemoryStream baos = new MemoryStream(); byte[] buf = new byte[1024]; int readedBytes; while ((readedBytes = ins.Read(buf, 0, 1024)) > 0) { baos.Write(buf, 0, readedBytes); } ins.Close(); ICrlClient crlClient = new CrlClientOffline(baos.ToArray()); X509CrlParser crlParser = new X509CrlParser(); X509Crl crl = crlParser.ReadCrl(new FileStream(CRLURL, FileMode.Open)); Console.WriteLine("CRL valid until: " + crl.NextUpdate); Console.WriteLine("Certificate revoked: " + crl.IsRevoked(chain[0])); IList <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(crlClient); C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", crlList, null, null, 0); }
internal static Pkcs12Store LoadCertificatesKeyStore(char[] password) { var keyStore = new Pkcs12Store(); using (var fs = new FileStream(Repository.Instance.CertificatesKeyStore, FileMode.Open)) { keyStore.Load(fs, password); } return(keyStore); }
public Pkcs12Store LoadCAPfx(char[] password) { var keyStore = new Pkcs12Store(); using (var fs = new FileStream(CAKeyStore, FileMode.Open)) { keyStore.Load(fs, password); } return(keyStore); }
public static void Main(String[] args) { Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); String tsaUrl = properties["TSAURL"]; String tsaUser = properties["TSAUSERNAME"]; String tsaPass = properties["TSAPASSWORD"]; Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyParameter pk = ks.GetKey(alias).Key; IList <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) { chain.Add(entry.Certificate); } IOcspClient ocspClient = new OcspClientBouncyCastle(); TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass); C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize(); bool succeeded = false; int estimatedSize = 10300; while (!succeeded) { try { Console.WriteLine("Attempt: " + estimatedSize + " bytes"); C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, tsaClient, estimatedSize); succeeded = true; Console.WriteLine("Succeeded!"); } catch (IOException ioe) { Console.WriteLine("Not succeeded: " + ioe.Message); estimatedSize += 50; } } Console.ReadKey(); }
public static Tuple <X509.X509Certificate, AsymmetricKeyParameter> GetSampleX509Certificate() { var store = new Pkcs12Store(); using (var ms = new MemoryStream(SamplePfx)) store.Load(ms, "mono".ToCharArray()); var alias = store.Aliases.Cast <string>().First(); var cert = store.GetCertificate(alias).Certificate; var privKey = store.GetKey(alias).Key; return(Tuple.Create(cert, privKey)); }
/// <summary> /// Loads the keystore from the <code>Repository.Instance.CertificatesKeyStore</code> /// You shud call <code>Repository.Instance.OpenExistingCertificateAuthority</code> /// before calling this. /// </summary> private void Load() { //load the keystore //check if it exists first if (File.Exists(Repository.Instance.CertificatesKeyStore)) { using (Stream istream = File.Open(Repository.Instance.CertificatesKeyStore, FileMode.Open)) { _store.Load(istream, _password); } RefreshStore(); } }
public ClientCertificateWithKey(byte[] pkcs12data, string password) { if (pkcs12data == null || pkcs12data.Length == 0) { throw new ArgumentException("No PKCS#12 data specified", nameof(pkcs12data)); } var inputKeyStore = new Pkcs12Store(); try { using (var ms = new MemoryStream(pkcs12data)) { inputKeyStore.Load(ms, string.IsNullOrEmpty(password) ? new char[0] : password.ToCharArray()); } } catch (IOException ex) { throw new AuthenticationException("Parsing of the PKCS#12 data failed", ex); } catch (Exception) { throw; } var keyAlias = inputKeyStore.Aliases.Cast <string>().FirstOrDefault(n => inputKeyStore.IsKeyEntry(n)); if (keyAlias == null) { throw new InvalidDataException("No private key found in PKCS12 data"); } var bcert = inputKeyStore.GetCertificate(keyAlias); this.Certificate = new X509Certificate2(bcert.Certificate.GetEncoded()); var ck = inputKeyStore.GetKey(keyAlias); var ecpk = ck.Key as ECPrivateKeyParameters; this.Key = ecpk.D.ToByteArrayUnsigned(); var sb = new StringBuilder(); TextWriter tw = new StringWriter(sb); var pw = new Org.BouncyCastle.OpenSsl.PemWriter(tw); pw.WriteObject(ecpk); this.Key = Encoding.ASCII.GetBytes(sb.ToString()); }
public static Pkcs12Store LoadCAPfx(char[] password) { var keyStore = new Pkcs12Store(); //PasswordWindow window = new PasswordWindow(); //if (window.ShowDialog() == true) { using (var fs = new FileStream(Repository.Instance.CAKeyStore, FileMode.Open)) { keyStore.Load(fs, password); } } return(keyStore); }
public static Tuple <X509Certificate, AsymmetricKeyParameter> GetSampleX509Certificate() { Pkcs12Store store = new Pkcs12Store(); char[] password = "******".ToCharArray(); using (MemoryStream ms = new MemoryStream(SamplePfx)) store.Load(ms, password); string alias = store.Aliases.Cast <string>().First(); X509Certificate cert = store.GetCertificate(alias).Certificate; AsymmetricKeyParameter privKey = store.GetKey(alias).Key; return(Tuple.Create(cert, privKey)); }
public static X509Certificate getCertificadoX509(string arquivoCertificado, string senha, out AsymmetricKeyParameter chavePrivada) { chavePrivada = null; using (FileStream certificadoStream = new FileStream(arquivoCertificado, FileMode.Open, FileAccess.Read)) { Pkcs12Store armazemPkcs12 = new Pkcs12Store(); armazemPkcs12.Load(certificadoStream, senha.ToCharArray()); string certificadoCN = armazemPkcs12.Aliases.Cast <string>().FirstOrDefault(n => armazemPkcs12.IsKeyEntry(n)); //Console.WriteLine("keyAlias => " + certificadoCN); chavePrivada = armazemPkcs12.GetKey(certificadoCN).Key; return((X509Certificate)armazemPkcs12.GetCertificate(certificadoCN).Certificate); } }
private void keyStoreTest( IAsymmetricKeyParameter sKey, IAsymmetricKeyParameter vKey) // throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, UnrecoverableKeyException { // // keystore test // // KeyStore ks = KeyStore.GetInstance("JKS"); // ks.Load(null, null); Pkcs12StoreBuilder ksBuilder = new Pkcs12StoreBuilder(); Pkcs12Store ks = ksBuilder.Build(); // // create the certificate - version 3 // X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name("CN=Test")); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name("CN=Test")); certGen.SetPublicKey(vKey); certGen.SetSignatureAlgorithm("GOST3411withGOST3410"); X509Certificate cert = certGen.Generate(sKey); X509CertificateEntry certEntry = new X509CertificateEntry(cert); // ks.SetKeyEntry("gost", sKey, "gost".ToCharArray(), new X509Certificate[] { cert }); ks.SetKeyEntry("gost", new AsymmetricKeyEntry(sKey), new X509CertificateEntry[] { certEntry }); MemoryStream bOut = new MemoryStream(); ks.Save(bOut, "gost".ToCharArray(), new SecureRandom()); // ks = KeyStore.getInstance("JKS"); ks = ksBuilder.Build(); ks.Load(new MemoryStream(bOut.ToArray(), false), "gost".ToCharArray()); // IAsymmetricKeyParameter gKey = (AsymmetricKeyParameter)ks.GetKey("gost", "gost".ToCharArray()); // AsymmetricKeyEntry gKeyEntry = (AsymmetricKeyEntry) ks.GetKey("gost"); }
private CertificateWithKey Convert(byte[] pfxCertificate) { using (var stream = new MemoryStream(pfxCertificate)) { var store = new Pkcs12Store(); store.Load(stream, Password.ToCharArray()); string alias = store.Aliases.OfType <string>().Single(); X509CertificateEntry certificateEntry = store.GetCertificate(alias); AsymmetricKeyEntry keyEntry = store.GetKey(alias); var result = new CertificateWithKey { Certificate = new X509Certificate2(certificateEntry.Certificate.GetEncoded()), KeyPair = new AsymmetricCipherKeyPair(certificateEntry.Certificate.GetPublicKey(), keyEntry.Key) }; return(result); } }
// This reads a certificate from a file. // Thanks to: http://blog.softwarecodehelp.com/2009/06/23/CodeForRetrievePublicKeyFromCertificateAndEncryptUsingCertificatePublicKeyForBothJavaC.aspx public static X509Certificate ReadCertFromFile(string strCertificatePath, string strCertificatePassword, out AsymmetricKeyParameter key) { key = null; // Create file stream object to read certificate using (var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read)) { // Read certificate using BouncyCastle component var inputKeyStore = new Pkcs12Store(); inputKeyStore.Load(keyStream, strCertificatePassword.ToCharArray()); var keyAlias = inputKeyStore.Aliases.Cast <string>().FirstOrDefault(n => inputKeyStore.IsKeyEntry(n)); // Read Key from Aliases if (keyAlias == null) { throw new NotImplementedException("Alias"); } key = inputKeyStore.GetKey(keyAlias).Key; //Read certificate into 509 format return((X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate); } }
private X509Certificate2 OpenCertificateStore(Stream stream) { Pkcs12Store store = new Pkcs12Store(); store.Load(stream, new char[] { }); var keyAlias = store.Aliases.Cast <string>().SingleOrDefault(a => store.IsKeyEntry(a)); var key = (RsaPrivateCrtKeyParameters)store.GetKey(keyAlias).Key; var bouncyCertificate = store.GetCertificate(keyAlias).Certificate; var certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCertificate)); var parameters = DotNetUtilities.ToRSAParameters(key); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(parameters); certificate = RSACertificateExtensions.CopyWithPrivateKey(certificate, rsa); return(certificate); }
public static void Main(String[] args) { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyParameter pk = ks.GetKey(alias).Key; ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) { chain.Add(entry.Certificate); } ICrlClient crlClient = new CrlClientOnline("https://crl.cacert.org/revoke.crl"); IList <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(crlClient); C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", crlList, null, null, 0); }
internal static Pkcs12Store LoadPkcs12Store(string basename, string password, CertificateType certtype) { string privateOutputPath = null; if (certtype == CertificateType.AuthorityCertificate) { privateOutputPath = AuthorityPrivateCertificatesPath; } else if (certtype == CertificateType.ServerCertificate) { privateOutputPath = ServerPrivateCertificatesPath; } else { privateOutputPath = UserPrivateCertificatesPath; } var store = new Pkcs12Store(); using (Stream stream = new FileStream( privateOutputPath + basename + ".p12", FileMode.Open, FileAccess.Read)) { try { store.Load(stream, password.ToCharArray()); } catch (System.Exception) { store = null; } stream.Close(); } return(store); }
public bool Init(string authentication_certificate_path, string authentication_certificate_password) { AuthenticationCertificatePrivateKey = null; AuthenticationCertificateCertificate = null; try { FileStream Cert = new FileStream(authentication_certificate_path, FileMode.Open, FileAccess.Read); var p12 = new Pkcs12Store(); p12.Load(Cert, authentication_certificate_password.ToCharArray()); foreach (string alias in p12.Aliases) { if (p12.IsKeyEntry(alias)) { AuthenticationCertificatePrivateKey = p12.GetKey(alias).Key; break; } } foreach (string alias in p12.Aliases) { X509CertificateEntry entry = p12.GetCertificate(alias); if (VerifyPivateAndPublicKey(entry.Certificate.GetPublicKey(), AuthenticationCertificatePrivateKey)) { AuthenticationCertificateCertificate = p12.GetCertificate(alias).Certificate; } } } catch (Exception ex) { return(false); } return(true); }
/// <summary> /// Returns the encrypted Base64 string of the certificate chain+key. Subject is a string containing the name of the owner etc. /// /// Example usage: /// /// var res = TryParseNemID (File.ReadAllBytes ($PATH$)); /// if (res.Success) /// do stuff /// /// </summary> public static (bool Success, string Base64, string Subject, string TemporaryPassword) TryParseNemID(byte[] raw, bool keepPassword = false, bool generateTemporaryPassword = false, string certificatePassword = null) { try { string ascii = System.Text.Encoding.ASCII.GetString(raw); var ex = new Regex("pkcs12=\"(?<data>[A-Za-z0-9+/=\\s]*?)\";", RegexOptions.Multiline); bool isHTML = ex.IsMatch(ascii); //Assume the file was a NemID HTML file. string base64; if (keepPassword) { base64 = isHTML ? ex.Match(ascii).Groups["data"].ToString().Replace("\n", "") : Convert.ToBase64String(raw); return(true, base64, null, null); } var inputKeyStore = new Pkcs12Store(); if (isHTML) { string data = ex.Match(ascii).Groups["data"].ToString().Replace("\n", ""); var bytes = Convert.FromBase64String(data); using (var keyStream = new MemoryStream(bytes)) { inputKeyStore.Load(keyStream, certificatePassword == null ? new char[0] : certificatePassword.ToCharArray()); } } else { using (var keyStream = new MemoryStream(raw)) { inputKeyStore.Load(keyStream, certificatePassword == null ? new char[0] : certificatePassword.ToCharArray()); } } string keyAlias = inputKeyStore.Aliases.Cast <string> ().FirstOrDefault(inputKeyStore.IsKeyEntry); if (keyAlias == null) { throw new NotImplementedException("Alias"); } Org.BouncyCastle.X509.X509Certificate certificate = inputKeyStore.GetCertificate(keyAlias).Certificate; var certf = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate)); string subject = certf.Subject; if (generateTemporaryPassword) { string temporaryPassword = "******"; using (var ms = new MemoryStream()) { inputKeyStore.Save(ms, temporaryPassword.ToCharArray(), new SecureRandom()); return(true, Convert.ToBase64String(ms.ToArray()), subject, temporaryPassword); } } base64 = isHTML ? ex.Match(ascii).Groups["data"].ToString().Replace("\n", "") : Convert.ToBase64String(raw); return(true, base64, subject, null); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine(ex.InnerException); } return(false, null, null, null); }