public Startup() { Pkcs12Store pkcs12 = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open, FileAccess.Read), pfxPassword.ToArray()); string keyAlias = null; foreach (string name in pkcs12.Aliases) { if (pkcs12.IsKeyEntry(name)) { keyAlias = name; break; } } AsymmetricKeyParameter key = pkcs12.GetKey(keyAlias).Key; X509CertificateEntry[] ce = pkcs12.GetCertificateChain(keyAlias); List<X509Certificate> chain = new List<X509Certificate>(ce.Length); foreach (var c in ce) { chain.Add(c.Certificate); } stamper = new Stamper() { CertChain = chain, PrivateKey = key, Stamp = iTextSharp.text.Image.GetInstance(stampImage) }; }
public void ProcessCert(string certificado, string password) { //First we'll read the certificate file Stream fs = new FileStream(certificado, FileMode.Open, FileAccess.Read); Pkcs12Store pk12 = new Pkcs12Store(fs, (password ?? "").ToCharArray()); //then Iterate throught certificate entries to find the private key entry /*foreach (string al in pk12.Aliases) { if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate) { alias = al; break; } }*/ string alias = pk12.Aliases.Cast<string>().FirstOrDefault(al => pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate); //IEnumerator i = pk12.Aliases.GetEnumerator(); //while (i.MoveNext()) //{ // alias = ((string)i.Current); // if (pk12.IsKeyEntry(alias)) // break; //} fs.Close(); Akp = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); //X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length]; Chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) Chain[k] = ce[k].Certificate; }
public static X509Certificate2 GenerateSelfSigned(TimeSpan lifetime) { Guid guid = Guid.NewGuid(); DateTime now = DateTime.UtcNow; SecureRandom rand = new SecureRandom(); //Generate a key pair RsaKeyPairGenerator keyGen = new RsaKeyPairGenerator(); keyGen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(rand, 1024)); AsymmetricCipherKeyPair key = keyGen.GenerateKeyPair(); //Generate a certificate X509Name dn = new X509Name("CN=" + guid.ToString()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetIssuerDN(dn); certGen.SetSerialNumber(new BigInteger(1, guid.ToByteArray())); certGen.SetSignatureAlgorithm("SHA1WITHRSA"); certGen.SetSubjectDN(dn); certGen.SetPublicKey(key.Public); certGen.SetNotBefore(now); certGen.SetNotAfter(now.Add(lifetime)); Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(key.Private); //Save it as pkcs12 MemoryStream p12Stream = new MemoryStream(); Pkcs12Store p12 = new Pkcs12Store(); p12.SetKeyEntry("sts", new AsymmetricKeyEntry(key.Private), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) }); p12.Save(p12Stream, p12TmpPwd.ToCharArray(), rand); //Load the pkcs12 as .Net Certificate return new X509Certificate2(p12Stream.ToArray(), p12TmpPwd, X509KeyStorageFlags.DefaultKeySet); }
public static void SaveToFile( X509Certificate newCert, AsymmetricCipherKeyPair kp, string FilePath, string CertAlias, string Password) { var newStore = new Pkcs12Store(); var certEntry = new X509CertificateEntry(newCert); newStore.SetCertificateEntry( CertAlias, certEntry ); newStore.SetKeyEntry( CertAlias, new AsymmetricKeyEntry(kp.Private), new[] { certEntry } ); using (var certFile = File.Create(FilePath)) { newStore.Save( certFile, Password.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator()) ); } }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="BouncyCastlePkcs7EncryptionHandler"/> 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 BouncyCastlePkcs7EncryptionHandler(Pkcs12Store senderCertificate, X509Certificate receiverCertificate, IEnumerable<Pkcs12Store> oldSenderCertificates = null) { _senderCertificate = senderCertificate; _receiverCertificate = receiverCertificate; _allSenderCertificates = (oldSenderCertificates ?? new Pkcs12Store[0]).Concat(new[] { senderCertificate }).Reverse().ToList(); }
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); }
public async Task <StatusMessage> RevokeCertificate(ILog log, ManagedCertificate managedCertificate) { // get current PFX, extract DER bytes try { var pkcs = new Org.BouncyCastle.Pkcs.Pkcs12Store(File.Open(managedCertificate.CertificatePath, FileMode.Open), "".ToCharArray()); var certAliases = pkcs.Aliases.GetEnumerator(); certAliases.MoveNext(); var certEntry = pkcs.GetCertificate(certAliases.Current.ToString()); var certificate = certEntry.Certificate; // revoke certificate var der = certificate.GetEncoded(); await _acme.RevokeCertificate(der, RevocationReason.Unspecified, null); } catch (Exception exp) { return(new StatusMessage { IsOK = false, Message = $"Failed to revoke certificate: {exp.Message}" }); } return(new StatusMessage { IsOK = true, Message = "Certificate revoked" }); }
/// <summary> /// Public constructor for a Pkcs certificate, takes in values to describe it's state. /// </summary> /// <param name="password">The value used to secure (encrypt) the private key with the certificate</param> /// <param name="keypair">An object used for manipulating/accessing the public and private key of a certificate</param> /// <param name="cert">An easy to manipulate version of an X509 certificate</param> /// <param name="store">A store of Pkcs12 certificates used to store and manipulate certificat chains and key associations</param> public PkcsCertificate(string password ,AsymmetricCipherKeyPair keypair, Org.BouncyCastle.X509.X509Certificate cert, Pkcs12Store store) { this.Password = password; this.Keypair = keypair; this.X509Certificate = cert; this.PkcsStore = store; // this is not the best place to do this }
public static void WritePkcs12(RsaPrivateCrtKeyParameters privKey, Org.BouncyCastle.X509.X509Certificate certificate, string password, Stream stream) { Pkcs12Store store = new Pkcs12Store(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = new X509CertificateEntry(certificate); store.SetKeyEntry("privateKey", new AsymmetricKeyEntry(privKey), chain); store.Save(stream, password.ToCharArray(), new SecureRandom()); }
///// <summary> ///// Construct a new KeyStoreWrapper for the supplied keystore. ///// </summary> ///// <param name="keyStore">The keystore</param> //public KeyStoreWrapper(Pkcs12Store keyStore) //{ // KeyStore = keyStore; //} /// <summary> /// Construct a new KeyStoreWrapper for the supplied keystore, keystore file and keystore password. /// </summary> /// <param name="keyStore">The keystore</param> /// <param name="fKeyStore">The keystore file</param> /// <param name="cPassword">The keystore password</param> public KeyStoreWrapper(String fKeyStore, char[] cPassword) { if (File.Exists(fKeyStore)) KeyStore = X509Utils.LoadCertificatesKeyStore(cPassword); else KeyStore = new Pkcs12Store(); KeyStoreFile = fKeyStore; Password = cPassword; }
private static X509Certificate[] constructChain(Pkcs12Store pkcs12Store, string alias) { var certificateChains = pkcs12Store.GetCertificateChain(alias); var chain = new X509Certificate[certificateChains.Length]; for (var k = 0; k < certificateChains.Length; ++k) chain[k] = certificateChains[k].Certificate; return chain; }
public static void ExportPKCS12(String path, String alias, AsymmetricKeyParameter privKey, char[] password, params X509Certificate[] certs) { var keyStore = new Pkcs12Store(); keyStore.SetKeyEntry(alias, new AsymmetricKeyEntry(privKey), WrapX509Certificates(certs)); using (var fs = new FileStream(path, FileMode.Create)) { keyStore.Save(fs, password, Repository.Srand); } }
/// <summary> /// Load the text to display /// </summary> protected override string LoadText() { if (password == null) { password = PasswordDialog.Ask(); } if (password == null) return string.Empty; var store = new Pkcs12Store(new MemoryStream(Load()), password.ToCharArray()); return string.Join(", " + Environment.NewLine, store.Aliases.Cast<string>()); }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="Pkcs7EncryptionHandler"/> 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 Pkcs7EncryptionHandler(Pkcs12Store senderCertificate, X509Certificate receiverCertificate, IEnumerable<Pkcs12Store> oldSenderCertificates = null) { #if NET45 var senderCert = ConvertToCertificate2(senderCertificate); var recCert = ConvertToCertificate2(receiverCertificate); var oldSenderCerts = oldSenderCertificates?.Select(ConvertToCertificate2); _encryptionHandler = new NativePkcs7EncryptionHandler(senderCert, recCert, oldSenderCerts); #else _encryptionHandler = new BouncyCastlePkcs7EncryptionHandler(senderCertificate, receiverCertificate, oldSenderCertificates); #endif }
/// <summary> /// Reads A Personal Information Exchange File. /// </summary> /// <param name="pfxPath">Certificate file's path</param> /// <param name="pfxPassword">Certificate file's password</param> public static PfxData ReadCertificate(string pfxPath, string pfxPassword) { using (var stream = new FileStream(pfxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var pkcs12Store = new Pkcs12Store(stream, pfxPassword.ToCharArray()); var alias = findThePublicKey(pkcs12Store); var asymmetricKeyParameter = pkcs12Store.GetKey(alias).Key; var chain = constructChain(pkcs12Store, alias); return new PfxData { X509PrivateKeys = chain, PublicKey = asymmetricKeyParameter }; } }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="Pkcs7EncryptionHandler"/> 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 Pkcs7EncryptionHandler(X509Certificate2 senderCertificate, X509Certificate2 receiverCertificate, IEnumerable<X509Certificate2> oldSenderCertificates = null) { #if NET45 _encryptionHandler = new NativePkcs7EncryptionHandler(senderCertificate, receiverCertificate, oldSenderCertificates); #else var senderCert = new Pkcs12Store(new MemoryStream(senderCertificate.Export(X509ContentType.Pkcs12)), new char[0]); var receiverCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(receiverCertificate.RawData); var oldSenderCerts = oldSenderCertificates?.Select(cert => new Pkcs12Store(new MemoryStream(cert.Export(X509ContentType.Pkcs12)), new char[0])); _encryptionHandler = new BouncyCastlePkcs7EncryptionHandler(senderCert, receiverCert, oldSenderCerts); #endif }
public static X509Certificate2 GenerateSelfSignedCert() { var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); const string signatureAlgorithm = "SHA1WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var subjectDN = new X509Name("CN=simpletorrent"); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); var notBefore = DateTime.UtcNow.Date.AddHours(-24); var notAfter = notBefore.AddYears(1000); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); const int strength = 4096; var keyGenerationParameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = subjectKeyPair; var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random); var store = new Pkcs12Store(); string friendlyName = certificate.SubjectDN.ToString(); var certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); string password = "******"; var stream = new MemoryStream(); store.Save(stream, password.ToCharArray(), random); //mono bug #1660 fix -> convert to definite-length encoding byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray()); var convertedCertificate = new X509Certificate2( pfx, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return convertedCertificate; }
private static string findThePublicKey(Pkcs12Store pkcs12Store) { var alias = string.Empty; foreach (var entry in pkcs12Store.Aliases.Cast<string>().Where(entry => pkcs12Store.IsKeyEntry(entry) && pkcs12Store.GetKey(entry).Key.IsPrivate)) { alias = entry; break; } if (string.IsNullOrEmpty(alias)) throw new InvalidOperationException("Provided certificate is invalid."); return alias; }
public static X509Certificate2 GenerateNewCertificate(string name) { var kpGen = new RsaKeyPairGenerator(); kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certificateName = new X509Name("CN=" + name); BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(serialNumber); gen.SetSubjectDN(certificateName); gen.SetIssuerDN(certificateName); gen.SetNotAfter(DateTime.Now.AddYears(100)); gen.SetNotBefore(DateTime.Now.AddDays(-1)); gen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); gen.SetPublicKey(keyPair.Public); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public), new GeneralNames(new GeneralName(certificateName)), serialNumber)); X509Certificate newCert = gen.Generate(keyPair.Private); var newStore = new Pkcs12Store(); var certEntry = new X509CertificateEntry(newCert); newStore.SetCertificateEntry( Environment.MachineName, certEntry ); newStore.SetKeyEntry( Environment.MachineName, new AsymmetricKeyEntry(keyPair.Private), new[] {certEntry} ); var memoryStream = new MemoryStream(); newStore.Save( memoryStream, new char[0], new SecureRandom(new CryptoApiRandomGenerator()) ); return new X509Certificate2(memoryStream.ToArray()); }
static void Cert(string path, string password, out AsymmetricKeyParameter akp, out Org.BouncyCastle.X509.X509Certificate[] chain) { string alias = null; Pkcs12Store pk12; //First we'll read the certificate file pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), password.ToCharArray()); //then Iterate throught certificate entries to find the private key entry IEnumerator i = pk12.Aliases.GetEnumerator(); while (i.MoveNext()) { alias = ((string)i.Current); if (pk12.IsKeyEntry(alias)) break; } akp = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) chain[k] = ce[k].Certificate; }
/// <summary> /// Loads the keystore from the <code>Repository.Instance.CertificatesKeyStore</code> /// You shud call <code>Repository.Instance.OpenExistingCertificateAuthority</code> /// before calling this. /// </summary> /// <param name="password">password for the keystore</param> public KeyStoreViewModel(char[] password, String path) { if (!Repository.Instance.OpenExistingCertificateAuthority(path, password)) { throw new Exception("Unable to open KeyStore. Invalid keystore directory"); } Name = Path.GetFileName(path); ReadOnlyKeyStore = false; _password = password; _listItems.Clear(); var storeBuilder = new Pkcs12StoreBuilder(); _store = storeBuilder.Build(); _x509CertViewModel = new X509CertViewModel((alias, cert, keypair) => { AddEntry(alias, cert, keypair); ShowCertificateGenerator = false; }); Load(); }
public void XmlDSigRsaKSPackage() { Directory.CreateDirectory(DestDir); String filename = "xfa.signed.package.pdf"; String output = DestDir + filename; MemoryStream ks = new MemoryStream(); using(FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) { byte[] buffer = new byte[reader.Length]; reader.Read(buffer, 0, (int)reader.Length); ks.Write(buffer, 0, buffer.Length); ks.Position = 0; } Pkcs12Store store = new Pkcs12Store(ks, PASSWORD.ToCharArray()); String alias = ""; List<X509Certificate> chain = new List<X509Certificate>(); // 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; SignPackageWithCertificate(Src, output, XfaXpathConstructor.XdpPackage.Template, parameters, chain.ToArray(), DigestAlgorithms.SHA1); String cmp = SaveXmlFromResult(output); Assert.IsTrue(VerifyPackageSignature(cmp), "XmlDSig Verification"); Assert.IsTrue(CompareXmls(cmp, CmpDir + filename.Replace(".pdf", ".xml"))); }
private void ProcessCert() { string alias = null; //First we'll read the certificate file Pkcs12Store pk12 = new Pkcs12Store(new FileStream(Path, FileMode.Open, FileAccess.Read), _password.ToCharArray()); //then Iterate throught certificate entries to find the private key entry foreach (var item in pk12.Aliases) { alias = ((string)item); if (pk12.IsKeyEntry(alias)) break; } _akp = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); _chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) _chain[k] = ce[k].Certificate; }
public void XadesBesRsa() { Directory.CreateDirectory(DestDirBes); String filename = "xfa.signed.bes.pdf"; String output = DestDirBes + filename; MemoryStream ks = new MemoryStream(); using (FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) { byte[] buffer = new byte[reader.Length]; reader.Read(buffer, 0, (int)reader.Length); ks.Write(buffer, 0, buffer.Length); ks.Position = 0; } Pkcs12Store store = new Pkcs12Store(ks, PASSWORD.ToCharArray()); String alias = ""; List<X509Certificate> chain = new List<X509Certificate>(); // 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; SignXades(Src, output, parameters, chain.ToArray(), DigestAlgorithms.SHA1, false); String cmp = SaveXmlFromResult(output); Assert.IsTrue(VerifySignature(cmp), "XmlDSig Verification"); }
internal string UploadCertificateWithPrivateKeyInPKCS12Test(ParametersValidation validationRequest, out StepType stepType, out SoapException exc, out int timeout) { int special; var r = GetCommand <string>("UploadCertificateWithPrivateKeyInPKCS12", UploadCertificateWithPrivateKeyInPKCS12, validationRequest, true, out stepType, out exc, out timeout, out special); if (0 != special) { var pkcs12Binary = (byte[])validationRequest.ValidationRules.First(rule => rule.ParameterName == "CertWithPrivateKey").Value; var passphraseID = validationRequest.ValidationRules.First(rule => rule.ParameterName == "EncryptionPassphraseID").Value; var pkcs12Store = new Org.BouncyCastle.Pkcs.Pkcs12Store(); pkcs12Store.Load(new MemoryStream(pkcs12Binary), ((null != passphraseID) ? "DefaultPassword" : "").ToArray()); m_X509CertificateFromUploadPKCS12 = pkcs12Store.GetCertificate(pkcs12Store.Aliases.OfType <string>().First()).Certificate.GetEncoded(); m_X509CertificateFromUploadPKCS12Alias = (string)validationRequest.ValidationRules.First(rule => rule.ParameterName == "CertificationPathAlias").Value; m_UploadPKCS12 = pkcs12Binary; } return(r); }
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); }
/// <summary> /// Exports the specified stream and password to a pkcs12 encrypted file. /// </summary> /// <remarks> /// Exports the specified stream and password to a pkcs12 encrypted file. /// </remarks> /// <param name="stream">The output stream.</param> /// <param name="password">The password to use to lock the private keys.</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="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var store = new Pkcs12Store (); foreach (var certificate in certs) { if (keys.ContainsKey (certificate)) continue; var alias = certificate.GetCommonName (); if (alias == null) continue; var entry = new X509CertificateEntry (certificate); store.SetCertificateEntry (alias, entry); } foreach (var kvp in keys) { var alias = kvp.Key.GetCommonName (); if (alias == null) continue; var entry = new AsymmetricKeyEntry (kvp.Value); var cert = new X509CertificateEntry (kvp.Key); var chain = new List<X509CertificateEntry> (); chain.Add (cert); store.SetKeyEntry (alias, entry, chain.ToArray ()); } store.Save (stream, password.ToCharArray (), new SecureRandom ()); }
/// <summary> /// Imports certificates and private keys from the specified stream. /// </summary> /// <remarks> /// <para>Imports certificates and private keys from the specified pkcs12 stream.</para> /// </remarks> /// <param name="stream">The stream to import.</param> /// <param name="password">The password to unlock the stream.</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="System.IO.IOException"> /// An error occurred reading the stream. /// </exception> public 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 ()); foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry (alias)) { var chain = pkcs12.GetCertificateChain (alias); var entry = pkcs12.GetKey (alias); for (int i = 0; i < chain.Length; i++) { if (unique.Add (chain[i].Certificate)) certs.Add (chain[i].Certificate); } if (entry.Key.IsPrivate) keys.Add (chain[0].Certificate, entry.Key); } else if (pkcs12.IsCertificateEntry (alias)) { var entry = pkcs12.GetCertificate (alias); if (unique.Add (entry.Certificate)) certs.Add (entry.Certificate); } } }
void LoadPkcs12 (Stream stream, string password) { var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ()); foreach (string alias in pkcs12.Aliases) { if (!pkcs12.IsKeyEntry (alias)) continue; var chain = pkcs12.GetCertificateChain (alias); var key = pkcs12.GetKey (alias); if (!key.Key.IsPrivate || chain.Length == 0) continue; var flags = chain[0].Certificate.GetKeyUsageFlags (); if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0) continue; CheckCertificateCanBeUsedForSigning (chain[0].Certificate); CertificateChain = new X509CertificateChain (); Certificate = chain[0].Certificate; PrivateKey = key.Key; foreach (var entry in chain) CertificateChain.Add (entry.Certificate); break; } if (PrivateKey == null) throw new ArgumentException ("The stream did not contain a private key.", nameof (stream)); }
private async void Button_Import_Click(object sender, RoutedEventArgs e) { StringBuilder contents = new StringBuilder(); StorageFile selectedFile2 = null; FileOpenPicker openPicker = new FileOpenPicker(); openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; openPicker.FileTypeFilter.Add(".pfx"); openPicker.FileTypeFilter.Add(".p12"); if (ApplicationView.Value == ApplicationViewState.Snapped) { if (ApplicationView.TryUnsnap()) { selectedFile2 = await openPicker.PickSingleFileAsync(); } } else { selectedFile2 = await openPicker.PickSingleFileAsync(); } if (selectedFile2 != null) { CredentialPanel cp = new CredentialPanel(); bool foco = cp.Focus(Windows.UI.Xaml.FocusState.Programmatic); CustomDialog customDialog = new CustomDialog(cp, labels.GetString("Etiqueta_peticion_pass")); customDialog.Commands.Add(new UICommand(labels.GetString("Boton_aceptar"))); customDialog.Commands.Add(new UICommand(labels.GetString("Boton_cancelar"))); customDialog.DefaultCommandIndex = 0; customDialog.CancelCommandIndex = 1; IUICommand com = await customDialog.ShowAsync(); if (com.Label.Equals(labels.GetString("Boton_aceptar"))) if (cp.getPassword() != null) using (StreamReader reader = new StreamReader(await selectedFile2.OpenStreamForReadAsync())) { char[] password = cp.getPassword().ToCharArray(); try { store = new Pkcs12Store(reader.BaseStream, password); if (store != null) { await selectedFile2.CopyAsync(localFolder, selectedFile2.Name, NameCollisionOption.ReplaceExisting); storeData = new StoreData(); storeData.LoadData(); _source = storeData.GetGroupsByCategory(); ItemGridView2.ItemsSource = storeData.Collection; EvaluateDeleteButton(storeData); // Le quitamos la extensión al nombre del almacén por coherencia con el borrado, que al pillarlo de la lista no tiene extensión. AfirmaMetroUtils.showMessage(labels.GetString("Info_almacen_importado") + selectedFile2.Name.Replace(selectedFile2.FileType, "") + "\".", "Importación de almacén correcta"); // Lanzamos: var options = new Windows.System.LauncherOptions(); options.DisplayApplicationPicker = true; var file2 = await localFolder.GetFileAsync(selectedFile2.Name); bool success = await Windows.System.Launcher.LaunchFileAsync(file2, options); } } catch { AfirmaMetroUtils.showMessage(labels.GetString("Error_carga_almacen"), "Error en la importación de almacén"); } } } }
internal CertId(AsymmetricKeyParameter pubKey) { this.id = Pkcs12Store.CreateSubjectKeyID(pubKey).GetKeyIdentifier(); }
/// <summary> /// Sets the private key. /// </summary> /// <param name="fs">The fs.</param> /// <param name="passWord">The pass word.</param> private void SetPrivateKey(Stream fs, string passWord) { Pkcs12Store store = new Pkcs12Store(fs, passWord.ToCharArray()); foreach (string n in store.Aliases) { if (store.IsKeyEntry(n)) { AsymmetricKeyEntry asymmetricKey = store.GetKey(n); if (asymmetricKey.Key.IsPrivate) { _ecPrivateKeyParameters = asymmetricKey.Key as ECPrivateKeyParameters; } else { _ecPublicKeyParameters = asymmetricKey.Key as ECPublicKeyParameters; } } } }
public Pkcs12Store LoadCAPfx(char[] password) { var keyStore = new Pkcs12Store(); using (var fs = new FileStream(CAKeyStore, FileMode.Open)) { keyStore.Load(fs, password); } return keyStore; }
public void Save(Stream stream, char[] password, SecureRandom random) { if (stream == null) { throw new ArgumentNullException("stream"); } if (random == null) { throw new ArgumentNullException("random"); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (string text in this.keys.Keys) { byte[] array = new byte[20]; random.NextBytes(array); AsymmetricKeyEntry asymmetricKeyEntry = (AsymmetricKeyEntry)this.keys[text]; DerObjectIdentifier oid; Asn1Encodable asn1Encodable; if (password == null) { oid = PkcsObjectIdentifiers.KeyBag; asn1Encodable = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricKeyEntry.Key); } else { oid = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag; asn1Encodable = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(this.keyAlgorithm, password, array, 1024, asymmetricKeyEntry.Key); } Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (string text2 in asymmetricKeyEntry.BagAttributeKeys) { Asn1Encodable obj = asymmetricKeyEntry[text2]; if (!text2.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { asn1EncodableVector2.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { new DerObjectIdentifier(text2), new DerSet(obj) }) }); } } asn1EncodableVector2.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(text)) }) }); if (asymmetricKeyEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry certificate = this.GetCertificate(text); AsymmetricKeyParameter publicKey = certificate.Certificate.GetPublicKey(); SubjectKeyIdentifier obj2 = Pkcs12Store.CreateSubjectKeyID(publicKey); asn1EncodableVector2.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(obj2) }) }); } asn1EncodableVector.Add(new Asn1Encodable[] { new SafeBag(oid, asn1Encodable.ToAsn1Object(), new DerSet(asn1EncodableVector2)) }); } byte[] derEncoded = new DerSequence(asn1EncodableVector).GetDerEncoded(); ContentInfo contentInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(derEncoded)); byte[] array2 = new byte[20]; random.NextBytes(array2); Asn1EncodableVector asn1EncodableVector3 = new Asn1EncodableVector(new Asn1Encodable[0]); Pkcs12PbeParams pkcs12PbeParams = new Pkcs12PbeParams(array2, 1024); AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(this.certAlgorithm, pkcs12PbeParams.ToAsn1Object()); ISet set = new HashSet(); foreach (string text3 in this.keys.Keys) { X509CertificateEntry certificate2 = this.GetCertificate(text3); CertBag certBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certificate2.Certificate.GetEncoded())); Asn1EncodableVector asn1EncodableVector4 = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (string text4 in certificate2.BagAttributeKeys) { Asn1Encodable obj3 = certificate2[text4]; if (!text4.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { asn1EncodableVector4.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { new DerObjectIdentifier(text4), new DerSet(obj3) }) }); } } asn1EncodableVector4.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(text3)) }) }); if (certificate2[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { AsymmetricKeyParameter publicKey2 = certificate2.Certificate.GetPublicKey(); SubjectKeyIdentifier obj4 = Pkcs12Store.CreateSubjectKeyID(publicKey2); asn1EncodableVector4.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(obj4) }) }); } asn1EncodableVector3.Add(new Asn1Encodable[] { new SafeBag(PkcsObjectIdentifiers.CertBag, certBag.ToAsn1Object(), new DerSet(asn1EncodableVector4)) }); set.Add(certificate2.Certificate); } foreach (string text5 in this.certs.Keys) { X509CertificateEntry x509CertificateEntry = (X509CertificateEntry)this.certs[text5]; if (this.keys[text5] == null) { CertBag certBag2 = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(x509CertificateEntry.Certificate.GetEncoded())); Asn1EncodableVector asn1EncodableVector5 = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (string text6 in x509CertificateEntry.BagAttributeKeys) { if (!text6.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { Asn1Encodable obj5 = x509CertificateEntry[text6]; if (!text6.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { asn1EncodableVector5.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { new DerObjectIdentifier(text6), new DerSet(obj5) }) }); } } } asn1EncodableVector5.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(text5)) }) }); asn1EncodableVector3.Add(new Asn1Encodable[] { new SafeBag(PkcsObjectIdentifiers.CertBag, certBag2.ToAsn1Object(), new DerSet(asn1EncodableVector5)) }); set.Add(x509CertificateEntry.Certificate); } } foreach (Pkcs12Store.CertId key in this.chainCerts.Keys) { X509CertificateEntry x509CertificateEntry2 = (X509CertificateEntry)this.chainCerts[key]; if (!set.Contains(x509CertificateEntry2.Certificate)) { CertBag certBag3 = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(x509CertificateEntry2.Certificate.GetEncoded())); Asn1EncodableVector asn1EncodableVector6 = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (string text7 in x509CertificateEntry2.BagAttributeKeys) { if (!text7.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { asn1EncodableVector6.Add(new Asn1Encodable[] { new DerSequence(new Asn1Encodable[] { new DerObjectIdentifier(text7), new DerSet(x509CertificateEntry2[text7]) }) }); } } asn1EncodableVector3.Add(new Asn1Encodable[] { new SafeBag(PkcsObjectIdentifiers.CertBag, certBag3.ToAsn1Object(), new DerSet(asn1EncodableVector6)) }); } } byte[] derEncoded2 = new DerSequence(asn1EncodableVector3).GetDerEncoded(); ContentInfo contentInfo2; if (password == null) { contentInfo2 = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(derEncoded2)); } else { byte[] str = Pkcs12Store.CryptPbeData(true, algorithmIdentifier, password, false, derEncoded2); EncryptedData encryptedData = new EncryptedData(PkcsObjectIdentifiers.Data, algorithmIdentifier, new BerOctetString(str)); contentInfo2 = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, encryptedData.ToAsn1Object()); } ContentInfo[] info = new ContentInfo[] { contentInfo, contentInfo2 }; byte[] encoded = new AuthenticatedSafe(info).GetEncoded(this.useDerEncoding ? "DER" : "BER"); ContentInfo contentInfo3 = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(encoded)); MacData macData = null; if (password != null) { byte[] array3 = new byte[20]; random.NextBytes(array3); byte[] digest = Pkcs12Store.CalculatePbeMac(OiwObjectIdentifiers.IdSha1, array3, 1024, password, false, encoded); AlgorithmIdentifier algID = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); DigestInfo digInfo = new DigestInfo(algID, digest); macData = new MacData(digInfo, array3, 1024); } Pfx obj6 = new Pfx(contentInfo3, macData); DerOutputStream derOutputStream; if (this.useDerEncoding) { derOutputStream = new DerOutputStream(stream); } else { derOutputStream = new BerOutputStream(stream); } derOutputStream.WriteObject(obj6); }
public void Load(Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromStream(input); Pfx pfx = new Pfx(seq); ContentInfo authSafe = pfx.AuthSafe; bool wrongPkcs12Zero = false; if (password != null && pfx.MacData != null) { MacData macData = pfx.MacData; DigestInfo mac = macData.Mac; AlgorithmIdentifier algorithmID = mac.AlgorithmID; byte[] salt = macData.GetSalt(); int intValue = macData.IterationCount.IntValue; byte[] octets = ((Asn1OctetString)authSafe.Content).GetOctets(); byte[] a = Pkcs12Store.CalculatePbeMac(algorithmID.ObjectID, salt, intValue, password, false, octets); byte[] digest = mac.GetDigest(); if (!Arrays.ConstantTimeAreEqual(a, digest)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } a = Pkcs12Store.CalculatePbeMac(algorithmID.ObjectID, salt, intValue, password, true, octets); if (!Arrays.ConstantTimeAreEqual(a, digest)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } this.keys.Clear(); this.localIds.Clear(); this.unmarkedKeyEntry = null; IList list = Platform.CreateArrayList(); if (authSafe.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets2 = ((Asn1OctetString)authSafe.Content).GetOctets(); AuthenticatedSafe authenticatedSafe = new AuthenticatedSafe((Asn1Sequence)Asn1Object.FromByteArray(octets2)); ContentInfo[] contentInfo = authenticatedSafe.GetContentInfo(); ContentInfo[] array = contentInfo; for (int i = 0; i < array.Length; i++) { ContentInfo contentInfo2 = array[i]; DerObjectIdentifier contentType = contentInfo2.ContentType; byte[] array2 = null; if (contentType.Equals(PkcsObjectIdentifiers.Data)) { array2 = ((Asn1OctetString)contentInfo2.Content).GetOctets(); } else if (contentType.Equals(PkcsObjectIdentifiers.EncryptedData) && password != null) { EncryptedData instance = EncryptedData.GetInstance(contentInfo2.Content); array2 = Pkcs12Store.CryptPbeData(false, instance.EncryptionAlgorithm, password, wrongPkcs12Zero, instance.Content.GetOctets()); } if (array2 != null) { Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(array2); foreach (Asn1Sequence seq2 in asn1Sequence) { SafeBag safeBag = new SafeBag(seq2); if (safeBag.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { list.Add(safeBag); } else if (safeBag.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { this.LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(safeBag.BagValue), safeBag.BagAttributes, password, wrongPkcs12Zero); } else if (safeBag.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { this.LoadKeyBag(PrivateKeyInfo.GetInstance(safeBag.BagValue), safeBag.BagAttributes); } } } } } this.certs.Clear(); this.chainCerts.Clear(); this.keyCerts.Clear(); foreach (SafeBag safeBag2 in list) { CertBag certBag = new CertBag((Asn1Sequence)safeBag2.BagValue); byte[] octets3 = ((Asn1OctetString)certBag.CertValue).GetOctets(); X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(octets3); IDictionary dictionary = Platform.CreateHashtable(); Asn1OctetString asn1OctetString = null; string text = null; if (safeBag2.BagAttributes != null) { foreach (Asn1Sequence asn1Sequence2 in safeBag2.BagAttributes) { DerObjectIdentifier instance2 = DerObjectIdentifier.GetInstance(asn1Sequence2[0]); Asn1Set instance3 = Asn1Set.GetInstance(asn1Sequence2[1]); if (instance3.Count > 0) { Asn1Encodable asn1Encodable = instance3[0]; if (dictionary.Contains(instance2.Id)) { if (!dictionary[instance2.Id].Equals(asn1Encodable)) { throw new IOException("attempt to add existing attribute with different value"); } } else { dictionary.Add(instance2.Id, asn1Encodable); } if (instance2.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { text = ((DerBmpString)asn1Encodable).GetString(); } else if (instance2.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { asn1OctetString = (Asn1OctetString)asn1Encodable; } } } } Pkcs12Store.CertId certId = new Pkcs12Store.CertId(x509Certificate.GetPublicKey()); X509CertificateEntry value = new X509CertificateEntry(x509Certificate, dictionary); this.chainCerts[certId] = value; if (this.unmarkedKeyEntry != null) { if (this.keyCerts.Count == 0) { string text2 = Hex.ToHexString(certId.Id); this.keyCerts[text2] = value; this.keys[text2] = this.unmarkedKeyEntry; } } else { if (asn1OctetString != null) { string key = Hex.ToHexString(asn1OctetString.GetOctets()); this.keyCerts[key] = value; } if (text != null) { this.certs[text] = value; } } } }