public GetCertificate ( string alias ) : |
||
alias | string | |
return |
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" }); }
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); }
/// <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); } } }
private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime? requestTimestamp = null) { var signCertAlias = signCertificate.Aliases.Cast<string>().First(signCertificate.IsKeyEntry); var signCertEntry = signCertificate.GetCertificate(signCertAlias); var signCert = signCertEntry.Certificate; var signPkEntry = signCertificate.GetKey(signCertAlias); var signPk = signPkEntry.Key; string digestName; if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id) { digestName = "SHA1"; } else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id) { digestName = "SHA256"; } else { throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}"); } var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id; var digest = DigestUtilities.CalculateDigest(digestName, data); var signedAttrs = new Dictionary<object, object>() { { CmsAttributeTableParameter.Digest, digest } }; if (requestTimestamp.HasValue) { var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime()))); signedAttrs.Add(signTimestamp.AttrType, signTimestamp); } var signedAttrGen = new DefaultSignedAttributeTableGenerator(); var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs); var generator = new CmsSignedDataGenerator(); generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null); var signedData = generator.Generate(new CmsProcessableByteArray(data), true); return signedData.GetEncoded(); }
internal static void SignWithPkcs12KeyStore(string keyStore, string password, string input, string output) { if (String.IsNullOrEmpty(keyStore)) { throw new ArgumentNullException("keyStore"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } if (String.IsNullOrEmpty(input)) { throw new ArgumentNullException("input"); } if (String.IsNullOrEmpty(output)) { throw new ArgumentNullException("output"); } if (!File.Exists(keyStore)) { throw new FileNotFoundException("Keystore is not found or is not a file: " + keyStore, keyStore); } if (!File.Exists(input)) { throw new FileNotFoundException("Input pdf not found: " + input, input); } try { var store = new Pkcs12Store(File.OpenRead(keyStore), password.ToCharArray()); var pKey = store.Aliases .Cast<string>() .FirstOrDefault(store.IsKeyEntry); var key = store.GetKey(pKey).Key; var chain = new[] { store.GetCertificate(pKey).Certificate }; var reader = new PdfReader(input); using (var stamper = PdfStamper.CreateSignature(reader, File.OpenWrite(output), '\0', null, true)) { var sigAppearance = stamper.SignatureAppearance; //Note:note the order of things here SetSigPosition(sigAppearance, reader.AcroFields.GetSignatureNames().Count); SetSigText(sigAppearance, chain); SetSigCryptoFromCipherParam(sigAppearance, key, chain); } } catch (Exception exception) { throw new Exception("Error while signing pdf file: " + exception.Message, exception); } }
/// <summary> /// Imports certificates and keys from a pkcs12-encoded stream. /// </summary> /// <remarks> /// Imports all of the certificates and keys from the pkcs12-encoded stream. /// </remarks> /// <param name="stream">The raw certificate and key data.</param> /// <param name="password">The password to unlock the data.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override void Import (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ()); var enabledAlgorithms = EnabledEncryptionAlgorithms; X509CertificateRecord record; foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry (alias)) { var chain = pkcs12.GetCertificateChain (alias); var entry = pkcs12.GetKey (alias); int startIndex = 0; if (entry.Key.IsPrivate) { if ((record = dbase.Find (chain[0].Certificate, ImportPkcs12Fields)) == null) { record = new X509CertificateRecord (chain[0].Certificate, entry.Key); record.AlgorithmsUpdated = DateTime.UtcNow; record.Algorithms = enabledAlgorithms; record.IsTrusted = true; dbase.Add (record); } else { record.AlgorithmsUpdated = DateTime.UtcNow; record.Algorithms = enabledAlgorithms; if (record.PrivateKey == null) record.PrivateKey = entry.Key; record.IsTrusted = true; dbase.Update (record, ImportPkcs12Fields); } startIndex = 1; } for (int i = startIndex; i < chain.Length; i++) { if ((record = dbase.Find (chain[i].Certificate, X509CertificateRecordFields.Id)) == null) dbase.Add (new X509CertificateRecord (chain[i].Certificate)); } } else if (pkcs12.IsCertificateEntry (alias)) { var entry = pkcs12.GetCertificate (alias); if ((record = dbase.Find (entry.Certificate, X509CertificateRecordFields.Id)) == null) dbase.Add (new X509CertificateRecord (entry.Certificate)); } } }
private void GetEdIdFromCertificate(string fn, string password) { var pkcs12 = new Pkcs12Store(File.Open(fn, FileMode.Open), password.ToCharArray()); var bcCert = pkcs12.GetCertificate("KeyContainer"); var uids = ((X509Name)bcCert.Certificate.SubjectDN).GetValues(X509Name.UID); EdID = (string)uids.ToArray()[0]; }