java.security.cert.Certificate源码实例Demo

java.security.cert.PKIXCertPathValidatorResult#java.security.cert.Certificate源码实例Demo

下面列出了java.security.cert.PKIXCertPathValidatorResult#java.security.cert.Certificate 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk8u-backup   文件: KeychainStore.java
/**
    * 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;
}
 
源代码2 项目: Bytecoder   文件: JavaKeyStore.java
/**
 * 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;
    }
}
 
源代码3 项目: cloudstack   文件: CertServiceImpl.java
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);
    }
}
 
源代码4 项目: openjdk-8   文件: UntrustedChecker.java
@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());
    }
}
 
源代码5 项目: TencentKona-8   文件: Activation.java
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;
}
 
源代码6 项目: knopflerfish.org   文件: Archive.java
/**
 *
 */
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);
      }
    }
  }
}
 
源代码7 项目: knopflerfish.org   文件: Archive.java
/**
 * 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!?
}
 
源代码8 项目: openjdk-jdk8u   文件: X509KeyManagerImpl.java
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);
    }
}
 
源代码9 项目: hottub   文件: MetadataEmptyTest.java
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");
}
 
源代码10 项目: jdk8u_jdk   文件: UnresolvedPermission.java
/**
 * 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());
            }
        }
    }
}
 
源代码11 项目: hottub   文件: DomainKeyStore.java
/**
 * 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;
}
 
源代码12 项目: openjdk-8   文件: HandshakeMessage.java
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()]);
}
 
源代码13 项目: openjdk-8   文件: DomainKeyStore.java
/**
 * 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;
}
 
源代码14 项目: openjdk-jdk9   文件: DupImport.java
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");
    }
 
源代码15 项目: fdroidclient   文件: JKS.java
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);
}
 
源代码16 项目: openjdk-8-source   文件: CertReplace.java
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]);
}
 
源代码17 项目: cs-actions   文件: SendMailService.java
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]);
    }
}
 
源代码18 项目: jetlinks-community   文件: KeyStoreHelper.java
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;
}
 
@Override
public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
    synchronized (ReferenceCountedOpenSslEngine.this) {
        if (isEmpty(peerCerts)) {
            throw new SSLPeerUnverifiedException("peer not verified");
        }
        return peerCerts.clone();
    }
}
 
源代码20 项目: Tomcat8-Source-Read   文件: OpenSSLEngine.java
@Override
public Principal getLocalPrincipal() {
    Certificate[] local = getLocalCertificates();
    if (local == null || local.length == 0) {
        return null;
    }
    return principal(local);
}
 
源代码21 项目: j2objc   文件: X509Factory.java
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;
}
 
源代码22 项目: freehealth-connector   文件: KeyStoreCredential.java
public Certificate[] getCertificateChain() {
   try {
      return this.keystore.getCertificateChain(this.alias);
   } catch (KeyStoreException var2) {
      LOG.error(var2.getMessage());
      throw new CredentialException(var2);
   }
}
 
源代码23 项目: openjdk-jdk8u-backup   文件: SSLContextImpl.java
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);
    }
}
 
源代码24 项目: Aria   文件: SSLContextUtil.java
/**
 * @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;
}
 
源代码25 项目: dragonwell8_jdk   文件: JarURL.java
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");
}
 
源代码26 项目: j2objc   文件: KSTrustedCertificateEntryTest.java
/**
 * 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());
}
 
源代码27 项目: hottub   文件: MyKeyManager.java
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);
            }
        }
    }
}
 
源代码28 项目: jdk8u60   文件: SSLContextImpl.java
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");
    }
}
 
源代码29 项目: spliceengine   文件: JarLoader.java
/**
 * 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);
    }
    
}
 
@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());
}