java.security.cert.Certificate Java Examples
The following examples show how to use
java.security.cert.Certificate.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DomainKeyStore.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * Returns the certificate chain associated with the given alias. * * @param alias the alias name * * @return the certificate chain (ordered with the user's certificate first * and the root certificate authority last), or null if the given alias * does not exist or does not contain a certificate chain (i.e., the given * alias identifies either a <i>trusted certificate entry</i> or a * <i>key entry</i> without a certificate chain). */ public Certificate[] engineGetCertificateChain(String alias) { AbstractMap.SimpleEntry<String, Collection<KeyStore>> pair = getKeystoresForReading(alias); Certificate[] chain = null; try { String entryAlias = pair.getKey(); for (KeyStore keystore : pair.getValue()) { chain = keystore.getCertificateChain(entryAlias); if (chain != null) { break; } } } catch (KeyStoreException e) { throw new IllegalStateException(e); } return chain; }
Example #2
Source File: KeychainStore.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * Returns the (alias) name of the first keystore entry whose certificate * matches the given certificate. * * <p>This method attempts to match the given certificate with each * keystore entry. If the entry being considered * is a <i>trusted certificate entry</i>, the given certificate is * compared to that entry's certificate. If the entry being considered is * a <i>key entry</i>, the given certificate is compared to the first * element of that entry's certificate chain (if a chain exists). * * @param cert the certificate to match with. * * @return the (alias) name of the first entry with matching certificate, * or null if no such entry exists in this keystore. */ public String engineGetCertificateAlias(Certificate cert) { permissionCheck(); Certificate certElem; for (Enumeration e = entries.keys(); e.hasMoreElements(); ) { String alias = (String)e.nextElement(); Object entry = entries.get(alias); if (entry instanceof TrustedCertEntry) { certElem = ((TrustedCertEntry)entry).cert; } else if (((KeyEntry)entry).chain != null) { certElem = ((KeyEntry)entry).chain[0]; } else { continue; } if (certElem.equals(cert)) { return alias; } } return null; }
Example #3
Source File: JavaKeyStore.java From Bytecoder with Apache License 2.0 | 6 votes |
/** * Returns the certificate associated with the given alias. * * <p>If the given alias name identifies a * <i>trusted certificate entry</i>, the certificate associated with that * entry is returned. If the given alias name identifies a * <i>key entry</i>, the first element of the certificate chain of that * entry is returned, or null if that entry does not have a certificate * chain. * * @param alias the alias name * * @return the certificate, or null if the given alias does not exist or * does not contain a certificate. */ public Certificate engineGetCertificate(String alias) { Object entry = entries.get(convertAlias(alias)); if (entry != null) { if (entry instanceof TrustedCertEntry) { return ((TrustedCertEntry)entry).cert; } else { if (((KeyEntry)entry).chain == null) { return null; } else { return ((KeyEntry)entry).chain[0]; } } } else { return null; } }
Example #4
Source File: CertReplace.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public static X509Certificate[] createPath(String chain) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List list = new ArrayList(); for (Certificate c: cf.generateCertificates( new FileInputStream(chain))) { list.add((X509Certificate)c); } return (X509Certificate[]) list.toArray(new X509Certificate[0]); }
Example #5
Source File: CertServiceImpl.java From cloudstack with Apache License 2.0 | 6 votes |
private void validate(final String certInput, final String keyInput, final String password, final String chainInput, boolean revocationEnabled) { try { List<Certificate> chain = null; final Certificate cert = parseCertificate(certInput); final PrivateKey key = parsePrivateKey(keyInput); if (chainInput != null) { chain = CertificateHelper.parseChain(chainInput); } validateCert(cert); validateKeys(cert.getPublicKey(), key); if (chainInput != null) { validateChain(chain, cert, revocationEnabled); } } catch (final IOException | CertificateException e) { throw new IllegalStateException("Parsing certificate/key failed: " + e.getMessage(), e); } }
Example #6
Source File: UntrustedChecker.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
@Override public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException { X509Certificate currCert = (X509Certificate)cert; if (UntrustedCertificates.isUntrusted(currCert)) { if (debug != null) { debug.println("UntrustedChecker: untrusted certificate " + currCert.getSubjectX500Principal()); } throw new CertPathValidatorException( "Untrusted certificate: " + currCert.getSubjectX500Principal()); } }
Example #7
Source File: Activation.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
private static PermissionCollection getExecPermissions() { /* * The approach used here is taken from the similar method * getLoaderAccessControlContext() in the class * sun.rmi.server.LoaderHandler. */ // obtain permissions granted to all code in current policy PermissionCollection perms = AccessController.doPrivileged( new PrivilegedAction<PermissionCollection>() { public PermissionCollection run() { CodeSource codesource = new CodeSource(null, (Certificate[]) null); Policy p = Policy.getPolicy(); if (p != null) { return p.getPermissions(codesource); } else { return new Permissions(); } } }); return perms; }
Example #8
Source File: Archive.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * */ private void saveCertificates() throws IOException { if (!ba.storage.isReadOnly()) { final File f = new File(getPath() + CERTS_SUFFIX); if (certs != null) { try { final FileOutputStream fos = new FileOutputStream(f); for (final Certificate cert : certs) { fos.write(cert.getEncoded()); } fos.close(); } catch (final CertificateEncodingException e) { ba.frameworkWarning(e); } } } }
Example #9
Source File: DupImport.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
static void test(String... files) throws Exception { System.out.println("Testing " + Arrays.toString(files)); List<String> all = new ArrayList<>(); for (String file : files) { all.addAll(Files.readAllLines(Paths.get(file))); } Files.write(Paths.get("reply"), all); run("-importcert -file reply -alias me"); KeyStore ks = KeyStore.getInstance( new File("dup.ks"), "changeit".toCharArray()); Certificate[] chain = ks.getCertificateChain("me"); if (chain.length != 3) { throw new Exception("Length is " + chain.length); } checkName(chain[0], "CN=Me"); checkName(chain[1], "CN=Int"); checkName(chain[2], "CN=Root"); }
Example #10
Source File: Archive.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * TBD improve this. */ private void loadCertificates() throws IOException { final File f = new File(getPath() + CERTS_SUFFIX); if (f.canRead()) { try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final FileInputStream fis = new FileInputStream(f); final Collection<? extends Certificate> c = cf.generateCertificates(fis); // TBD, check if order is preserved if (c.size() > 0) { certs = new Certificate[c.size()]; certs = c.toArray(certs); } } catch (final CertificateException e) { ba.frameworkWarning(e); } } // TODO, load certificates from both trusted and untrusted storage!? }
Example #11
Source File: X509KeyManagerImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
boolean matches(Certificate[] chain) { if (!chain[0].getPublicKey().getAlgorithm().equals(keyAlgorithm)) { return false; } if (sigKeyAlgorithm == null) { return true; } if (chain.length > 1) { // if possible, check the public key in the issuer cert return sigKeyAlgorithm.equals( chain[1].getPublicKey().getAlgorithm()); } else { // Check the signature algorithm of the certificate itself. // Look for the "withRSA" in "SHA1withRSA", etc. X509Certificate issuer = (X509Certificate)chain[0]; String sigAlgName = issuer.getSigAlgName().toUpperCase(ENGLISH); String pattern = "WITH" + sigKeyAlgorithm.toUpperCase(ENGLISH); return sigAlgName.contains(pattern); } }
Example #12
Source File: MetadataEmptyTest.java From hottub with GNU General Public License v2.0 | 6 votes |
private void runTest() throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException { KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH, Utils.KeyStoreType.pkcs12, PASSWORD); Key key = ks.getKey(ALIAS, PASSWORD); Certificate cert = ks .getCertificate(ALIAS); KeyStore.Entry entry = new KeyStore.PrivateKeyEntry( (PrivateKey) key, new Certificate[]{cert}); if (!entry.getAttributes().isEmpty()) { throw new RuntimeException("Entry's attributes set " + "must be empty"); } out.println("Test Passed"); }
Example #13
Source File: UnresolvedPermission.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
/** * Writes this object out to a stream (i.e., serializes it). * * @serialData An initial {@code String} denoting the * {@code type} is followed by a {@code String} denoting the * {@code name} is followed by a {@code String} denoting the * {@code actions} is followed by an {@code int} indicating the * number of certificates to follow * (a value of "zero" denotes that there are no certificates associated * with this object). * Each certificate is written out starting with a {@code String} * denoting the certificate type, followed by an * {@code int} specifying the length of the certificate encoding, * followed by the certificate encoding itself which is written out as an * array of bytes. */ private void writeObject(java.io.ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); if (certs==null || certs.length==0) { oos.writeInt(0); } else { // write out the total number of certs oos.writeInt(certs.length); // write out each cert, including its type for (int i=0; i < certs.length; i++) { java.security.cert.Certificate cert = certs[i]; try { oos.writeUTF(cert.getType()); byte[] encoded = cert.getEncoded(); oos.writeInt(encoded.length); oos.write(encoded); } catch (CertificateEncodingException cee) { throw new IOException(cee.getMessage()); } } } }
Example #14
Source File: DomainKeyStore.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * Returns the certificate chain associated with the given alias. * * @param alias the alias name * * @return the certificate chain (ordered with the user's certificate first * and the root certificate authority last), or null if the given alias * does not exist or does not contain a certificate chain (i.e., the given * alias identifies either a <i>trusted certificate entry</i> or a * <i>key entry</i> without a certificate chain). */ public Certificate[] engineGetCertificateChain(String alias) { AbstractMap.SimpleEntry<String, Collection<KeyStore>> pair = getKeystoresForReading(alias); Certificate[] chain = null; try { String entryAlias = pair.getKey(); for (KeyStore keystore : pair.getValue()) { chain = keystore.getCertificateChain(entryAlias); if (chain != null) { break; } } } catch (KeyStoreException e) { throw new IllegalStateException(e); } return chain; }
Example #15
Source File: HandshakeMessage.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
CertificateMsg(HandshakeInStream input) throws IOException { int chainLen = input.getInt24(); List<Certificate> v = new ArrayList<>(4); CertificateFactory cf = null; while (chainLen > 0) { byte[] cert = input.getBytes24(); chainLen -= (3 + cert.length); try { if (cf == null) { cf = CertificateFactory.getInstance("X.509"); } v.add(cf.generateCertificate(new ByteArrayInputStream(cert))); } catch (CertificateException e) { throw (SSLProtocolException)new SSLProtocolException( e.getMessage()).initCause(e); } } chain = v.toArray(new X509Certificate[v.size()]); }
Example #16
Source File: SSLContextImpl.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private void checkAlgorithmConstraints(X509Certificate[] chain, AlgorithmConstraints constraints) throws CertificateException { try { // Does the certificate chain end with a trusted certificate? int checkedLength = chain.length - 1; Collection<X509Certificate> trustedCerts = new HashSet<>(); X509Certificate[] certs = tm.getAcceptedIssuers(); if ((certs != null) && (certs.length > 0)){ Collections.addAll(trustedCerts, certs); } if (trustedCerts.contains(chain[checkedLength])) { checkedLength--; } // A forward checker, need to check from trust to target if (checkedLength >= 0) { AlgorithmChecker checker = new AlgorithmChecker(constraints); checker.init(false); for (int i = checkedLength; i >= 0; i--) { Certificate cert = chain[i]; // We don't care about the unresolved critical extensions. checker.check(cert, Collections.<String>emptySet()); } } } catch (CertPathValidatorException cpve) { throw new CertificateException( "Certificates does not conform to algorithm constraints"); } }
Example #17
Source File: KeychainStore.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private boolean validateChain(Certificate[] certChain) { for (int i = 0; i < certChain.length-1; i++) { X500Principal issuerDN = ((X509Certificate)certChain[i]).getIssuerX500Principal(); X500Principal subjectDN = ((X509Certificate)certChain[i+1]).getSubjectX500Principal(); if (!(issuerDN.equals(subjectDN))) return false; } return true; }
Example #18
Source File: ServerCrypto.java From carbon-identity with Apache License 2.0 | 5 votes |
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException { try { // Generate cert path java.util.List certList = java.util.Arrays.asList(certs); CertPath path = this.getCertificateFactory().generateCertPath(certList); // Use the certificates in the keystore as TrustAnchors PKIXParameters param = new PKIXParameters(ks); // Do not check a revocation list param.setRevocationEnabled(false); // Verify the trust path using the above settings String provider = properties .getProperty("org.apache.ws.security.crypto.merlin.cert.provider"); CertPathValidator certPathValidator; if (provider == null || provider.length() == 0) { certPathValidator = CertPathValidator.getInstance("PKIX"); } else { certPathValidator = CertPathValidator.getInstance("PKIX", provider); } certPathValidator.validate(path, param); } catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException | InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[]{ex.getMessage()}, ex); } return true; }
Example #19
Source File: TrustStoreImplTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void importTrustCertificateStrings_throwCertificateEncodingExceptionWhileCalculateSha1() throws KeystoreException, CertificateException { when(certificate.getEncoded()).thenThrow(new CertificateEncodingException("Throwing exception for test")); Certificate certAdded = underTest.importTrustCertificate(CERT_IN_PEM_UNIX, "test"); assertNotNull(certAdded); verify(keyStoreManager).importTrustCertificate(isA(Certificate.class), eq("test")); verify(freezeService).checkWritable("Unable to import a certificate while database is frozen."); }
Example #20
Source File: CertificateFactory1Test.java From j2objc with Apache License 2.0 | 5 votes |
/** * Test for <code>generateCertPath(List certificates)</code> method * Assertion: returns empty CertPath if certificates is empty */ public void testCertificateFactory15() throws CertificateException { if (!X509Support) { fail(NotSupportMsg); return; } CertificateFactory[] certFs = initCertFs(); assertNotNull("CertificateFactory objects were not created", certFs); List<Certificate> list = new Vector<Certificate>(); for (int i = 0; i < certFs.length; i++) { CertPath cp = certFs[i].generateCertPath(list); List<? extends Certificate> list1 = cp.getCertificates(); assertTrue("List should be empty", list1.isEmpty()); } }
Example #21
Source File: Timestamp.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** * Returns a string describing this timestamp. * * @return A string comprising the date and time of the timestamp and * its signer's certificate. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("("); sb.append("timestamp: " + timestamp); List<? extends Certificate> certs = signerCertPath.getCertificates(); if (!certs.isEmpty()) { sb.append("TSA: " + certs.get(0)); } else { sb.append("TSA: <empty>"); } sb.append(")"); return sb.toString(); }
Example #22
Source File: KeyStoreHelper.java From jetlinks-community with Apache License 2.0 | 5 votes |
private static KeyStore loadCA(Stream<Buffer> certValues) throws Exception { final KeyStore keyStore = createEmptyKeyStore(); keyStore.load(null, null); int count = 0; Iterable<Buffer> iterable = certValues::iterator; for (Buffer certValue : iterable) { for (Certificate cert : loadCerts(certValue)) { keyStore.setCertificateEntry(DUMMY_CERT_ALIAS + count++, cert); } } return keyStore; }
Example #23
Source File: MyKeyManager.java From hottub with GNU General Public License v2.0 | 5 votes |
MyKeyManager(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { if (ks == null) { return; } Enumeration aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = (String)aliases.nextElement(); if (ks.isKeyEntry(alias)) { Certificate[] certs; certs = ks.getCertificateChain(alias); if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) { if (!(certs instanceof X509Certificate[])) { Certificate[] tmp = new X509Certificate[certs.length]; System.arraycopy(certs, 0, tmp, 0, certs.length); certs = tmp; } Key key = ks.getKey(alias, password); certChainMap.put(alias, certs); keyMap.put(alias, key); } } } }
Example #24
Source File: KSTrustedCertificateEntryTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * Test for <codfe>toString()</code> method * Assertion: returns non null string */ public void testToString() { Certificate cert = new MyCertificate("TEST", new byte[10]); KeyStore.TrustedCertificateEntry ksTCE = new KeyStore.TrustedCertificateEntry(cert); assertNotNull("toString() returns null string", ksTCE.toString()); }
Example #25
Source File: PolicyFile.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
private String getDN(String alias, KeyStore keystore) { Certificate cert = null; try { cert = keystore.getCertificate(alias); } catch (Exception e) { if (debug != null) { debug.println(" Error retrieving certificate for '" + alias + "': " + e.toString()); } return null; } if (cert == null || !(cert instanceof X509Certificate)) { if (debug != null) { debug.println(" -- No certificate for '" + alias + "' - ignoring entry"); } return null; } else { X509Certificate x509Cert = (X509Certificate)cert; // 4702543: X500 names with an EmailAddress // were encoded incorrectly. create new // X500Principal name with correct encoding X500Principal p = new X500Principal (x509Cert.getSubjectX500Principal().toString()); return p.getName(); } }
Example #26
Source File: JarURL.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { String userDir = System.getProperty("user.dir"); String jarURL = "jar:file:" + userDir + File.separator + "foo.jar!/"; URL codeSourceURL = new URL(jarURL); CodeSource cs = new CodeSource(codeSourceURL, new Certificate[0]); PermissionCollection perms = Policy.getPolicy().getPermissions(cs); if (!perms.implies(new AllPermission())) throw new Exception("FAILED: " + codeSourceURL + " not granted AllPermission"); }
Example #27
Source File: SSLContextImpl.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
private void checkAlgorithmConstraints(X509Certificate[] chain, AlgorithmConstraints constraints) throws CertificateException { try { // Does the certificate chain end with a trusted certificate? int checkedLength = chain.length - 1; Collection<X509Certificate> trustedCerts = new HashSet<>(); X509Certificate[] certs = tm.getAcceptedIssuers(); if ((certs != null) && (certs.length > 0)){ Collections.addAll(trustedCerts, certs); } if (trustedCerts.contains(chain[checkedLength])) { checkedLength--; } // A forward checker, need to check from trust to target if (checkedLength >= 0) { AlgorithmChecker checker = new AlgorithmChecker(constraints); checker.init(false); for (int i = checkedLength; i >= 0; i--) { Certificate cert = chain[i]; // We don't care about the unresolved critical extensions. checker.check(cert, Collections.<String>emptySet()); } } } catch (CertPathValidatorException cpve) { throw new CertificateException( "Certificates does not conform to algorithm constraints"); } }
Example #28
Source File: JKS.java From fdroidclient with GNU General Public License v3.0 | 5 votes |
private static void writeCert(DataOutputStream dout, Certificate cert) throws IOException, CertificateException { dout.writeUTF(cert.getType()); byte[] b = cert.getEncoded(); dout.writeInt(b.length); dout.write(b); }
Example #29
Source File: SunX509KeyManagerImpl.java From Bytecoder with Apache License 2.0 | 5 votes |
SunX509KeyManagerImpl(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { credentialsMap = new HashMap<String,X509Credentials>(); serverAliasCache = Collections.synchronizedMap( new HashMap<String,String[]>()); if (ks == null) { return; } for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); ) { String alias = aliases.nextElement(); if (!ks.isKeyEntry(alias)) { continue; } Key key = ks.getKey(alias, password); if (key instanceof PrivateKey == false) { continue; } Certificate[] certs = ks.getCertificateChain(alias); if ((certs == null) || (certs.length == 0) || !(certs[0] instanceof X509Certificate)) { continue; } if (!(certs instanceof X509Certificate[])) { Certificate[] tmp = new X509Certificate[certs.length]; System.arraycopy(certs, 0, tmp, 0, certs.length); certs = tmp; } X509Credentials cred = new X509Credentials((PrivateKey)key, (X509Certificate[])certs); credentialsMap.put(alias, cred); if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) { SSLLogger.fine("found key for : " + alias, (Object[])certs); } } }
Example #30
Source File: JarLoader.java From spliceengine with GNU Affero General Public License v3.0 | 5 votes |
/** * Validate the security certificates (signers) for the class data. */ private Certificate[] getSigners(String className, JarEntry je) throws IOException { try { Certificate[] list = je.getCertificates(); if ((list == null) || (list.length == 0)) { return null; } for (Certificate aList : list) { if (!(aList instanceof X509Certificate)) { String msg = MessageService.getTextMessage( MessageId.CM_UNKNOWN_CERTIFICATE, className, getJarName()); throw new SecurityException(msg); } X509Certificate cert = (X509Certificate) aList; cert.checkValidity(); } return list; } catch (GeneralSecurityException gse) { // convert this into an unchecked security // exception. Unchecked as eventually it has // to pass through a method that's only throwing // ClassNotFoundException throw handleException(gse, className); } }