Java Code Examples for java.security.cert.Certificate

The following examples show how to use java.security.cert.Certificate. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
    * 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 2
Source Project: Bytecoder   Source File: JavaKeyStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source Project: cloudstack   Source File: CertServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: openjdk-8   Source File: UntrustedChecker.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 5
Source Project: TencentKona-8   Source File: Activation.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 6
/**
 *
 */
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 7
/**
 * 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 8
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 9
Source Project: hottub   Source File: MetadataEmptyTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 10
/**
 * 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 11
Source Project: hottub   Source File: DomainKeyStore.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 12
Source Project: openjdk-8   Source File: HandshakeMessage.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 13
Source Project: openjdk-8   Source File: DomainKeyStore.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 14
Source Project: openjdk-jdk9   Source File: DupImport.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 15
Source Project: fdroidclient   Source File: JKS.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 16
Source Project: openjdk-8-source   Source File: CertReplace.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 17
Source Project: cs-actions   Source File: SendMailService.java    License: Apache License 2.0 5 votes vote down vote up
private void addEncryptionSettings() throws Exception {
    URL keystoreUrl = new URL(input.getEncryptionKeystore());
    try (InputStream publicKeystoreInputStream = keystoreUrl.openStream()) {
        char[] smimePw = input.getEncryptionKeystorePassword().toCharArray();
        gen = new SMIMEEnvelopedGenerator();
        Security.addProvider(new BouncyCastleProvider());
        KeyStore ks = KeyStore.getInstance(SecurityConstants.PKCS_KEYSTORE_TYPE, SecurityConstants.BOUNCY_CASTLE_PROVIDER);
        ks.load(publicKeystoreInputStream, smimePw);

        if (StringUtils.EMPTY.equals(input.getEncryptionKeyAlias())) {
            Enumeration aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();

                if (ks.isKeyEntry(alias)) {
                    input.setEncryptionKeyAlias(alias);
                }
            }
        }

        if (StringUtils.EMPTY.equals(input.getEncryptionKeyAlias())) {
            throw new Exception(ExceptionMsgs.PUBLIC_KEY_ERROR_MESSAGE);
        }

        Certificate[] chain = ks.getCertificateChain(input.getEncryptionKeyAlias());

        if (chain == null) {
            throw new Exception("The key with alias \"" + input.getEncryptionKeyAlias() + "\" can't be found in given keystore.");
        }

        //
        // create the generator for creating an smime/encrypted message
        //
        gen.addKeyTransRecipient((X509Certificate) chain[0]);
    }
}
 
Example 18
Source Project: jetlinks-community   Source File: KeyStoreHelper.java    License: Apache License 2.0 5 votes vote down vote up
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 19
@Override
public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
    synchronized (ReferenceCountedOpenSslEngine.this) {
        if (isEmpty(peerCerts)) {
            throw new SSLPeerUnverifiedException("peer not verified");
        }
        return peerCerts.clone();
    }
}
 
Example 20
Source Project: Tomcat8-Source-Read   Source File: OpenSSLEngine.java    License: MIT License 5 votes vote down vote up
@Override
public Principal getLocalPrincipal() {
    Certificate[] local = getLocalCertificates();
    if (local == null || local.length == 0) {
        return null;
    }
    return principal(local);
}
 
Example 21
Source Project: j2objc   Source File: X509Factory.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<? extends java.security.cert.Certificate>
    parseX509orPKCS7Cert(InputStream is)
    throws CertificateException, IOException
{
    Collection<X509CertImpl> coll = new ArrayList<>();
    byte[] data = readOneBlock(is);
    if (data == null) {
        return new ArrayList<>(0);
    }
    try {
        PKCS7 pkcs7 = new PKCS7(data);
        X509Certificate[] certs = pkcs7.getCertificates();
        // certs are optional in PKCS #7
        if (certs != null) {
            return Arrays.asList(certs);
        } else {
            // no crls provided
            return new ArrayList<>(0);
        }
    } catch (ParsingException e) {
        while (data != null) {
            coll.add(new X509CertImpl(data));
            data = readOneBlock(is);
        }
    }
    return coll;
}
 
Example 22
public Certificate[] getCertificateChain() {
   try {
      return this.keystore.getCertificateChain(this.alias);
   } catch (KeyStoreException var2) {
      LOG.error(var2.getMessage());
      throw new CredentialException(var2);
   }
}
 
Example 23
private void checkAlgorithmConstraints(X509Certificate[] chain,
        AlgorithmConstraints constraints, boolean isClient) 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, null,
                            (isClient ? Validator.VAR_TLS_CLIENT : Validator.VAR_TLS_SERVER));
            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 do not conform to algorithm constraints", cpve);
    }
}
 
Example 24
Source Project: Aria   Source File: SSLContextUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param cacheKey 别名 + 证书路径,然后取md5
 */
private static SSLContext createContext(String caAlias, Certificate ca, String protocol,
    String cacheKey) {
  try {
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(caAlias, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);
    KeyManagerFactory kmf =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, null);

    // Create an SSLContext that uses our TrustManager
    SSLContext context =
        SSLContext.getInstance(TextUtils.isEmpty(protocol) ? ProtocolType.Default : protocol);
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    SSL_CACHE.put(cacheKey, context);
    return context;
  } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException | KeyManagementException | UnrecoverableKeyException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 25
Source Project: dragonwell8_jdk   Source File: JarURL.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 26
Source Project: j2objc   Source File: KSTrustedCertificateEntryTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 27
Source Project: hottub   Source File: MyKeyManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 28
Source Project: jdk8u60   Source File: SSLContextImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 29
/**
 * 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);
    }
    
}
 
Example 30
@Override public List<Certificate> getServerCertificateChain()
    throws SSLPeerUnverifiedException {
  if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
    throw new SSLPeerUnverifiedException(null);
  }
  return Arrays.asList(entry.peerCertificates.clone());
}