public override void PerformTest() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeKeyPair(); X509Certificate testCert = OcspTestUtil.MakeCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !testCert.Equals(certs[0])) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Object extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } byte[] compareNonce = ((Asn1OctetString) extObj).GetOctets(); if (!AreEqual(compareNonce, sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response parsing - test 1 // OcspResp response = new OcspResp(testResp1); if (response.Status != 0) { Fail("response status not zero."); } BasicOcspResp brep = (BasicOcspResp) response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 1 failed to Verify."); } // // test 2 // SingleResp[] singleResp = brep.Responses; response = new OcspResp(testResp2); if (response.Status != 0) { Fail("response status not zero."); } brep = (BasicOcspResp)response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 2 failed to Verify."); } singleResp = brep.Responses; // // simple response generation // OCSPRespGenerator respGen = new OCSPRespGenerator(); OcspResp resp = respGen.Generate(OCSPRespGenerator.Successful, response.GetResponseObject()); if (!resp.GetResponseObject().Equals(response.GetResponseObject())) { Fail("response fails to match"); } doTestECDsa(); doTestRsa(); doTestIrregularVersionReq(); }
/// <summary> /// Decides if the given attribute certificate should be selected. /// </summary> /// <param name="obj">The attribute certificate to be checked.</param> /// <returns><code>true</code> if the object matches this selector.</returns> public bool Match( object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } IX509AttributeCertificate attrCert = obj as IX509AttributeCertificate; if (attrCert == null) { return(false); } if (this.attributeCert != null && !this.attributeCert.Equals(attrCert)) { return(false); } if (serialNumber != null && !attrCert.SerialNumber.Equals(serialNumber)) { return(false); } if (holder != null && !attrCert.Holder.Equals(holder)) { return(false); } if (issuer != null && !attrCert.Issuer.Equals(issuer)) { return(false); } if (attributeCertificateValid != null && !attrCert.IsValid(attributeCertificateValid.Value)) { return(false); } if (targetNames.Count > 0 || targetGroups.Count > 0) { Asn1OctetString targetInfoExt = attrCert.GetExtensionValue( X509Extensions.TargetInformation); if (targetInfoExt != null) { TargetInformation targetinfo; try { targetinfo = TargetInformation.GetInstance( X509ExtensionUtilities.FromExtensionValue(targetInfoExt)); } catch (Exception) { return(false); } Targets[] targetss = targetinfo.GetTargetsObjects(); if (targetNames.Count > 0) { bool found = false; for (int i = 0; i < targetss.Length && !found; i++) { Target[] targets = targetss[i].GetTargets(); for (int j = 0; j < targets.Length; j++) { GeneralName targetName = targets[j].TargetName; if (targetName != null && targetNames.Contains(targetName)) { found = true; break; } } } if (!found) { return(false); } } if (targetGroups.Count > 0) { bool found = false; for (int i = 0; i < targetss.Length && !found; i++) { Target[] targets = targetss[i].GetTargets(); for (int j = 0; j < targets.Length; j++) { GeneralName targetGroup = targets[j].TargetGroup; if (targetGroup != null && targetGroups.Contains(targetGroup)) { found = true; break; } } } if (!found) { return(false); } } } } return(true); }
private void doTestECDsa() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeECKeyPair(); X509Certificate testCert = OcspTestUtil.MakeECDsaCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest(new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withECDSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !certs[0].Equals(testCert)) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest(new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withECDSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Encodable extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } if (!AreEqual(((Asn1OctetString)extObj).GetOctets(), sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response generation // BasicOcspRespGenerator respGen = new BasicOcspRespGenerator(signKP.Public); respGen.AddResponse(id, CertificateStatus.Good); respGen.Generate("SHA1withECDSA", signKP.Private, chain, DateTime.UtcNow); }
public virtual bool Match( object obj) { X509Crl c = obj as X509Crl; if (c == null) { return(false); } if (dateAndTime != null) { DateTime dt = dateAndTime.Value; DateTime tu = c.ThisUpdate; DateTimeObject nu = c.NextUpdate; if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0) { return(false); } } if (issuers != null) { X509Name i = c.IssuerDN; bool found = false; foreach (X509Name issuer in issuers) { if (issuer.Equivalent(i, true)) { found = true; break; } } if (!found) { return(false); } } if (maxCrlNumber != null || minCrlNumber != null) { Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber); if (extVal == null) { return(false); } IBigInteger cn = CrlNumber.GetInstance( X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue; if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0) { return(false); } if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0) { return(false); } } DerInteger dci = null; try { Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator); if (bytes != null) { dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes)); } } catch (Exception) { return(false); } if (dci == null) { if (DeltaCrlIndicatorEnabled) { return(false); } } else { if (CompleteCrlEnabled) { return(false); } if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0) { return(false); } } if (issuingDistributionPointEnabled) { Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint); if (issuingDistributionPoint == null) { if (idp != null) { return(false); } } else { if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint)) { return(false); } } } return(true); }
public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); string newLine = Platform.NewLine; stringBuilder.Append(" Version: ").Append(Version).Append(newLine); stringBuilder.Append(" IssuerDN: ").Append(IssuerDN).Append(newLine); stringBuilder.Append(" This update: ").Append(ThisUpdate).Append(newLine); stringBuilder.Append(" Next update: ").Append(NextUpdate).Append(newLine); stringBuilder.Append(" Signature Algorithm: ").Append(SigAlgName).Append(newLine); byte[] signature = GetSignature(); stringBuilder.Append(" Signature: "); stringBuilder.Append(Hex.ToHexString(signature, 0, 20)).Append(newLine); for (int i = 20; i < signature.Length; i += 20) { int length = Math.Min(20, signature.Length - i); stringBuilder.Append(" "); stringBuilder.Append(Hex.ToHexString(signature, i, length)).Append(newLine); } X509Extensions extensions = c.TbsCertList.Extensions; if (extensions != null) { IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator(); if (enumerator.MoveNext()) { stringBuilder.Append(" Extensions: ").Append(newLine); } do { DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.Current; X509Extension extension = extensions.GetExtension(derObjectIdentifier); if (extension.Value != null) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(extension.Value); stringBuilder.Append(" critical(").Append(extension.IsCritical).Append(") "); try { if (derObjectIdentifier.Equals(X509Extensions.CrlNumber)) { stringBuilder.Append(new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine); } else if (derObjectIdentifier.Equals(X509Extensions.DeltaCrlIndicator)) { stringBuilder.Append("Base CRL: " + new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine); } else if (derObjectIdentifier.Equals(X509Extensions.IssuingDistributionPoint)) { stringBuilder.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine); } else if (derObjectIdentifier.Equals(X509Extensions.CrlDistributionPoints)) { stringBuilder.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine); } else if (derObjectIdentifier.Equals(X509Extensions.FreshestCrl)) { stringBuilder.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine); } else { stringBuilder.Append(derObjectIdentifier.Id); stringBuilder.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object)).Append(newLine); } } catch (Exception) { stringBuilder.Append(derObjectIdentifier.Id); stringBuilder.Append(" value = ").Append("*****").Append(newLine); } } else { stringBuilder.Append(newLine); } }while (enumerator.MoveNext()); } ISet revokedCertificates = GetRevokedCertificates(); if (revokedCertificates != null) { foreach (X509CrlEntry item in revokedCertificates) { stringBuilder.Append(item); stringBuilder.Append(newLine); } } return(stringBuilder.ToString()); }
public bool Match(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } IX509AttributeCertificate iX509AttributeCertificate = obj as IX509AttributeCertificate; if (iX509AttributeCertificate == null) { return(false); } if (this.attributeCert != null && !this.attributeCert.Equals(iX509AttributeCertificate)) { return(false); } if (this.serialNumber != null && !iX509AttributeCertificate.SerialNumber.Equals(this.serialNumber)) { return(false); } if (this.holder != null && !iX509AttributeCertificate.Holder.Equals(this.holder)) { return(false); } if (this.issuer != null && !iX509AttributeCertificate.Issuer.Equals(this.issuer)) { return(false); } if (this.attributeCertificateValid != null && !iX509AttributeCertificate.IsValid(this.attributeCertificateValid.Value)) { return(false); } if (this.targetNames.Count > 0 || this.targetGroups.Count > 0) { Asn1OctetString extensionValue = iX509AttributeCertificate.GetExtensionValue(X509Extensions.TargetInformation); if (extensionValue != null) { TargetInformation instance; try { instance = TargetInformation.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)); } catch (Exception) { bool result = false; return(result); } Targets[] targetsObjects = instance.GetTargetsObjects(); if (this.targetNames.Count > 0) { bool flag = false; int num = 0; while (num < targetsObjects.Length && !flag) { Target[] targets = targetsObjects[num].GetTargets(); for (int i = 0; i < targets.Length; i++) { GeneralName targetName = targets[i].TargetName; if (targetName != null && this.targetNames.Contains(targetName)) { flag = true; break; } } num++; } if (!flag) { return(false); } } if (this.targetGroups.Count <= 0) { return(true); } bool flag2 = false; int num2 = 0; while (num2 < targetsObjects.Length && !flag2) { Target[] targets2 = targetsObjects[num2].GetTargets(); for (int j = 0; j < targets2.Length; j++) { GeneralName targetGroup = targets2[j].TargetGroup; if (targetGroup != null && this.targetGroups.Contains(targetGroup)) { flag2 = true; break; } } num2++; } if (!flag2) { return(false); } return(true); } } return(true); }
/// <summary> /// Read CA private key file from .key or pfx file /// Read data from certificate request file .csr /// Generate signed certificate request file .cer /// </summary> /// <param name="signedCERFile"></param> /// <param name="privateKeyFile"></param> /// <param name="v"></param> /// <param name="password"></param> private async void GenerateCerFile(string certRequestFile, string privateKeyFile, string generateSignedCertificateFile, string password, string friendlyName, DateTime startDate, DateTime endDate) { #region LoadCertificate // read public & private key from file AsymmetricKeyParameter privateKey = null; AsymmetricKeyParameter publicKey = null; System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate = null; Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = null; // Ovo NE radi //issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2( // privateKeyFile, // password // ); // Ovo RADI issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2( privateKeyFile, password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable ); // This doesn't work for selfsign certificate //bool isOK = issuerCertificate.Verify(); bool isHasPrivateKey = issuerCertificate.HasPrivateKey; DateTime noAfter = issuerCertificate.NotAfter; DateTime noBefore = issuerCertificate.NotBefore; X509ExtensionCollection x509extensions = issuerCertificate.Extensions; int errorNum = 0; X509CertificateParser parser = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData); BasicConstraints basicConstraints = null; bool isCa = false; Asn1OctetString str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19")); if (str != null) { basicConstraints = BasicConstraints.GetInstance( X509ExtensionUtilities.FromExtensionValue(str)); if (basicConstraints != null) { isCa = basicConstraints.IsCA(); } } if (!isCa) { errorNum++; Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n"; tbOutputMessageBox.Foreground = bckForeground; } // This doesn't work for selfsign certificate //if (!isOK) //{ // errorNum++; // Brush bckForeground = tbOutputMessageBox.Foreground; // tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); // tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n"; // tbOutputMessageBox.Foreground = bckForeground; //} if (!isHasPrivateKey) { errorNum++; Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "File with CA certificate DOES NOT have a private key." + "\n"; tbOutputMessageBox.Foreground = bckForeground; } if (noBefore > startDate) { errorNum++; Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "File with CA certificate start date: " + startDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n"; tbOutputMessageBox.Foreground = bckForeground; } if (noAfter < endDate) { errorNum++; Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "File with CA certificate end date: " + endDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n"; tbOutputMessageBox.Foreground = bckForeground; } if (errorNum > 0) { Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "File with CA certificate has error!!!" + "\n"; tbOutputMessageBox.Foreground = bckForeground; return; } bool isOk = issuerCertificate.Verify(); AsymmetricCipherKeyPair issuerKeyPairTmp = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey); privateKey = issuerKeyPairTmp.Private; publicKey = issuerKeyPairTmp.Public; issuerCertificateX509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData()); issuerCertificateX509.Verify(publicKey); Org.BouncyCastle.X509.X509Certificate x509 = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate); x509.Verify(publicKey); x509.CheckValidity(startDate); #endregion // Read certificate request .csr file Pkcs10CertificationRequest cerRequest = null; try { String input_data = File.ReadAllText(certRequestFile); StringReader sr = new StringReader(input_data); PemReader pr = new PemReader(sr); cerRequest = (Pkcs10CertificationRequest)pr.ReadObject(); tbOutputMessageBox.Text += "Verify file with certificate request : " + certRequestFile + "\n"; bool requestIsOK = cerRequest.Verify(); if (requestIsOK) { tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " is OK." + "\n"; } else { tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " NOT valid." + "\n"; return; } } catch (Exception ex) { var metroWindow = (Application.Current.MainWindow as MetroWindow); await metroWindow.ShowMessageAsync("Info Warning", "ERROR reading certificate request file (.csr)" + "\n" + "Error: " + ex.Source + " " + ex.Message, MessageDialogStyle.Affirmative); return; } Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate( cerRequest, x509, issuerKeyPairTmp, startDate, endDate); try { File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded()); tbOutputMessageBox.Text += "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n"; signedRequestFileNamePath = generateSignedCertificateFile; btnContinue.IsEnabled = true; } catch (Exception) { tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n"; } #region Public Key //try //{ // var store = new Pkcs12Store(); // string friendlyName1 = issuerCertificateX509.SubjectDN.ToString(); // var certificateEntry = new X509CertificateEntry(issuerCertificateX509); // store.SetCertificateEntry(friendlyName1, certificateEntry); // store.SetKeyEntry(friendlyName1, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry }); // var stream = new MemoryStream(); // var random1 = GetSecureRandom(); // store.Save(stream, "password".ToCharArray(), random1); // //Verify that the certificate is valid. // var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); // //Write the file. // File.WriteAllBytes(generateSignedCertificateFile, stream.ToArray()); // File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded()); // //using (TextWriter tw = new StreamWriter(outputPublicKeyName)) // //{ // // PemWriter pw = new PemWriter(tw); // // pw.WriteObject(subjectKeyPair.Public); // // tw.Flush(); // //} // tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n"; //} //catch (Exception ex) //{ // var metroWindow = (Application.Current.MainWindow as MetroWindow); // await metroWindow.ShowMessageAsync("Info Warning", // "ERROR creating certificate private key file (.key)" + "\n" + // "Error: " + ex.Source + " " + ex.Message, // MessageDialogStyle.Affirmative); // return; //} //StringBuilder publicKeyStrBuilder = new StringBuilder(); //PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder)); //publicKeyPemWriter.WriteObject(genCert.GetPublicKey()); //publicKeyPemWriter.Writer.Flush(); //string publicKey = publicKeyStrBuilder.ToString(); //try //{ // using (TextWriter tw = new StreamWriter(generateSignedCertificateFile)) // { // PemWriter pw = new PemWriter(tw); // pw.WriteObject(genCert.GetPublicKey()); // tw.Flush(); // } // tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n"; //} //catch (Exception ex) //{ // var metroWindow = (Application.Current.MainWindow as MetroWindow); // await metroWindow.ShowMessageAsync("Info Warning", // "ERROR creating certificate private key file (.key)" + "\n" + // "Error: " + ex.Source + " " + ex.Message, // MessageDialogStyle.Affirmative); // return; //} #endregion Public Key }
// public void setBagAttribute( // DERObjectIdentifier oid, // DEREncodable attribute) // { // pkcs12Attributes.put(oid, attribute); // pkcs12Ordering.addElement(oid); // } // // public DEREncodable getBagAttribute( // DERObjectIdentifier oid) // { // return (DEREncodable)pkcs12Attributes.get(oid); // } // // public Enumeration getBagAttributeKeys() // { // return pkcs12Ordering.elements(); // } public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" [0] Version: ").Append(this.Version).Append(nl); buf.Append(" SerialNumber: ").Append(this.SerialNumber).Append(nl); buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl); buf.Append(" Start Date: ").Append(this.NotBefore).Append(nl); buf.Append(" Final Date: ").Append(this.NotAfter).Append(nl); buf.Append(" SubjectDN: ").Append(this.SubjectDN).Append(nl); buf.Append(" Public Key: ").Append(this.GetPublicKey()).Append(nl); buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl); byte[] sig = this.GetSignature(); buf.Append(" Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl); for (int i = 20; i < sig.Length; i += 20) { int len = System.Math.Min(20, sig.Length - i); buf.Append(" ").Append(Hex.ToHexString(sig, i, len)).Append(nl); } X509Extensions extensions = c.TbsCertificate.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" Extensions: \n"); } do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object obj = X509ExtensionUtilities.FromExtensionValue(ext.Value); buf.Append(" critical(").Append(ext.IsCritical).Append(") "); try { if (oid.Equals(X509Extensions.BasicConstraints)) { buf.Append(BasicConstraints.GetInstance(obj)); } else if (oid.Equals(X509Extensions.KeyUsage)) { buf.Append(KeyUsage.GetInstance(obj)); } else if (oid.Equals(MiscObjectIdentifiers.NetscapeCertType)) { buf.Append(new NetscapeCertType((DerBitString)obj)); } else if (oid.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl)) { buf.Append(new NetscapeRevocationUrl((DerIA5String)obj)); } else if (oid.Equals(MiscObjectIdentifiers.VerisignCzagExtension)) { buf.Append(new VerisignCzagExtension((DerIA5String)obj)); } else { buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); //buf.Append(" value = ").Append("*****").Append(nl); } } catch (Exception) { buf.Append(oid.Id); //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl); buf.Append(" value = ").Append("*****"); } } buf.Append(nl); }while (e.MoveNext()); } return(buf.ToString()); }
/// <inheritdoc/> public async Task <Tuple <X509Certificate, RsaKeyParameters> > GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger logger = null) { string applicationUri = applicationDescription.ApplicationUri; if (string.IsNullOrEmpty(applicationUri)) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } string subjectName = null; string hostName = null; string appName = null; UriBuilder appUri = new UriBuilder(applicationUri); if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host)) { var path = appUri.Path.Trim('/'); if (!string.IsNullOrEmpty(path)) { hostName = appUri.Host; appName = path; subjectName = $"CN={appName},DC={hostName}"; } } if (appUri.Scheme == "urn") { var parts = appUri.Path.Split(new[] { ':' }, 2); if (parts.Length == 2) { hostName = parts[0]; appName = parts[1]; subjectName = $"CN={appName},DC={hostName}"; } } if (subjectName == null) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } var crt = default(X509Certificate); var key = default(RsaKeyParameters); // Build 'own/certs' certificate store. var ownCerts = new Org.BouncyCastle.Utilities.Collections.HashSet(); var ownCertsInfo = new DirectoryInfo(Path.Combine(this.pkiPath, "own", "certs")); if (ownCertsInfo.Exists) { foreach (var info in ownCertsInfo.EnumerateFiles()) { using (var crtStream = info.OpenRead()) { var c = this.certParser.ReadCertificate(crtStream); if (c != null) { ownCerts.Add(c); } } } } IX509Store ownCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(ownCerts)); // Select the newest certificate that matches by subject name. var selector = new X509CertStoreSelector() { Subject = new X509Name(subjectName) }; crt = ownCertStore.GetMatches(selector).OfType <X509Certificate>().OrderBy(c => c.NotBefore).LastOrDefault(); if (crt != null) { // If certificate found, verify alt-name, and retrieve private key. var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName); if (asn1OctetString != null) { var asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString); GeneralNames gns = GeneralNames.GetInstance(asn1Object); if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri)) { var ki = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key")); if (ki.Exists) { using (var keyStream = new StreamReader(ki.OpenRead())) { var keyReader = new PemReader(keyStream); var keyPair = keyReader.ReadObject() as AsymmetricCipherKeyPair; if (keyPair != null) { key = keyPair.Private as RsaKeyParameters; } } } } } } // If certificate and key are found, return to caller. if (crt != null && key != null) { logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'."); return(new Tuple <X509Certificate, RsaKeyParameters>(crt, key)); } if (!this.CreateLocalCertificateIfNotExist) { return(null); } // Create new certificate var subjectDN = new X509Name(subjectName); // Create a keypair. var kp = await Task.Run <AsymmetricCipherKeyPair>(() => { RsaKeyPairGenerator kg = new RsaKeyPairGenerator(); kg.Init(new KeyGenerationParameters(this.rng, 2048)); return(kg.GenerateKeyPair()); }); key = kp.Private as RsaPrivateCrtKeyParameters; // Create a certificate. X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); var subjectSN = BigInteger.ProbablePrime(120, this.rng); cg.SetSerialNumber(subjectSN); cg.SetSubjectDN(subjectDN); cg.SetIssuerDN(subjectDN); cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime()); cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25)); cg.SetPublicKey(kp.Public); cg.AddExtension( X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); cg.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public))); cg.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN)); cg.AddExtension( X509Extensions.SubjectAlternativeName, false, new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) })); cg.AddExtension( X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment)); cg.AddExtension( X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth)); crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, this.rng)); logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'."); var keyInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key")); if (!keyInfo.Directory.Exists) { Directory.CreateDirectory(keyInfo.DirectoryName); } else if (keyInfo.Exists) { keyInfo.Delete(); } using (var keystream = new StreamWriter(keyInfo.OpenWrite())) { var pemwriter = new PemWriter(keystream); pemwriter.WriteObject(key); } var crtInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "certs", $"{crt.SerialNumber}.crt")); if (!crtInfo.Directory.Exists) { Directory.CreateDirectory(crtInfo.DirectoryName); } else if (crtInfo.Exists) { crtInfo.Delete(); } using (var crtstream = new StreamWriter(crtInfo.OpenWrite())) { var pemwriter = new PemWriter(crtstream); pemwriter.WriteObject(crt); } return(new Tuple <X509Certificate, RsaKeyParameters>(crt, key)); }
public virtual bool Match(object obj) { X509Certificate x509Certificate = obj as X509Certificate; if (x509Certificate == null) { return(false); } if (!MatchExtension(authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier)) { return(false); } if (basicConstraints != -1) { int num = x509Certificate.GetBasicConstraints(); if (basicConstraints == -2) { if (num != -1) { return(false); } } else if (num < basicConstraints) { return(false); } } if (certificate != null && !certificate.Equals(x509Certificate)) { return(false); } if (certificateValid != null && !x509Certificate.IsValid(certificateValid.Value)) { return(false); } if (extendedKeyUsage != null) { global::System.Collections.IList list = x509Certificate.GetExtendedKeyUsage(); if (list != null) { { global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)extendedKeyUsage).GetEnumerator(); try { while (enumerator.MoveNext()) { DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current(); if (!list.Contains((object)derObjectIdentifier.Id)) { return(false); } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } } } } if (issuer != null && !issuer.Equivalent(x509Certificate.IssuerDN, inOrder: true)) { return(false); } if (keyUsage != null) { bool[] array = x509Certificate.GetKeyUsage(); if (array != null) { for (int i = 0; i < 9; i++) { if (keyUsage[i] && !array[i]) { return(false); } } } } if (policy != null) { Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies); if (extensionValue == null) { return(false); } Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)); if (((global::System.Collections.ICollection)policy).get_Count() < 1 && instance.Count < 1) { return(false); } bool flag = false; { global::System.Collections.IEnumerator enumerator = instance.GetEnumerator(); try { while (enumerator.MoveNext()) { PolicyInformation policyInformation = (PolicyInformation)enumerator.get_Current(); if (policy.Contains(policyInformation.PolicyIdentifier)) { flag = true; break; } } } finally { global::System.IDisposable disposable2 = enumerator as global::System.IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } } if (!flag) { return(false); } } if (privateKeyValid != null) { Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod); if (extensionValue2 == null) { return(false); } PrivateKeyUsagePeriod instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2)); global::System.DateTime value = privateKeyValid.Value; global::System.DateTime dateTime = instance2.NotAfter.ToDateTime(); global::System.DateTime dateTime2 = instance2.NotBefore.ToDateTime(); if (value.CompareTo((object)dateTime) > 0 || value.CompareTo((object)dateTime2) < 0) { return(false); } } if (serialNumber != null && !serialNumber.Equals(x509Certificate.SerialNumber)) { return(false); } if (subject != null && !subject.Equivalent(x509Certificate.SubjectDN, inOrder: true)) { return(false); } if (!MatchExtension(subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier)) { return(false); } if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(x509Certificate))) { return(false); } if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(x509Certificate).AlgorithmID)) { return(false); } return(true); }
public X509Certificate( X509CertificateStructure c) { this.c = c; try { this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm); Asn1Encodable parameters = c.SignatureAlgorithm.Parameters; this.sigAlgParams = (null == parameters) ? null : parameters.GetEncoded(Asn1Encodable.Der); } catch (Exception e) { throw new CrlException("Certificate contents invalid: " + e); } try { Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19")); if (str != null) { basicConstraints = BasicConstraints.GetInstance( X509ExtensionUtilities.FromExtensionValue(str)); } } catch (Exception e) { throw new CertificateParsingException("cannot construct BasicConstraints: " + e); } try { Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15")); if (str != null) { DerBitString bits = DerBitString.GetInstance( X509ExtensionUtilities.FromExtensionValue(str)); byte[] bytes = bits.GetBytes(); int length = (bytes.Length * 8) - bits.PadBits; keyUsage = new bool[(length < 9) ? 9 : length]; for (int i = 0; i != length; i++) { // keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0; } } else { keyUsage = null; } } catch (Exception e) { throw new CertificateParsingException("cannot construct KeyUsage: " + e); } }
public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" userCertificate: ").Append(this.SerialNumber).Append(nl); buf.Append(" revocationDate: ").Append(this.RevocationDate).Append(nl); buf.Append(" certificateIssuer: ").Append(this.GetCertificateIssuer()).Append(nl); X509Extensions extensions = c.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" crlEntryExtensions:").Append(nl); do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object obj = X509ExtensionUtilities.FromExtensionValue(ext.Value); buf.Append(" critical(") .Append(ext.IsCritical) .Append(") "); try { if (oid.Equals(X509Extensions.ReasonCode)) { buf.Append(new CrlReason(DerEnumerated.GetInstance(obj))); } else if (oid.Equals(X509Extensions.CertificateIssuer)) { buf.Append("Certificate issuer: ").Append( GeneralNames.GetInstance((Asn1Sequence)obj)); } else { buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); } buf.Append(nl); } catch (Exception) { buf.Append(oid.Id); buf.Append(" value = ").Append("*****").Append(nl); } } else { buf.Append(nl); } }while (e.MoveNext()); } } return(buf.ToString()); }
public AuthorityKeyIdentifierStructure(Asn1OctetString encodedValue) : base((Asn1Sequence)X509ExtensionUtilities.FromExtensionValue(encodedValue)) { }
public override string ToString() { StringBuilder builder = new StringBuilder(); string newLine = Platform.NewLine; builder.Append(" Version: ").Append(this.Version).Append(newLine); builder.Append(" IssuerDN: ").Append(this.IssuerDN).Append(newLine); builder.Append(" This update: ").Append(this.ThisUpdate).Append(newLine); builder.Append(" Next update: ").Append(this.NextUpdate).Append(newLine); builder.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(newLine); byte[] signature = this.GetSignature(); builder.Append(" Signature: "); builder.Append(Hex.ToHexString(signature, 0, 20)).Append(newLine); for (int i = 20; i < signature.Length; i += 20) { int length = Math.Min(20, signature.Length - i); builder.Append(" "); builder.Append(Hex.ToHexString(signature, i, length)).Append(newLine); } X509Extensions extensions = this.c.TbsCertList.Extensions; if (extensions != null) { IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator(); if (enumerator.MoveNext()) { builder.Append(" Extensions: ").Append(newLine); } do { DerObjectIdentifier current = (DerObjectIdentifier)enumerator.Current; X509Extension extension = extensions.GetExtension(current); if (extension.Value != null) { Asn1Object obj2 = X509ExtensionUtilities.FromExtensionValue(extension.Value); builder.Append(" critical(").Append(extension.IsCritical).Append(") "); try { if (current.Equals(X509Extensions.CrlNumber)) { builder.Append(new CrlNumber(DerInteger.GetInstance(obj2).PositiveValue)).Append(newLine); } else if (current.Equals(X509Extensions.DeltaCrlIndicator)) { builder.Append("Base CRL: " + new CrlNumber(DerInteger.GetInstance(obj2).PositiveValue)).Append(newLine); } else if (current.Equals(X509Extensions.IssuingDistributionPoint)) { builder.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)obj2)).Append(newLine); } else if (current.Equals(X509Extensions.CrlDistributionPoints)) { builder.Append(CrlDistPoint.GetInstance((Asn1Sequence)obj2)).Append(newLine); } else if (current.Equals(X509Extensions.FreshestCrl)) { builder.Append(CrlDistPoint.GetInstance((Asn1Sequence)obj2)).Append(newLine); } else { builder.Append(current.Id); builder.Append(" value = ").Append(Asn1Dump.DumpAsString((Asn1Encodable)obj2)).Append(newLine); } } catch (Exception) { builder.Append(current.Id); builder.Append(" value = ").Append("*****").Append(newLine); } } else { builder.Append(newLine); } }while (enumerator.MoveNext()); } ISet revokedCertificates = this.GetRevokedCertificates(); if (revokedCertificates != null) { IEnumerator enumerator = revokedCertificates.GetEnumerator(); try { while (enumerator.MoveNext()) { X509CrlEntry current = (X509CrlEntry)enumerator.Current; builder.Append(current); builder.Append(newLine); } } finally { if (enumerator is IDisposable disposable) { IDisposable disposable; disposable.Dispose(); } } } return(builder.ToString()); }
public virtual bool Match( object obj) { X509Certificate c = obj as X509Certificate; if (c == null) { return(false); } if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier)) { return(false); } if (basicConstraints != -1) { int bc = c.GetBasicConstraints(); if (basicConstraints == -2) { if (bc != -1) { return(false); } } else { if (bc < basicConstraints) { return(false); } } } if (certificate != null && !certificate.Equals(c)) { return(false); } if (certificateValid != null && !c.IsValid(certificateValid.Value)) { return(false); } if (extendedKeyUsage != null) { IList eku = c.GetExtendedKeyUsage(); // Note: if no extended key usage set, all key purposes are implicitly allowed if (eku != null) { foreach (DerObjectIdentifier oid in extendedKeyUsage) { if (!eku.Contains(oid.Id)) { return(false); } } } } if (issuer != null && !issuer.Equivalent(c.IssuerDN, true)) { return(false); } if (keyUsage != null) { bool[] ku = c.GetKeyUsage(); // Note: if no key usage set, all key purposes are implicitly allowed if (ku != null) { for (int i = 0; i < 9; ++i) { if (keyUsage[i] && !ku[i]) { return(false); } } } } if (policy != null) { Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies); if (extVal == null) { return(false); } Asn1Sequence certPolicies = Asn1Sequence.GetInstance( X509ExtensionUtilities.FromExtensionValue(extVal)); if (policy.Count < 1 && certPolicies.Count < 1) { return(false); } bool found = false; foreach (PolicyInformation pi in certPolicies) { if (policy.Contains(pi.PolicyIdentifier)) { found = true; break; } } if (!found) { return(false); } } if (privateKeyValid != null) { Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod); if (extVal == null) { return(false); } PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance( X509ExtensionUtilities.FromExtensionValue(extVal)); DateTime dt = privateKeyValid.Value; DateTime notAfter = pkup.NotAfter.ToDateTime(); DateTime notBefore = pkup.NotBefore.ToDateTime(); if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0) { return(false); } } if (serialNumber != null && !serialNumber.Equals(c.SerialNumber)) { return(false); } if (subject != null && !subject.Equivalent(c.SubjectDN, true)) { return(false); } if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier)) { return(false); } if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c))) { return(false); } if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID)) { return(false); } return(true); }
public override void PerformTest() { IX509AttributeCertificate aCert = new X509V2AttributeCertificate(attrCert); X509CertificateParser fact = new X509CertificateParser(); X509Certificate sCert = fact.ReadCertificate(signCert); aCert.Verify(sCert.GetPublicKey()); // // search test // IList list = new ArrayList(); list.Add(sCert); // CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); // CertStore store = CertStore.getInstance("Collection", ccsp); IX509Store store = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(list)); ArrayList certs = new ArrayList( // store.getCertificates(aCert.getIssuer())); store.GetMatches(aCert.Issuer)); if (certs.Count != 1 || !certs.Contains(sCert)) { Fail("sCert not found by issuer"); } X509Attribute[] attrs = aCert.GetAttributes("1.3.6.1.4.1.6760.8.1.1"); if (attrs == null || attrs.Length != 1) { Fail("attribute not found"); } // // reencode test // aCert = new X509V2AttributeCertificate(aCert.GetEncoded()); aCert.Verify(sCert.GetPublicKey()); IX509AttributeCertificate saCert = new X509V2AttributeCertificate(aCert.GetEncoded()); if (!aCert.NotAfter.Equals(saCert.NotAfter)) { Fail("failed date comparison"); } // base generator test // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); AsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC; // // set up the keys // // PrivateKey privKey; // PublicKey pubKey; // // KeyFactory kFact = KeyFactory.getInstance("RSA"); // // privKey = kFact.generatePrivate(privKeySpec); // pubKey = kFact.generatePublic(pubKeySpec); X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); gen.AddAttribute(attrs[0]); gen.SetHolder(aCert.Holder); gen.SetIssuer(aCert.Issuer); gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); gen.SetSerialNumber(aCert.SerialNumber); gen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); aCert = gen.Generate(privKey); aCert.CheckValidity(); aCert.Verify(pubKey); // as the issuer is the same this should still work (even though it is not // technically correct certs = new ArrayList( // store.getCertificates(aCert.Issuer)); store.GetMatches(aCert.Issuer)); if (certs.Count != 1 || !certs.Contains(sCert)) { Fail("sCert not found by issuer"); } attrs = aCert.GetAttributes("1.3.6.1.4.1.6760.8.1.1"); if (attrs == null || attrs.Length != 1) { Fail("attribute not found"); } // // reencode test // aCert = new X509V2AttributeCertificate(aCert.GetEncoded()); aCert.Verify(pubKey); AttributeCertificateIssuer issuer = aCert.Issuer; X509Name[] principals = issuer.GetPrincipals(); // // test holder // AttributeCertificateHolder holder = aCert.Holder; if (holder.GetEntityNames() == null) { Fail("entity names not set"); } if (holder.SerialNumber != null) { Fail("holder serial number set when none expected"); } if (holder.GetIssuer() != null) { Fail("holder issuer set when none expected"); } principals = holder.GetEntityNames(); string ps = principals[0].ToString(); // TODO Check that this is a good enough test // if (!ps.Equals("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), [email protected]")) if (!principals[0].Equivalent(new X509Name("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), [email protected]"))) { Fail("principal[0] for entity names don't Match"); } // // extension test // gen.AddExtension("1.1", true, new DerOctetString(new byte[10])); gen.AddExtension("2.2", false, new DerOctetString(new byte[20])); aCert = gen.Generate(privKey); ISet exts = aCert.GetCriticalExtensionOids(); if (exts.Count != 1 || !exts.Contains("1.1")) { Fail("critical extension test failed"); } exts = aCert.GetNonCriticalExtensionOids(); if (exts.Count != 1 || !exts.Contains("2.2")) { Fail("non-critical extension test failed"); } Asn1OctetString extString = aCert.GetExtensionValue(new DerObjectIdentifier("1.1")); Asn1Encodable extValue = X509ExtensionUtilities.FromExtensionValue(extString); if (!extValue.Equals(new DerOctetString(new byte[10]))) { Fail("wrong extension value found for 1.1"); } doTestCertWithBaseCertificateID(); doTestGenerateWithCert(); doTestGenerateWithPrincipal(); }
/** * Returns a string representation of this CRL. * * @return a string representation of this CRL. */ public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" Version: ").Append(this.Version).Append(nl); buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl); buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl); buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl); buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl); byte[] sig = this.GetSignature(); buf.Append(" Signature: "); buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl); for (int i = 20; i < sig.Length; i += 20) { int count = System.Math.Min(20, sig.Length - i); buf.Append(" "); buf.Append(Hex.ToHexString(sig, i, count)).Append(nl); } X509Extensions extensions = c.TbsCertList.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" Extensions: ").Append(nl); } do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value); buf.Append(" critical(").Append(ext.IsCritical).Append(") "); try { if (oid.Equals(X509Extensions.CrlNumber)) { buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl); } else if (oid.Equals(X509Extensions.DeltaCrlIndicator)) { buf.Append( "Base CRL: " + new CrlNumber(DerInteger.GetInstance( asn1Value).PositiveValue)) .Append(nl); } else if (oid.Equals(X509Extensions.IssuingDistributionPoint)) { buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl); } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl); } else if (oid.Equals(X509Extensions.FreshestCrl)) { buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl); } else { buf.Append(oid.Id); buf.Append(" value = ").Append( Asn1Dump.DumpAsString(asn1Value)) .Append(nl); } } catch (Exception) { buf.Append(oid.Id); buf.Append(" value = ").Append("*****").Append(nl); } } else { buf.Append(nl); } }while (e.MoveNext()); } ISet certSet = GetRevokedCertificates(); if (certSet != null) { foreach (X509CrlEntry entry in certSet) { buf.Append(entry); buf.Append(nl); } } return(buf.ToString()); }
public virtual bool Match(object obj) { X509Crl x509Crl = obj as X509Crl; if (x509Crl == null) { return(false); } if (this.dateAndTime != null) { DateTime value = this.dateAndTime.Value; DateTime thisUpdate = x509Crl.ThisUpdate; DateTimeObject nextUpdate = x509Crl.NextUpdate; if (value.CompareTo(thisUpdate) < 0 || nextUpdate == null || value.CompareTo(nextUpdate.Value) >= 0) { return(false); } } if (this.issuers != null) { X509Name issuerDN = x509Crl.IssuerDN; bool flag = false; foreach (X509Name x509Name in this.issuers) { if (x509Name.Equivalent(issuerDN, true)) { flag = true; break; } } if (!flag) { return(false); } } if (this.maxCrlNumber != null || this.minCrlNumber != null) { Asn1OctetString extensionValue = x509Crl.GetExtensionValue(X509Extensions.CrlNumber); if (extensionValue == null) { return(false); } BigInteger positiveValue = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)).PositiveValue; if (this.maxCrlNumber != null && positiveValue.CompareTo(this.maxCrlNumber) > 0) { return(false); } if (this.minCrlNumber != null && positiveValue.CompareTo(this.minCrlNumber) < 0) { return(false); } } DerInteger derInteger = null; try { Asn1OctetString extensionValue2 = x509Crl.GetExtensionValue(X509Extensions.DeltaCrlIndicator); if (extensionValue2 != null) { derInteger = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2)); } } catch (Exception) { return(false); } if (derInteger == null) { if (this.DeltaCrlIndicatorEnabled) { return(false); } } else { if (this.CompleteCrlEnabled) { return(false); } if (this.maxBaseCrlNumber != null && derInteger.PositiveValue.CompareTo(this.maxBaseCrlNumber) > 0) { return(false); } } if (this.issuingDistributionPointEnabled) { Asn1OctetString extensionValue3 = x509Crl.GetExtensionValue(X509Extensions.IssuingDistributionPoint); if (this.issuingDistributionPoint == null) { if (extensionValue3 != null) { return(false); } } else if (!Arrays.AreEqual(extensionValue3.GetOctets(), this.issuingDistributionPoint)) { return(false); } } return(true); }