List of usage examples for java.security.cert X509Certificate getSigAlgName
public abstract String getSigAlgName();
From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/*from w w w . j ava 2 s. co m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (AbLogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":"); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (AbLogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
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. j a va2s . co 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:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java
/** * Produce a human readable export of the given tsl to the given file. * //from www .j a va 2s .c om * @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); } 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.getTradeName(), 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); 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); } } 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:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
protected KeyMap cacheKeys(KeyStore ks, KeyInfoManager keyInfoManager) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException { KeyMap keys = new KeyMap(); // load and cache the keys for (Entry<String, KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet()) { String keyAlias = keyEntry.getKey(); KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias); String passwordStr = keyInfo != null ? keyInfo.getPassword() : null; // Null is an acceptable value (means no key) Key key = null;// w w w. ja va 2s . c om // Attempt to get the key key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray()); if (key != null) { keys.setKey(keyAlias, key); } // Key loaded if (logger.isDebugEnabled()) { logger.debug( "Retrieved key from keystore: \n" + " Location: " + getKeyStoreParameters().getLocation() + "\n" + " Provider: " + getKeyStoreParameters().getProvider() + "\n" + " Type: " + getKeyStoreParameters().getType() + "\n" + " Alias: " + keyAlias + "\n" + " Password?: " + (passwordStr != null)); Certificate[] certs = ks.getCertificateChain(keyAlias); if (certs != null) { logger.debug("Certificate chain '" + keyAlias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; logger.debug(" Certificate " + (c + 1) + ":"); logger.debug(" Subject DN: " + cert.getSubjectDN()); logger.debug(" Signature Algorithm: " + cert.getSigAlgName()); logger.debug(" Valid from: " + cert.getNotBefore()); logger.debug(" Valid until: " + cert.getNotAfter()); logger.debug(" Issuer: " + cert.getIssuerDN()); } } } } } return keys; }
From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java
@Test public void testIssueCert() throws IOException, CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException, InvalidKeyException, SignatureException { X509Certificate issuer = loadCertificate( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.crt"))); KeyPair issuerKeyPair = loadKeyPair( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.key"))); String dn = "CN=testIssued, O=testOrg"; KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, keyPair.getPublic(), issuer, issuerKeyPair, signingAlgorithm, days); assertEquals(dn, x509Certificate.getSubjectX500Principal().toString()); assertEquals(issuer.getSubjectX500Principal().toString(), x509Certificate.getIssuerX500Principal().toString()); assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey()); Date notAfter = x509Certificate.getNotAfter(); assertTrue(notAfter.after(inFuture(days - 1))); assertTrue(notAfter.before(inFuture(days + 1))); Date notBefore = x509Certificate.getNotBefore(); assertTrue(notBefore.after(inFuture(-1))); assertTrue(notBefore.before(inFuture(1))); assertEquals(signingAlgorithm, x509Certificate.getSigAlgName()); assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm()); x509Certificate.verify(issuerKeyPair.getPublic()); }
From source file:org.signserver.admin.gui.ViewCertificateFrame.java
private void viewCertificate(final X509Certificate certificate) { this.certificate = certificate; if (certificate == null) { fields = null;/*from w w w .ja v a 2s . co m*/ } else { fields = new ArrayList<Field>(); fields.add(new Field("Version", String.valueOf(certificate.getVersion()))); fields.add(new Field("Serial Number", certificate.getSerialNumber().toString(16))); fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName()))); fields.add(new Field("Issuer", String.valueOf(certificate.getIssuerDN()))); fields.add(new Field("Validity Not Before", String.valueOf(certificate.getNotBefore()))); fields.add(new Field("Validity Not After", String.valueOf(certificate.getNotAfter()))); fields.add(new Field("Subject", String.valueOf(certificate.getSubjectDN()))); fields.add(new Field("Subject Public Key Algorithm", String.valueOf(certificate.getPublicKey().getAlgorithm()))); fields.add(new Field("Subject's Public Key", new String(Hex.encode(certificate.getPublicKey().getEncoded())))); if (certificate.getCriticalExtensionOIDs() != null) { for (String extensionOid : certificate.getCriticalExtensionOIDs()) { fields.add(new Field("Critical extension: " + extensionOid, "<Not supported yet>")); } } if (certificate.getNonCriticalExtensionOIDs() != null) { for (String extensionOid : certificate.getNonCriticalExtensionOIDs()) { fields.add(new Field("Non critical extension: " + extensionOid, "<Not supported yet>")); } } fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName()))); fields.add( new Field("Certificate Signature Value", new String(Hex.encode(certificate.getSignature())))); fieldsList.setModel(new AbstractListModel() { @Override public int getSize() { return fields.size(); } @Override public Object getElementAt(int index) { return fields.get(index); } }); } }
From source file:org.openanzo.client.AnzoTrustManager.java
private void handleCertificateException(CertificateException ce, X509Certificate[] chain) throws CertificateException { if (trustAll) { return;//from w w w. j a v a 2 s .com } System.err.println(ce.getMessage()); System.err.println("Certificate Information: \n"); Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(chain[0].getNotBefore().getTime()); System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " " + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR)); //System.err.println("Entry type: " + chain[0].getType()); System.err.println("Certificate chain length: " + chain.length); // print some information about the certificate(s) that failed int i = 1; for (X509Certificate cert : chain) { System.err.println("Certificate[" + i++ + "]:"); System.err.println("Owner: " + cert.getSubjectX500Principal().toString()); System.err.println("Issuer: " + cert.getIssuerX500Principal().toString()); String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray())); System.err.println("Serial Number: " + serialNum); System.err.println( "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString()); System.err.println("Certificate fingerprints: "); try { byte[] sig = cert.getEncoded(); System.err.println("\tMD5: " + getHash(sig, "MD5")); System.err.println("\tSHA1: " + getHash(sig, "SHA1")); } catch (NoSuchAlgorithmException e) { } System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName()); System.err.println("\tVersion: " + cert.getVersion()); System.err.println("-----------------------------------------------------"); } System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; try { line = in.readLine(); } catch (IOException e) { CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace); System.exit(1); } if (Character.toLowerCase(line.charAt(0)) == 'o') { return; } else if (Character.toLowerCase(line.charAt(0)) == 'a') { try { String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS"); String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD); String truststorePath = System.getProperty("javax.net.ssl.trustStore"); if (truststorePath == null) { // there is no trust store location in the user's settings.trig file String userHome = System.getProperty("user.home"); if (userHome == null) throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER, "User's home directory is not specified"); File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST); truststorePath = truststoreFile.getCanonicalPath(); if (!truststoreFile.exists()) openTruststore(truststoreType, truststorePath, truststorePassword); } else { truststorePath = CommandContext.preprocessString(truststorePath); File truststoreFile = new File(truststorePath); if (!truststoreFile.exists()) { System.err.println("Could not find the specified trust store file at:"); System.err.println(truststoreFile.getCanonicalPath()); System.err.println( "The trust store file is used for permanently trusting server certificates that"); System.err.println("are not trusted by default."); System.err.println( "Would you like to create a new trust store file at the specified location?"); System.err.println("(y)es, (n)o"); try { line = in.readLine(); } catch (IOException e) { CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace); System.exit(1); } if (Character.toLowerCase(line.charAt(0)) == 'y') openTruststore(truststoreType, truststorePath, truststorePassword); else System.exit(1); } } KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword, "imported_" + System.currentTimeMillis(), chain[0]); } catch (AnzoException ae) { System.err.println("Error importing certificate into truststore: "); CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace); System.exit(1); } catch (IOException e) { System.err.println("Error importing certificate into truststore: "); CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace); System.exit(1); } } else { System.exit(1); // if the user does not want to trust the certificate then exit } }
From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java
/** * Produce a human readable export of the given tsl to the given file. * /*ww w. j ava 2 s . c om*/ * @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:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java
private void populateCertificateTree() { certificateTree.removeAll();/*from w w w . j a v a 2 s .c o m*/ valueText.setText(StringUtils.EMPTY); IStructuredSelection selection = (IStructuredSelection) hierarchyTreeViewer.getSelection(); if (selection.size() != 1) { return; } CertificateChainItem certificateItem = (CertificateChainItem) selection.getFirstElement(); X509Certificate certificate = certificateItem.certificate; TreeItem rootItem = new TreeItem(certificateTree, SWT.NONE); Map<String, String> attributeMap = getAttributeMap(certificate.getSubjectX500Principal()); rootItem.setText(attributeMap.get("CN")); //$NON-NLS-1$ TreeItem certItem = createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Certificate"), //$NON-NLS-1$ StringUtils.EMPTY); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Version"), //$NON-NLS-1$ String.valueOf(certificate.getVersion())); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SerialNumber"), //$NON-NLS-1$ certificate.getSerialNumber().toString(16)); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$ certificate.getSigAlgName()); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Issuer"), //$NON-NLS-1$ certificate.getIssuerX500Principal().getName()); TreeItem validityItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Validity"), //$NON-NLS-1$ StringUtils.EMPTY); createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotBefore"), //$NON-NLS-1$ certificate.getNotBefore().toString()); createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotAfter"), //$NON-NLS-1$ certificate.getNotAfter().toString()); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Subject"), //$NON-NLS-1$ certificate.getSubjectX500Principal().getName()); TreeItem pkiItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyInfo"), StringUtils.EMPTY); //$NON-NLS-1$ createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyAlgorithm"), //$NON-NLS-1$ certificate.getPublicKey().getAlgorithm()); createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKey"), //$NON-NLS-1$ new String(Hex.encodeHex(certificate.getPublicKey().getEncoded()))); TreeItem extItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Extensions"), //$NON-NLS-1$ StringUtils.EMPTY); populateExtensions(extItem, certificate, true); populateExtensions(extItem, certificate, false); createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.SignatureAlgorithm"), //$NON-NLS-1$ certificate.getSigAlgName()); createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$ new String(Hex.encodeHex(certificate.getSignature()))); rootItem.setExpanded(true); certItem.setExpanded(true); validityItem.setExpanded(true); pkiItem.setExpanded(true); extItem.setExpanded(true); }
From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java
/** * Signed specified cert using the private key of RegistryOperator. * Warning this uses Sun's JDK impl specific classes and will not work * with other JDK impls./*from w w w .java 2s.c om*/ * */ @SuppressWarnings("static-access") X509Certificate signCertificate(X509Certificate inCert) throws RegistryException { X509CertImpl signedCert = null; try { X509CertImpl caCert = (X509CertImpl) getCACertificate(); X509CertInfo caCertInfo = new X509CertInfo(caCert.getTBSCertificate()); X509CertInfo inCertInfo = new X509CertInfo(inCert.getTBSCertificate()); // Use catch (certs subject name as signed cert's issuer name CertificateSubjectName caCertSubjectName = (CertificateSubjectName) caCertInfo .get(X509CertInfo.SUBJECT); CertificateIssuerName signedCertIssuerName = new CertificateIssuerName( (X500Name) caCertSubjectName.get(CertificateSubjectName.DN_NAME)); inCertInfo.set(X509CertInfo.ISSUER, signedCertIssuerName); signedCert = new X509CertImpl(inCertInfo); //TODO: Need to remove hardcoding below and instead somehow use info.algId => algName // signedCert.sign(ac.getPrivateKey(ac.ALIAS_REGISTRY_OPERATOR, ac.ALIAS_REGISTRY_OPERATOR), "MD5WithRSA"); // JDK6 // signedCert.sign(ac.getPrivateKey(ac.ALIAS_REGISTRY_OPERATOR, ac.ALIAS_REGISTRY_OPERATOR), "SHA256withRSA"); // JDK7 // removed hardcoding signedCert.sign(ac.getPrivateKey(ac.ALIAS_REGISTRY_OPERATOR, ac.ALIAS_REGISTRY_OPERATOR), inCert.getSigAlgName()); } catch (java.security.GeneralSecurityException e) { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.ErrorSigningRegIssuedCert"), e); } catch (java.io.IOException e) { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.ErrorSigningRegIssuedCert"), e); } return signedCert; }