List of usage examples for java.security.cert CertificateFactory getInstance
public static final CertificateFactory getInstance(String type) throws CertificateException
From source file:org.apache.syncope.client.console.wicket.markup.html.form.preview.BinaryCertPreviewer.java
@Override public Component preview(final byte[] uploadedBytes) { Label commonNameLabel = new Label("certCommonName", new Model<>()); if (uploadedBytes.length == 0) { LOG.info("Enpty certificate"); return commonNameLabel; }/* w ww . j av a2s .com*/ try (ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes)) { X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(certificateStream); StringBuilder commonNameBuilder = new StringBuilder("cn="); LdapName ldapName = new LdapName(certificate.getIssuerDN().getName()); for (Rdn rdn : ldapName.getRdns()) { if ("CN".equalsIgnoreCase(rdn.getType())) { commonNameBuilder .append(rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString()); } } commonNameLabel.setDefaultModelObject(commonNameBuilder.toString()); } catch (Exception e) { LOG.error("Error evaluating certificate file", e); commonNameLabel.setDefaultModelObject(getString(Constants.ERROR)); } return this.addOrReplace(commonNameLabel); }
From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java
/** * Return the file's absolute path name string * /*from w w w . j ava2s.co m*/ * @param x509Cert * @return Path name string * @throws Exception */ public static String importCertificate(String x509Cert) throws Exception { // CREATE A KEYSTORE OF TYPE "Java Key Store" KeyStore ks = KeyStore.getInstance("JKS"); /* * LOAD THE STORE The first time you're doing this (i.e. the keystore * does not yet exist - you're creating it), you HAVE to load the * keystore from a null source with null password. Before any methods * can be called on your keystore you HAVE to load it first. Loading it * from a null source and null password simply creates an empty * keystore. At a later time, when you want to verify the keystore or * get certificates (or whatever) you can load it from the file with * your password. */ ks.load(null, null); // GET THE FILE CONTAINING YOUR CERTIFICATE File x509 = new File(x509Cert); FileInputStream fis = new FileInputStream(x509); BufferedInputStream bis = new BufferedInputStream(fis); // I USE x.509 BECAUSE THAT'S WHAT keytool CREATES CertificateFactory cf = CertificateFactory.getInstance("X.509"); // NOTE: THIS IS java.security.cert.Certificate NOT // java.security.Certificate X509Certificate cert = (X509Certificate) cf.generateCertificate(bis); ks.setCertificateEntry(CERT_ALIAS, cert); // SAVE THE KEYSTORE TO A FILE /* * After this is saved, I believe you can just do setCertificateEntry to * add entries and then not call store. I believe it will update the * existing store you load it from and not just in memory. */ File storeFile = new File(x509.getParentFile().getAbsolutePath(), KEYSTORE); ks.store(new FileOutputStream(storeFile), KEYSTORE_PASS.toCharArray()); return storeFile.getAbsolutePath(); }
From source file:nl.surfnet.spring.security.opensaml.util.KeyStoreUtil.java
/** * Append a certificate and private key to a keystore. * * @param keyStore where to append the certificate and private key to * @param keyAlias the alias of the key * @param certificateInputStream the inputStream containing the certificate in the PEM format * @param privatekeyInputStream the input stream containing the private key in the DER format * @param password the password on the key * <p/>//from w ww. ja va 2 s . com * Generate your private key: openssl genrsa -out something.key 1024 * <p/> * Show the PEM private key: openssl asn1parse -inform pem -dump -i * -in something.key * <p/> * Translate the key to pkcs8 DER format: openssl pkcs8 -topk8 * -inform PEM -outform DER -in something.key -nocrypt > * something.pkcs8.der * <p/> * Show the DER private key: openssl asn1parse -inform der -dump -i * -in something.pkcs8.der * <p/> * Generate a certificate request: openssl req -new -key * something.key -out something.csr * <p/> * Generate a certificate: openssl x509 -req -days 365 -in * something.csr -signkey something.key -out something.crt */ public static void appendKeyToKeyStore(KeyStore keyStore, String keyAlias, InputStream certificateInputStream, InputStream privatekeyInputStream, char[] password) throws IOException { CertificateFactory certFact; Certificate cert; try { certFact = CertificateFactory.getInstance("X.509"); cert = certFact.generateCertificate(certificateInputStream); } catch (CertificateException e) { throw new RuntimeException("Could not instantiate cert", e); } ArrayList<Certificate> certs = new ArrayList<Certificate>(); certs.add(cert); byte[] privKeyBytes = IOUtils.toByteArray(privatekeyInputStream); try { KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes); RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(ks); keyStore.setKeyEntry(keyAlias, privKey, password, certs.toArray(new Certificate[certs.size()])); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java
/** * Default constructor.//from ww w . ja v a 2 s . c o m */ public BeIDIntegrity() { try { this.certificateFactory = CertificateFactory.getInstance("X.509"); } catch (final CertificateException cex) { throw new RuntimeException("X.509 algo", cex); } }
From source file:ch.bfh.unicert.certimport.Main.java
/** * Create a certificate fot the given CSV record * * @param record the record to parse//from w w w .j av a 2 s. c o m * @throws InvalidNameException */ private static void createCertificate(CSVRecord record) throws InvalidNameException { int recordid = Integer.parseInt(record.get(0)); String pemCert = record.get(1); String institution = record.get(2); int revoked = Integer.parseInt(record.get(3)); if (revoked == 1) { System.out.println("Certficate " + recordid + " is revoked. Looking for next certificate..."); return; } String studyBranch = record.get(5); String uniqueId = record.get(6); String mail = record.get(8); CertificateFactory cf; X509Certificate cert; try { cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(pemCert.getBytes())); } catch (CertificateException ex) { logger.log(Level.SEVERE, "Not able to read certificate for record {0}, exception: {1}", new Object[] { recordid, ex }); return; } DSAPublicKey pubKey = (DSAPublicKey) cert.getPublicKey(); String commonName = cert.getSubjectDN().getName(); LdapName ln = new LdapName(cert.getSubjectX500Principal().toString()); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { commonName = (String) rdn.getValue(); break; } else if (rdn.getType().equalsIgnoreCase("UID")) { uniqueId = (String) rdn.getValue(); break; } else if (rdn.getType().equalsIgnoreCase("OU")) { studyBranch = (String) rdn.getValue(); break; } } IdentityData idData = new IdentityData(commonName, uniqueId, institution, studyBranch, null, null, null, null, null, "SwitchAAI", null); try { Certificate certificate = issuer.createClientCertificate(idData, keystorePath, pubKey, 10, "UniVote", new String[] { "Voter" }, uniBoardWSDLurl, uniBoardUrl, section); counter++; System.out.println("Certificate published for " + recordid + ". Count " + counter + " of 6424"); } catch (CertificateCreationException ex) { logger.log(Level.SEVERE, "Not able to create certificate for record {0}, exception: {1}", new Object[] { recordid, ex }); } }
From source file:com.evilisn.DAO.CertMapper.java
@Override public Object mapRow(ResultSet resultSet, int i) throws SQLException { Cert crt = new Cert(); crt.setCertificate(resultSet.getString("certificate")); CertificateFactory fact = null; try {//from w w w. j a v a 2 s. c om fact = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { e.printStackTrace(); } X509Certificate x509cert = null; InputStream stream = new ByteArrayInputStream(crt.getCertificate().getBytes(StandardCharsets.UTF_8)); try { x509cert = (X509Certificate) fact.generateCertificate(stream); crt.setClient_cert(x509cert); } catch (CertificateException e) { e.printStackTrace(); } crt.setResponder_uri(OCSP.getResponderURI(x509cert)); X509Certificate issuerCert; if (!cached_issuers.containsKey(getIssuerCertURL(x509cert))) { //download and set the issuers. try { issuerCert = getX509Certificate(httpGetBin(getIssuerCertURL(x509cert), true)); cached_issuers.put(getIssuerCertURL(x509cert), issuerCert); crt.setIssuer_cert(issuerCert); } catch (Exception e) { e.printStackTrace(); } } else { issuerCert = cached_issuers.get(getIssuerCertURL(x509cert)); crt.setIssuer_cert(issuerCert); } Principal principal = x509cert.getIssuerDN(); String issuerDn = principal.getName(); crt.setIssuer_dn(issuerDn); return crt; }
From source file:com.spotify.docker.client.DockerCertificates.java
private DockerCertificates(final Builder builder) throws DockerCertificateException { try {/*from w ww . j a v a 2s .c om*/ final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert }); this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build(); } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new DockerCertificateException(e); } }
From source file:no.difi.meldingsutveksling.domain.Sertifikat.java
private static Sertifikat lagSertifikat(byte[] certificate) throws CertificateException { X509Certificate x509Certificate = (X509Certificate) CertificateFactory.getInstance("X509") .generateCertificate(new ByteArrayInputStream(certificate)); return new Sertifikat(x509Certificate); }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESCertificateSource.java
@Override public List<X509Certificate> getCertificates() { List<X509Certificate> list = new ArrayList<X509Certificate>(); try {// w ww .j av a2s. c o m CertificateFactory factory = CertificateFactory.getInstance("X509"); NodeList nodeList2 = (NodeList) XMLUtils.getNodeList(signatureElement, "ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CertificateValues/xades:EncapsulatedX509Certificate"); for (int i = 0; i < nodeList2.getLength(); i++) { Element certEl = (Element) nodeList2.item(i); byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent()); X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(derEncoded)); if (!list.contains(cert)) { list.add(cert); } } if (!onlyExtended) { NodeList nodeList = (NodeList) XMLUtils.getNodeList(signatureElement, "ds:KeyInfo/ds:X509Data/ds:X509Certificate"); for (int i = 0; i < nodeList.getLength(); i++) { Element certEl = (Element) nodeList.item(i); byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent()); X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(derEncoded)); if (!list.contains(cert)) { list.add(cert); } } } } catch (CertificateException e) { throw new RuntimeException(e); } return list; }
From source file:io.vertx.config.vault.utils.Certificates.java
/** * Called by the constructor method prior to configuring and launching the Vault instance. Uses Bouncy Castle * (https://www.bouncycastle.org) to programmatically generate a private key and X509 certificate for use by * the Vault server instance in accepting SSL connections. *///w w w . j a v a 2s .c om public static void createVaultCertAndKey() throws Exception { if (SSL_DIRECTORY.isDirectory() && CERT_PEMFILE.isFile()) { try (FileInputStream fis = new FileInputStream(CERT_PEMFILE)) { CertificateFactory fact = CertificateFactory.getInstance("X.509"); vaultCertificate = (X509Certificate) fact.generateCertificate(fis); } return; } SSL_DIRECTORY.mkdirs(); // Generate a certificate and private key for Vault, and write them to disk in PEM format. Also store the // original X509Certificate object in a member variable, so it can later be used by "createClientCertAndKey()". final KeyPair keyPair = generateKeyPair(); vaultCertificate = generateCert(keyPair, "C=AU, O=The Legion of the Bouncy Castle, OU=Vault Server Certificate, CN=localhost"); writeCertToPem(vaultCertificate, CERT_PEMFILE); writePrivateKeyToPem(keyPair.getPrivate(), PRIVATE_KEY_PEMFILE); }