List of usage examples for java.security.cert X509Certificate getSubjectX500Principal
public X500Principal getSubjectX500Principal()
From source file:Main.java
private static boolean isKnownRoot(X509Certificate root) throws NoSuchAlgorithmException, KeyStoreException { assert Thread.holdsLock(sLock); // Could not find the system key store. Conservatively report false. if (sSystemKeyStore == null) return false; // Check the in-memory cache first; avoid decoding the anchor from disk // if it has been seen before. Pair<X500Principal, PublicKey> key = new Pair<X500Principal, PublicKey>(root.getSubjectX500Principal(), root.getPublicKey());/*from w w w . java2 s . co m*/ if (sSystemTrustAnchorCache.contains(key)) return true; // Note: It is not sufficient to call sSystemKeyStore.getCertificiateAlias. If the server // supplies a copy of a trust anchor, X509TrustManagerExtensions returns the server's // version rather than the system one. getCertificiateAlias will then fail to find an anchor // name. This is fixed upstream in https://android-review.googlesource.com/#/c/91605/ // // TODO(davidben): When the change trickles into an Android release, query sSystemKeyStore // directly. // System trust anchors are stored under a hash of the principal. In case of collisions, // a number is appended. String hash = hashPrincipal(root.getSubjectX500Principal()); for (int i = 0; true; i++) { String alias = hash + '.' + i; if (!new File(sSystemCertificateDirectory, alias).exists()) break; Certificate anchor = sSystemKeyStore.getCertificate("system:" + alias); // It is possible for this to return null if the user deleted a trust anchor. In // that case, the certificate remains in the system directory but is also added to // another file. Continue iterating as there may be further collisions after the // deleted anchor. if (anchor == null) continue; if (!(anchor instanceof X509Certificate)) { // This should never happen. String className = anchor.getClass().getName(); Log.e(TAG, "Anchor " + alias + " not an X509Certificate: " + className); continue; } // If the subject and public key match, this is a system root. X509Certificate anchorX509 = (X509Certificate) anchor; if (root.getSubjectX500Principal().equals(anchorX509.getSubjectX500Principal()) && root.getPublicKey().equals(anchorX509.getPublicKey())) { sSystemTrustAnchorCache.add(key); return true; } } return false; }
From source file:wptools.cmds.DumpCerts.java
private static void dumpCert(X509Certificate cert) { System.out.println("Serial No.: " + formatFing(cert.getSerialNumber().toByteArray())); try {//w w w . j ava2 s. com for (String ftype : FTYPES) { MessageDigest md = MessageDigest.getInstance(ftype); md.reset(); System.out.format("%s: %s%n", ftype, formatFing(md.digest(cert.getEncoded()))); } } catch (NoSuchAlgorithmException | CertificateException e) { Misc.die(e.getMessage()); } System.out.println("Issued To: " + cert.getSubjectX500Principal()); System.out.println("Issued By: " + cert.getIssuerX500Principal()); System.out.format("Valid: from %tFT%<tT%<tz to %tFT%<tT%<tz%n%n", cert.getNotBefore(), cert.getNotAfter()); }
From source file:org.sandrob.android.net.http.HttpsConnection.java
private static String getCertificateAlias(X509Certificate cert) { X500Principal subject = cert.getSubjectX500Principal(); X500Principal issuer = cert.getIssuerX500Principal(); String sSubjectCN = getCommonName(subject); // Could not get a subject CN - return blank if (sSubjectCN == null) { return ""; }//from w w w . j a v a2s . c om String sIssuerCN = getCommonName(issuer); // Self-signed certificate or could not get an issuer CN if (subject.equals(issuer) || sIssuerCN == null) { // Alias is the subject CN return sSubjectCN; } // else non-self-signed certificate // Alias is the subject CN followed by the issuer CN in parenthesis return MessageFormat.format("{0} ({1})", sSubjectCN, sIssuerCN); }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static KeyInfo getKeyInfo(XMLSignatureFactory factory, X509Certificate certificate) { KeyInfoFactory kif = factory.getKeyInfoFactory(); List<Object> x509Content = new ArrayList<Object>(); x509Content.add(certificate.getSubjectX500Principal().getName()); x509Content.add(certificate);//from w w w .j ava 2s . c o m X509Data cerData = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(cerData), null); return ki; }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static KeyInfo getKeyInfo(XMLSignatureFactory factory, X509Certificate certificate) { KeyInfoFactory kif = factory.getKeyInfoFactory(); List<Object> x509Content = new ArrayList<>(); x509Content.add(certificate.getSubjectX500Principal().getName()); x509Content.add(certificate);//from w ww . j a v a2s .c o m X509Data cerData = kif.newX509Data(x509Content); return kif.newKeyInfo(Collections.singletonList(cerData), null); }
From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java
/** * Create a PKCS #10 certificate signing request (CSR) using the supplied * certificate, private key and signature algorithm. * * @param cert// w ww . j av a 2 s. c o m * The certificate * @param privateKey * The private key * @param signatureType * Signature * @param challenge * Challenge, optional, pass null if not required * @param unstructuredName * An optional company name, pass null if not required * @param useExtensions * Use extensions from cert for extensionRequest attribute? * @throws CryptoException * If there was a problem generating the CSR * @return The CSR */ public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException { try { JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder( cert.getSubjectX500Principal(), cert.getPublicKey()); // add challenge attribute if (challenge != null) { // PKCS#9 2.0: SHOULD use UTF8String encoding csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge)); } if (unstructuredName != null) { csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName)); } if (useExtensions) { // add extensionRequest attribute with all extensions from the certificate Certificate certificate = Certificate.getInstance(cert.getEncoded()); Extensions extensions = certificate.getTBSCertificate().getExtensions(); if (extensions != null) { csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive()); } } // fall back to bouncy castle provider if given provider does not support the requested algorithm if (provider != null && provider.getService("Signature", signatureType.jce()) == null) { provider = new BouncyCastleProvider(); } ContentSigner contentSigner = null; if (provider == null) { contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey); } else { contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider) .build(privateKey); } PKCS10CertificationRequest csr = csrBuilder.build(contentSigner); if (!verifyCsr(csr)) { throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message")); } return csr; } catch (CertificateEncodingException e) { throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e); } catch (OperatorCreationException e) { throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e); } }
From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java
private static boolean isRootCA(X509Certificate cert) throws InvalidKeyException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { if (!cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) return false; cert.verify(cert.getPublicKey());/*from ww w .j a v a 2s . c om*/ return true; }
From source file:ch.bfh.unicert.certimport.Main.java
/** * Create a certificate fot the given CSV record * * @param record the record to parse/* w ww .j a v 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:io.fabric8.utils.cxf.WebClients.java
public static KeyStore createKeyStore(String clientCertData, File clientCertFile, String clientKeyData, File clientKeyFile, String clientKeyAlgo, char[] clientKeyPassword) throws Exception { try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream); InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile); PEMReader reader = new PEMReader(keyInputStream); RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec(); KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo); RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null);/*from w w w. j a v a 2s. c o m*/ String alias = cert.getSubjectX500Principal().getName(); keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert }); return keyStore; } }
From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java
public static BasicOCSPRespGenerator createOCSPResponse(OCSPReq req, X509Certificate respondercert, int respIdType) throws OCSPException, NotSupportedException { if (null == req) { throw new IllegalArgumentException(); }//from w w w . j ava 2 s . c o m BasicOCSPRespGenerator res = null; if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) { res = new BasicOCSPRespGenerator(new RespID(respondercert.getSubjectX500Principal())); } else { res = new BasicOCSPRespGenerator(respondercert.getPublicKey()); } X509Extensions reqexts = req.getRequestExtensions(); if (reqexts != null) { X509Extension ext = reqexts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_response); if (null != ext) { //m_log.debug("Found extension AcceptableResponses"); ASN1OctetString oct = ext.getValue(); try { ASN1Sequence seq = ASN1Sequence.getInstance( new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject()); Enumeration en = seq.getObjects(); boolean supportsResponseType = false; while (en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); //m_log.debug("Found oid: "+oid.getId()); if (oid.equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) { // This is the response type we support, so we are happy! Break the loop. supportsResponseType = true; m_log.debug("Response type supported: " + oid.getId()); continue; } } if (!supportsResponseType) { throw new NotSupportedException( "Required response type not supported, this responder only supports id-pkix-ocsp-basic."); } } catch (IOException e) { } } } return res; }