List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java
/** * Load a trusted list for the specified URL * * @param url//from w ww.java 2s . c o m * @param signerCert * @return * @throws IOException */ private TrustStatusList getTrustStatusList(String url, X509Certificate signerCert) { InputStream input = null; try { input = dataLoader.get(url); if (input == null) { throw new DSSNullReturnedException("The loader returned a null InputStream for: " + url); } if (url.toLowerCase().endsWith(".zip")) { input = getZippedData(input); } Document doc = DSSXMLUtils.buildDOM(input); boolean coreValidity = true; if (checkSignature) { coreValidity = false; if (signerCert != null) { final NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodeList.getLength() == 0) { throw new DSSException("Not ETSI compliant signature. The Xml is not signed."); } if (signatureNodeList.getLength() > 1) { throw new DSSException("Not ETSI compliant signature. There is more than one signature."); } final Element signatureEl = (Element) signatureNodeList.item(0); final KeySelector keySelector = KeySelector.singletonKeySelector(signerCert.getPublicKey()); final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureEl); final TSLURIDereferencer tsluriDereferencer = new TSLURIDereferencer(signatureEl); valContext.setURIDereferencer(tsluriDereferencer); final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); final XMLSignature signature = factory.unmarshalXMLSignature(valContext); coreValidity = signature.validate(valContext); LOG.info("The TSL signature validity: " + coreValidity); } } final TrustStatusList tsl = TrustServiceListFactory.newInstance(doc); tsl.setWellSigned(coreValidity); return tsl; } catch (DSSException e) { throw e; } catch (Exception e) { throw new DSSException(e); } finally { DSSUtils.closeQuietly(input); } }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Generates a signed certificate for an entity. * //from w ww . j a v a 2 s . co m * @param country The country of org/entity * @param orgName The name of the organization the entity belongs to * @param type The type of the entity * @param callName The name of the entity * @param email The email of the entity * @param publickey The public key of the entity * @return Returns a signed X509Certificate */ public X509Certificate generateCertForEntity(BigInteger serialNumber, String country, String orgName, String type, String callName, String email, String uid, PublicKey publickey, Map<String, String> customAttr) { PrivateKeyEntry signingCertEntry = getSigningCertEntry(); java.security.cert.Certificate signingCert = signingCertEntry.getCertificate(); X509Certificate signingX509Cert = (X509Certificate) signingCert; // Try to find the correct country code, else we just use the country name as code String orgCountryCode = country; String[] locales = Locale.getISOCountries(); for (String countryCode : locales) { Locale loc = new Locale("", countryCode); if (loc.getDisplayCountry(Locale.ENGLISH).equals(orgCountryCode)) { orgCountryCode = loc.getCountry(); break; } } String orgSubjectDn = "C=" + orgCountryCode + ", " + "O=" + orgName + ", " + "OU=" + type + ", " + "CN=" + callName + ", " + "UID=" + uid; if (email != null && !email.isEmpty()) { orgSubjectDn += ", " + "E=" + email; } X509Certificate orgCert = null; try { orgCert = buildAndSignCert(serialNumber, signingCertEntry.getPrivateKey(), signingX509Cert.getPublicKey(), publickey, new JcaX509CertificateHolder(signingX509Cert).getSubject(), new X500Name(orgSubjectDn), customAttr, "ENTITY"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return orgCert; }
From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java
/** * Produce a human readable export of the given tsl to the given file. * /*from ww w . j av a 2 s . c o m*/ * @param tsl * the TrustServiceList to export * @param pdfFile * the file to generate * @return * @throws IOException */ public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) { Document document = new Document(); OutputStream outputStream; try { outputStream = new FileOutputStream(pdfFile); } catch (FileNotFoundException e) { throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e); } try { final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); pdfWriter.setPDFXConformance(PdfWriter.PDFA1B); // title final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory()); final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName() + "): Trusted List"; Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ", headerFooterFont); HeaderFooter footer = new HeaderFooter(footerPhrase, true); document.setFooter(footer); Phrase headerPhrase = new Phrase(title, headerFooterFont); HeaderFooter header = new HeaderFooter(headerPhrase, false); document.setHeader(header); document.open(); addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document); addLongItem("Scheme name", tsl.getSchemeName(), document); addLongItem("Legal Notice", tsl.getLegalNotice(), document); // information table PdfPTable informationTable = createInfoTable(); addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable); addItemRow("Scheme status determination approach", substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable); /* final List<String> schemeTypes = new ArrayList<String>(); for (final String schemeType : tsl.getSchemeTypes()) { schemeTypes.add(schemeType); } */ final List<String> schemeTypes = new ArrayList<String>(); List<NonEmptyMultiLangURIType> uris = tsl.getSchemeTypes(); for (NonEmptyMultiLangURIType uri : uris) { schemeTypes.add(uri.getValue()); } addItemRow("Scheme type community rules", schemeTypes, informationTable); addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable); addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable); addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days", informationTable); addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable); addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable); document.add(informationTable); addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document); informationTable = createInfoTable(); addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable); PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH); addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(), informationTable); addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(), informationTable); addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable); addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable); addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable); List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses(); addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable); document.add(informationTable); addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document); List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders(); for (TrustServiceProvider trustServiceProvider : trustServiceProviders) { addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document); PdfPTable providerTable = createInfoTable(); addItemRow("Service provider trade name", trustServiceProvider.getTradeNames(), providerTable); addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable); PostalAddressType postalAddress = trustServiceProvider.getPostalAddress(); addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable); addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable); addItemRow("Service provider locality", postalAddress.getLocality(), providerTable); addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable); addItemRow("Service provider country", postalAddress.getCountryName(), providerTable); document.add(providerTable); List<TrustService> trustServices = trustServiceProvider.getTrustServices(); for (TrustService trustService : trustServices) { addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document); PdfPTable serviceTable = createInfoTable(); addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable); addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable); addItemRow("Status starting time", trustService.getStatusStartingTime().toString(), serviceTable); document.add(serviceTable); addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document); final X509Certificate certificate = trustService.getServiceDigitalIdentity(); final PdfPTable serviceIdentityTable = createInfoTable(); addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable); addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable); addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable); addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable); addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable); addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable); addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable); addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable); // TODO certificate policies addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable); addItemRow("CRL distribution points", getCrlDistributionPoints(certificate), serviceIdentityTable); addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable); addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable); addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable); byte[] encodedCertificate; try { encodedCertificate = certificate.getEncoded(); } catch (CertificateEncodingException e) { throw new RuntimeException("cert: " + e.getMessage(), e); } addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable); addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate), serviceIdentityTable); document.add(serviceIdentityTable); //add Scheme service definition if (null != trustService.getSchemeServiceDefinitionURI()) { addTitle("Scheme Service Definition URI", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document); final PdfPTable schemeServiceDefinitionURITabel = createInfoTable(); for (NonEmptyMultiLangURIType uri : trustService.getSchemeServiceDefinitionURI().getURI()) { addItemRow(uri.getLang(), uri.getValue(), schemeServiceDefinitionURITabel); } document.add(schemeServiceDefinitionURITabel); } List<ExtensionType> extensions = trustService.getExtensions(); for (ExtensionType extension : extensions) { printExtension(extension, document); } addLongMonoItem("The decoded certificate:", certificate.toString(), document); addLongMonoItem("The certificate in PEM format:", toPem(certificate), document); ServiceHistoryType serviceHistoryType = trustService.getServiceHistoryInstanceType(); if (null != serviceHistoryType) { for (ServiceHistoryInstanceType serviceHistoryInstanceType : serviceHistoryType .getServiceHistoryInstance()) { PdfPTable serviceHistoryTable = createInfoTable(); //Service approval history information addTitle("Service approval history information", title3Font, Paragraph.ALIGN_LEFT, 10, 2, document); // service type identifier //5.6.2 Service name InternationalNamesType i18nServiceName = serviceHistoryInstanceType.getServiceName(); String servName = TrustServiceListUtils.getValue(i18nServiceName, Locale.ENGLISH); addItemRow("Name", servName, serviceHistoryTable); //5.6.1 Service type identifier addItemRow("Type", substringAfter(serviceHistoryInstanceType.getServiceTypeIdentifier(), "Svctype/"), serviceHistoryTable); addItemRow("Status", serviceHistoryInstanceType.getServiceStatus(), serviceHistoryTable); //5.6.4 Service previous status addItemRow("Previous status", serviceHistoryInstanceType.getServiceStatus(), serviceHistoryTable); //5.6.5 Previous status starting date and time addItemRow( "Previous starting time", new DateTime(serviceHistoryInstanceType .getStatusStartingTime().toGregorianCalendar()).toString(), serviceHistoryTable); //5.6.3 Service digital identity final X509Certificate previousCertificate = trustService.getServiceDigitalIdentity( serviceHistoryInstanceType.getServiceDigitalIdentity()); document.add(serviceHistoryTable); addTitle("Service digital identity (X509)", title4Font, Paragraph.ALIGN_LEFT, 2, 0, document); final PdfPTable serviceIdentityTableHistory = createInfoTable(); addItemRow("Version", Integer.toString(previousCertificate.getVersion()), serviceIdentityTableHistory); addItemRow("Serial number", previousCertificate.getSerialNumber().toString(), serviceIdentityTableHistory); addItemRow("Signature algorithm", previousCertificate.getSigAlgName(), serviceIdentityTableHistory); addItemRow("Issuer", previousCertificate.getIssuerX500Principal().toString(), serviceIdentityTableHistory); addItemRow("Valid from", previousCertificate.getNotBefore().toString(), serviceIdentityTableHistory); addItemRow("Valid to", previousCertificate.getNotAfter().toString(), serviceIdentityTableHistory); addItemRow("Subject", previousCertificate.getSubjectX500Principal().toString(), serviceIdentityTableHistory); addItemRow("Public key", previousCertificate.getPublicKey().toString(), serviceIdentityTableHistory); // TODO certificate policies addItemRow("Subject key identifier", toHex(getSKId(previousCertificate)), serviceIdentityTableHistory); addItemRow("CRL distribution points", getCrlDistributionPoints(previousCertificate), serviceIdentityTableHistory); addItemRow("Authority key identifier", toHex(getAKId(previousCertificate)), serviceIdentityTableHistory); addItemRow("Key usage", getKeyUsage(previousCertificate), serviceIdentityTableHistory); addItemRow("Basic constraints", getBasicConstraints(previousCertificate), serviceIdentityTableHistory); byte[] encodedHistoryCertificate; try { encodedHistoryCertificate = previousCertificate.getEncoded(); } catch (CertificateEncodingException e) { throw new RuntimeException("cert: " + e.getMessage(), e); } addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedHistoryCertificate), serviceIdentityTableHistory); addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedHistoryCertificate), serviceIdentityTableHistory); document.add(serviceIdentityTableHistory); ExtensionsListType previousExtensions = serviceHistoryInstanceType .getServiceInformationExtensions(); if (null != previousExtensions) { for (ExtensionType extension : previousExtensions.getExtension()) { printExtension(extension, document); } } addLongMonoItem("The decoded certificate:", previousCertificate.toString(), document); addLongMonoItem("The certificate in PEM format:", toPem(previousCertificate), document); } } } } X509Certificate signerCertificate = tsl.verifySignature(); if (null != signerCertificate) { Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font); tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER); document.add(tslSignerTitle); final PdfPTable signerTable = createInfoTable(); addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable); addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable); addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable); addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable); addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable); addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable); byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded(); addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable); addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable); document.add(signerTable); addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document); addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document); addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document); } document.close(); } catch (DocumentException e) { throw new RuntimeException("PDF document error: " + e.getMessage(), e); } catch (Exception e) { throw new RuntimeException("Exception: " + e.getMessage(), e); } }
From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java
private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate, String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { String defaultAlias = Collections.list(keyStore.aliases()).get(0); X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias); Assert.assertNotNull(secretCertificate); Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName() .equals(x509Certificate.getSubjectX500Principal().getName())); Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName() .equals(x509Certificate.getIssuerX500Principal().getName())); Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber())); // Validate the key in the KeyStore Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray()); Assert.assertNotNull(secretKey);//from ww w . j av a 2s . c o m Assert.assertTrue(secretKey instanceof PrivateKey); PrivateKey secretPrivateKey = (PrivateKey) secretKey; // Create a KeyPair with the private key from the KeyStore and public // key from the certificate to verify they match KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey); Assert.assertNotNull(keyPair); verifyRSAKeyPair(keyPair); }
From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java
/** * 5.5.3 Service digital identity/*from ww w . ja v a 2s. c o m*/ * <p/> * The same public key (and hence the same certificate representing this public key) shall not appear * more than once in the trusted list for the same type of service. The same public key may appear * more than once in the TL only when associated to trust services having different 'Service type * identifier' ('Sti') values (e.g. public key used for verifying signatures on different types of Trust * Services Tokens) for which different supervision/ accreditation systems apply. */ private void checkRuleUniqueSDIperService() { if (services != null) { Set<String> keySet = new HashSet<String>(); for (TSPServiceType service : services) { // both values are mandatory and are supposed to be present at this point String sti = service.getServiceInformation().getServiceTypeIdentifier(); DigitalIdentityListType sdi = service.getServiceInformation().getServiceDigitalIdentity(); byte[] publicKey = null; for (DigitalIdentityType id : sdi.getDigitalId()) { // 1-2 entries if (publicKey == null) { try { byte[] x509Certificate = id.getX509Certificate(); final X509Certificate x509 = DSSUtils.loadCertificate(x509Certificate); publicKey = x509.getPublicKey().getEncoded(); continue; } catch (DSSException e) { LOG.log(Level.SEVERE, e.getMessage(), e); } } else { break; } } String couple = sti + Arrays.hashCode(publicKey); if (keySet.contains(couple)) { logger.error(uiKeys.getString("Validation.rule.uniqueSDIperService"), service); } else { keySet.add(couple); } } } }
From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java
/** * 5.5.3 Service digital identity/* w ww . j av a 2 s . c om*/ * <p/> * The TLSO may list more than one certificate to represent the * public key, but only when all those certificates relate to the same public key and have identical * subject names */ void checkRuleAllSDIHaveTheSamePublicKey() { if (services != null) { for (TSPServiceType service : services) { // both values are mandatory and are supposed to be present at this point DigitalIdentityListType sdi = service.getServiceInformation().getServiceDigitalIdentity(); Set<PublicKey> publicKeySet = new HashSet<PublicKey>(); Set<X500Principal> subjectSet = new HashSet<X500Principal>(); for (DigitalIdentityType id : sdi.getDigitalId()) { // 1-2 entries byte[] x509Certificate = id.getX509Certificate(); if (x509Certificate != null) { try { final X509Certificate x509 = DSSUtils.loadCertificate(x509Certificate); publicKeySet.add(x509.getPublicKey()); subjectSet.add(x509.getSubjectX500Principal()); } catch (DSSException e) { LOG.log(Level.SEVERE, e.getMessage(), e); } } else { final String x509SubjectName = id.getX509SubjectName(); if (x509SubjectName != null) { subjectSet.add(new X500Principal(x509SubjectName)); } } } if (publicKeySet.size() > 1) { logger.error(uiKeys.getString("Validation.rule.digitalIdentity.uniquePublicKeyPerService"), service); } if (subjectSet.size() > 1) { logger.error(uiKeys.getString("Validation.rule.digitalIdentity.uniqueSubjectNamePerService"), service); } } } }
From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java
/** * 5.5.3 Service digital identity/*w w w . java2 s. co m*/ * <p/> * The TLSO may list more than one certificate to represent the * public key, but only when all those certificates relate to the same public key and have identical * subject names */ void checkRulePointerToOtherTSLHaveTheSamePublicKey() { if (pointers != null) { for (OtherTSLPointerType pointer : pointers) { final List<DigitalIdentityListType> serviceDigitalIdentity = pointer.getServiceDigitalIdentities() .getServiceDigitalIdentity(); for (DigitalIdentityListType digitalIdentityListType : serviceDigitalIdentity) { Set<PublicKey> publicKeySet = new HashSet<PublicKey>(); Set<X500Principal> subjectSet = new HashSet<X500Principal>(); for (DigitalIdentityType id : digitalIdentityListType.getDigitalId()) { // 1-2 entries byte[] x509Certificate = id.getX509Certificate(); if (x509Certificate != null) { try { final X509Certificate x509 = DSSUtils.loadCertificate(x509Certificate); publicKeySet.add(x509.getPublicKey()); subjectSet.add(x509.getSubjectX500Principal()); } catch (DSSException e) { LOG.log(Level.SEVERE, e.getMessage(), e); } } } if (publicKeySet.size() > 1) { logger.error(uiKeys.getString("Validation.rule.digitalIdentity.uniquePublicKeyPerService"), pointer); } if (subjectSet.size() > 1) { logger.error( uiKeys.getString("Validation.rule.digitalIdentity.uniqueSubjectNamePerService"), pointer); } } } } }
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return null; }//w w w .ja v a 2s.c o m LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return null; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return null; } Object responseObject; try { responseObject = ocspResp.getResponseObject(); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; try { X509Certificate[] responseCertificates = basicOCSPResp.getCerts(BouncyCastleProvider.PROVIDER_NAME); for (X509Certificate responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubjectX500Principal()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuerX500Principal()); } TrustLinkerResult trustResult = TrustValidator .checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgName()); if (!trustResult.isValid()) return trustResult; if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the * issuing CA itself. */ boolean verificationResult = basicOCSPResp.verify(certificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return null; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509Certificate ocspResponderCertificate = responseCertificates[0]; boolean verificationResult = basicOCSPResp.verify(ocspResponderCertificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return null; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(ocspResponderCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly * signed by the CA. */ issuingCaCertificate = certificate; } else { issuingCaCertificate = responseCertificates[1]; /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return null; } } // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); trustResult = publicKeyTrustLinker.hasTrustLink(ocspResponderCertificate, issuingCaCertificate, validationDate, revocationData); if (null != trustResult) { if (!trustResult.isValid()) { LOG.debug("OCSP responder not trusted"); return null; } } if (null == ocspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return null; } List<String> extendedKeyUsage; try { extendedKeyUsage = ocspResponderCertificate.getExtendedKeyUsage(); } catch (CertificateParsingException e) { LOG.debug("OCSP Responder parsing error: " + e.getMessage(), e); return null; } if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return null; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return null; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); } } } catch (NoSuchProviderException e) { LOG.debug("JCA provider exception: " + e.getMessage(), e); return null; } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } catch (CertificateEncodingException e) { LOG.debug("certificate encoding error: " + e.getMessage(), e); return null; } CertificateID certificateId; try { certificateId = new CertificateID(CertificateID.HASH_SHA1, certificate, childCertificate.getSerialNumber()); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } Date thisUpdate = singleResp.getThisUpdate(); LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("OCSP nextUpdate: " + singleResp.getNextUpdate()); long dt = Math.abs(thisUpdate.getTime() - validationDate.getTime()); if (dt > this.freshnessInterval) { LOG.warn("freshness interval exceeded: " + dt + " milliseconds"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(true); } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return null; }
From source file:it.cnr.icar.eric.server.security.authentication.AuthenticationServiceImpl.java
protected void registerUserCertificate(String userId, X509Certificate cert) throws RegistryException { java.io.FileOutputStream fos = null; try {/*from w w w .j a va 2 s .c o m*/ KeyStore keyStore = getKeyStore(); // Make sure no other user is registered with same cert under a // different alias String alias = getKeyStore().getCertificateAlias(cert); if ((null != alias) && (!userId.equalsIgnoreCase(alias))) { throw new UserRegistrationException(ServerResourceBundle.getInstance() .getString("message.error.certificateAlreadyExists", new Object[] { userId, alias })); } // Check if already in store X509Certificate oldCert = null; try { oldCert = getCertificate(userId); } catch (Exception e) { } // System.err.println("Checking the certificates are the same..."); if ((oldCert != null) && !certificatesAreSame(cert, oldCert)) { throw new UserRegistrationException(ServerResourceBundle.getInstance() .getString("message.userRegistrationFailed", new Object[] { userId })); } // Add the cert. to the keystore if the cert. does not exist yet if (oldCert == null) { if (propsReader.getProperty("eric.security.validateCertificates").trim().equalsIgnoreCase("true")) { validateCertificate(cert); } synchronized (keyStoreWriteLock) { keyStore.setCertificateEntry(userId, cert); String keystoreFile = getKeyStoreFileName(); fos = new java.io.FileOutputStream(keystoreFile); String keystorePass = getKeyStorePassword(); keyStore.store(fos, keystorePass.toCharArray()); fos.flush(); fos.close(); this.keyStore = null; // Update publicKeyToCertMap publicKeyToCertMap.put(cert.getPublicKey(), cert); } } } catch (KeyStoreException e) { throw new UserRegistrationException(e); } catch (IOException e) { throw new UserRegistrationException(e); } catch (java.security.cert.CertificateException e) { throw new UserRegistrationException(e); } catch (NoSuchAlgorithmException e) { throw new UserRegistrationException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }