Java 类java.security.cert.Certificate 实例源码

项目:openjdk-jdk10    文件:MVJarSigningTest.java   
private static void signWithJarSignerAPI(String jarName)
        throws Throwable {
    // Get JarSigner
    try (FileInputStream fis = new FileInputStream(KEYSTORE)) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(fis, STOREPASS.toCharArray());
            PrivateKey pk = (PrivateKey)ks.getKey(ALIAS, KEYPASS.toCharArray());
            Certificate cert = ks.getCertificate(ALIAS);
            JarSigner signer = new JarSigner.Builder(pk,
                    CertificateFactory.getInstance("X.509").generateCertPath(
                            Collections.singletonList(cert)))
                    .build();
        // Sign jar
        try (ZipFile src = new JarFile(jarName);
                FileOutputStream out = new FileOutputStream(SIGNED_JAR)) {
            signer.sign(src,out);
        }
    }
}
项目:openjdk-jdk10    文件:JceKeyStore.java   
/**
 * Assigns the given key (that has already been protected) to the given
 * alias.
 *
 * <p>If the protected key is of type
 * <code>java.security.PrivateKey</code>,
 * it must be accompanied by a certificate chain certifying the
 * corresponding public key.
 *
 * <p>If the given alias already exists, the keystore information
 * associated with it is overridden by the given key (and possibly
 * certificate chain).
 *
 * @param alias the alias name
 * @param key the key (in protected format) to be associated with the alias
 * @param chain the certificate chain for the corresponding public
 * key (only useful if the protected key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if this operation fails.
 */
public void engineSetKeyEntry(String alias, byte[] key,
                              Certificate[] chain)
    throws KeyStoreException
{
    synchronized(entries) {
        // We assume it's a private key, because there is no standard
        // (ASN.1) encoding format for wrapped secret keys
        PrivateKeyEntry entry = new PrivateKeyEntry();
        entry.date = new Date();

        entry.protectedKey = key.clone();
        if ((chain != null) &&
            (chain.length != 0)) {
            entry.chain = chain.clone();
        } else {
            entry.chain = null;
        }

        entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
    }
}
项目:osc-core    文件:X509TrustManagerFactory.java   
private Certificate[] tryParsePKIPathChain(File chainFile)
        throws IOException, FileNotFoundException, CertificateException {

    Certificate[] internalCertificateChain = null;
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try (FileInputStream inputStream = new FileInputStream(chainFile)) {
        CertPath certPath = cf.generateCertPath(inputStream);
        List<? extends Certificate> certList = certPath.getCertificates();
        internalCertificateChain = certList.toArray(new Certificate[]{});
    } catch (CertificateException e){
        LOG.info("Tried and failed to parse file as a PKI :" + chainFile.getName(), e);
    }

    return internalCertificateChain;
}
项目:GitHub    文件:Cache.java   
private List<Certificate> readCertificateList(BufferedSource source) throws IOException {
  int length = readInt(source);
  if (length == -1) return Collections.emptyList(); // OkHttp v1.2 used -1 to indicate null.

  try {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    List<Certificate> result = new ArrayList<>(length);
    for (int i = 0; i < length; i++) {
      String line = source.readUtf8LineStrict();
      Buffer bytes = new Buffer();
      bytes.write(ByteString.decodeBase64(line));
      result.add(certificateFactory.generateCertificate(bytes.inputStream()));
    }
    return result;
  } catch (CertificateException e) {
    throw new IOException(e.getMessage());
  }
}
项目:cas-5.1.0    文件:FileTrustStoreSslSocketFactory.java   
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {

    final boolean trusted = this.trustManagers.stream().anyMatch(trustManager -> {
        try {
            trustManager.checkServerTrusted(chain, authType);
            return true;
        } catch (final CertificateException e) {
            final String msg = "Unable to trust the server certificates [%s] for auth type [%s]: [%s]";
            LOGGER.debug(String.format(msg, Arrays.stream(chain).map(Certificate::toString).collect(Collectors.toSet()),
                    authType, e.getMessage()), e);
            return false;
        }
    });
    if (!trusted) {
        throw new CertificateException("None of the TrustManagers trust this certificate chain");
    }
}
项目:GitHub    文件:Handshake.java   
public static Handshake get(SSLSession session) {
  String cipherSuiteString = session.getCipherSuite();
  if (cipherSuiteString == null) throw new IllegalStateException("cipherSuite == null");
  CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);

  String tlsVersionString = session.getProtocol();
  if (tlsVersionString == null) throw new IllegalStateException("tlsVersion == null");
  TlsVersion tlsVersion = TlsVersion.forJavaName(tlsVersionString);

  Certificate[] peerCertificates;
  try {
    peerCertificates = session.getPeerCertificates();
  } catch (SSLPeerUnverifiedException ignored) {
    peerCertificates = null;
  }
  List<Certificate> peerCertificatesList = peerCertificates != null
      ? Util.immutableList(peerCertificates)
      : Collections.<Certificate>emptyList();

  Certificate[] localCertificates = session.getLocalCertificates();
  List<Certificate> localCertificatesList = localCertificates != null
      ? Util.immutableList(localCertificates)
      : Collections.<Certificate>emptyList();

  return new Handshake(tlsVersion, cipherSuite, peerCertificatesList, localCertificatesList);
}
项目:mi-firma-android    文件:AOXAdESTriPhaseSigner.java   
@Override
public byte[] sign(final byte[] data,
                   final String algorithm,
                   final PrivateKey key,
                   final Certificate[] certChain,
                   final Properties xParams) throws AOException {
    return triPhaseOperation(
        this.signFormat,
        CRYPTO_OPERATION_SIGN,
        data,
        algorithm,
        key,
        certChain,
        xParams
    );
}
项目:openjdk-jdk10    文件: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;
    }
}
项目:wowza-letsencrypt-converter    文件:PemCertKeyTest.java   
@Test
public void testCertOnly() throws Exception {
    InputStream in = new FileInputStream("src/test/resources/pem/cert.pem");
    PemCertKey t = new PemCertKey(in);

    Certificate cert = t.getCertificate();
    assertThat(cert).isNotNull();
    assertThat(cert.getType()).isEqualTo("X.509");

    assertThat(t.hasCertificate()).isTrue();
    assertThat(t.getCertificateChain()).hasSize(1);
    assertThat(t.getCertificateChain()[0]).isEqualTo(cert);

    assertThat(t.matchesCertificate(cert)).isTrue();
    assertThat(t.matchesCertificate(null)).isFalse();

    assertThat(t.hasKey()).isFalse();
    assertThat(t.getPrivateKey()).isNull();

    assertThat(t.getCreationDate()).isCloseTo(new Date(), 5000);
}
项目:OpenJSharp    文件:Main.java   
X509Certificate getTsaCert(String alias) {

        java.security.cert.Certificate cs = null;

        try {
            cs = store.getCertificate(alias);
        } catch (KeyStoreException kse) {
            // this never happens, because keystore has been loaded
        }
        if (cs == null || (!(cs instanceof X509Certificate))) {
            MessageFormat form = new MessageFormat(rb.getString
                ("Certificate.not.found.for.alias.alias.must.reference.a.valid.KeyStore.entry.containing.an.X.509.public.key.certificate.for.the"));
            Object[] source = {alias, alias};
            error(form.format(source));
        }
        return (X509Certificate) cs;
    }
项目:openjdk-jdk10    文件:HandshakeCompletedEvent.java   
/**
 * Returns the principal that was sent to the peer during handshaking.
 *
 * @return the principal sent to the peer. Returns an X500Principal
 * of the end-entity certificate for X509-based cipher suites, and
 * KerberosPrincipal for Kerberos cipher suites. If no principal was
 * sent, then null is returned.
 *
 * @see #getLocalCertificates()
 * @see #getPeerPrincipal()
 *
 * @since 1.5
 */
public Principal getLocalPrincipal()
{
    Principal principal;
    try {
        principal = session.getLocalPrincipal();
    } catch (AbstractMethodError e) {
        principal = null;
        // if the provider does not support it, fallback to local certs.
        // return the X500Principal of the end-entity cert.
        Certificate[] certs = getLocalCertificates();
        if (certs != null) {
            principal =
                    ((X509Certificate)certs[0]).getSubjectX500Principal();
        }
    }
    return principal;
}
项目:jdk8u-jdk    文件:ConvertP12Test.java   
private void compareKeyEntry(KeyStore a, KeyStore b, String aPass,
        String bPass, String alias) throws KeyStoreException,
        UnrecoverableKeyException, NoSuchAlgorithmException {
    Certificate[] certsA = a.getCertificateChain(alias);
    Certificate[] certsB = b.getCertificateChain(alias);

    if (!Arrays.equals(certsA, certsB)) {
        throw new RuntimeException("Certs don't match for alias:" + alias);
    }

    Key keyA = a.getKey(alias, aPass.toCharArray());
    Key keyB = b.getKey(alias, bPass.toCharArray());

    if (!keyA.equals(keyB)) {
        throw new RuntimeException(
                "Key don't match for alias:" + alias);
    }
}
项目:OpenJSharp    文件:JavaKeyStore.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) {
    Certificate certElem;

    for (Enumeration<String> e = entries.keys(); e.hasMoreElements(); ) {
        String alias = 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;
}
项目:jdk8u-jdk    文件: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;
    }
}
项目:GitHub    文件:CallTest.java   
@Test public void matchingPinnedCertificate() throws Exception {
  enableTls();
  server.enqueue(new MockResponse());
  server.enqueue(new MockResponse());

  // Make a first request without certificate pinning. Use it to collect certificates to pin.
  Request request1 = new Request.Builder().url(server.url("/")).build();
  Response response1 = client.newCall(request1).execute();
  CertificatePinner.Builder certificatePinnerBuilder = new CertificatePinner.Builder();
  for (Certificate certificate : response1.handshake().peerCertificates()) {
    certificatePinnerBuilder.add(server.getHostName(), CertificatePinner.pin(certificate));
  }
  response1.body().close();

  // Make another request with certificate pinning. It should complete normally.
  client = client.newBuilder()
      .certificatePinner(certificatePinnerBuilder.build())
      .build();
  Request request2 = new Request.Builder().url(server.url("/")).build();
  Response response2 = client.newCall(request2).execute();
  assertNotSame(response2.handshake(), response1.handshake());
  response2.body().close();
}
项目:OpenJSharp    文件:DomainKeyStore.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) {

    try {

        String alias = null;
        for (KeyStore keystore : keystores.values()) {
            if ((alias = keystore.getCertificateAlias(cert)) != null) {
                break;
            }
        }
        return alias;

    } catch (KeyStoreException e) {
        throw new IllegalStateException(e);
    }
}
项目:openjdk-jdk10    文件:PKCS12KeyStore.java   
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;
    }

    // Check for loops in the chain. If there are repeated certs,
    // the Set of certs in the chain will contain fewer certs than
    // the chain
    Set<Certificate> set = new HashSet<>(Arrays.asList(certChain));
    return set.size() == certChain.length;
}
项目:neoscada    文件:XMLSignatureWidgetFactory.java   
private void setKeyCert ( final KeyInformation ki )
{
    if ( ki == null )
    {
        this.text.setText ( "<none>" );
        return;
    }

    final Certificate certificate = ki.getCertificate ();
    final Key key = ki.getKey ();

    if ( certificate instanceof X509Certificate )
    {
        this.text.setText ( "" + ( (X509Certificate)certificate ).getSubjectX500Principal () );
    }
    else
    {
        this.text.setText ( String.format ( "%s - %s - %s", ki.getAlias (), key.getFormat (), key.getAlgorithm () ) );
    }
}
项目:GetApkSignInfo    文件:Main.java   
private static Certificate[] loadCertificates(JarFile jarFile, JarEntry jarEntry) {
    InputStream is;
    try {
        // We must read the stream for the JarEntry to retrieve its certificates
        is = jarFile.getInputStream(jarEntry);
        readFullyIgnoringContents(is);

        return jarEntry.getCertificates();
    } catch (IOException | RuntimeException e) {
        System.err.println("Failed reading " + jarEntry.getName() + " in " + jarFile);

        if (DEBUG) e.printStackTrace();
        System.exit(1);
    }
    return null;
}
项目:jdk8u-jdk    文件:JceKeyStore.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) {
    Certificate cert = null;

    Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));

    if (entry != null) {
        if (entry instanceof TrustedCertEntry) {
            cert = ((TrustedCertEntry)entry).cert;
        } else if ((entry instanceof PrivateKeyEntry) &&
                   (((PrivateKeyEntry)entry).chain != null)) {
            cert = ((PrivateKeyEntry)entry).chain[0];
        }
    }

    return cert;
}
项目:ats-framework    文件:SslUtils.java   
/**
 * Load a public key
 * 
 * @param keystore
 * @param publicKeyAlias
 * @return
 */
public static PublicKey loadPublicKey( KeyStore keystore, String publicKeyAlias ) {

    Certificate certificate;
    try {
        certificate = keystore.getCertificate(publicKeyAlias);
    } catch (KeyStoreException e) {
        throw new RuntimeException("Error loading public key for alias '" + publicKeyAlias + "'", e);
    }

    if (certificate == null) {
        throw new RuntimeException("Error loading public key for alias '" + publicKeyAlias
                                   + "': Given alias does not exist or does not contain a certificate.");
    }

    if (log.isDebugEnabled()) {
        log.debug("Loaded public key for alias '" + publicKeyAlias + "'");
    }
    return certificate.getPublicKey();
}
项目:jdk8u-jdk    文件:PKCS12KeyStore.java   
private void setCertEntry(String alias, Certificate cert,
    Set<KeyStore.Entry.Attribute> attributes) throws KeyStoreException {

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entry != null && entry instanceof KeyEntry) {
        throw new KeyStoreException("Cannot overwrite own certificate");
    }

    CertEntry certEntry =
        new CertEntry((X509Certificate) cert, null, alias, AnyUsage,
            attributes);
    certificateCount++;
    entries.put(alias, certEntry);

    if (debug != null) {
        debug.println("Setting a trusted certificate at alias '" + alias +
            "'");
    }
}
项目:cyberduck    文件:AbstractX509KeyManager.java   
/**
 * @param issuers The list of acceptable CA issuer subject names or null if it does not matter which issuers are used
 * @return True if certificate matches issuer and key type
 */
protected boolean matches(final Certificate c, final String[] keyTypes, final Principal[] issuers) {
    if(!(c instanceof X509Certificate)) {
        log.warn(String.format("Certificate %s is not of type X509", c));
        return false;
    }
    if(!Arrays.asList(keyTypes).contains(c.getPublicKey().getAlgorithm())) {
        log.warn(String.format("Key type %s does not match any of %s", c.getPublicKey().getAlgorithm(),
                Arrays.toString(keyTypes)));
        return false;
    }
    if(null == issuers || Arrays.asList(issuers).isEmpty()) {
        // null if it does not matter which issuers are used
        return true;
    }
    final X500Principal issuer = ((X509Certificate) c).getIssuerX500Principal();
    if(!Arrays.asList(issuers).contains(issuer)) {
        log.warn(String.format("Issuer %s does not match", issuer));
        return false;
    }
    return true;
}
项目:OpenJSharp    文件:JceKeyStore.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) {
    Certificate certElem;

    Enumeration<String> e = entries.keys();
    while (e.hasMoreElements()) {
        String alias = e.nextElement();
        Object entry = entries.get(alias);
        if (entry instanceof TrustedCertEntry) {
            certElem = ((TrustedCertEntry)entry).cert;
        } else if ((entry instanceof PrivateKeyEntry) &&
                   (((PrivateKeyEntry)entry).chain != null)) {
            certElem = ((PrivateKeyEntry)entry).chain[0];
        } else {
            continue;
        }
        if (certElem.equals(cert)) {
            return alias;
        }
    }
    return null;
}
项目:jdk8u-jdk    文件:PrivateKeyResolver.java   
private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?");

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {

            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);

                if (certSKI.equals(x509SKI)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");

                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    } catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                        // Keep searching
                    }
                }
            }
        }
    }

    return null;
}
项目:javaide    文件:DebugKeyProvider.java   
/**
 * Returns the debug {@link Certificate} to use to sign applications for debug purpose.
 * @return the certificate or <code>null</code> if its creation failed.
 */
@SuppressWarnings("unused") // the thrown Exceptions are not actually thrown
public Certificate getCertificate() throws KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, UnrecoverableEntryException {
    if (mEntry != null) {
        return mEntry.getCertificate();
    }

    return null;
}
项目:BTNotifierAndroid    文件:SslUtils.java   
private void trustCertificate(Certificate cert, String deviceLabel) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
    KeyStore ts = getKeyStore();

    Log.i(TAG, "Adding certificate ID " + deviceLabel + " to Trust store (" + trustStorePath + "): " + cert);
    ts.setCertificateEntry(deviceLabel, cert);

    ts.store(new FileOutputStream(trustStorePath), null);
}
项目:https-github.com-apache-zookeeper    文件:NettyServerCnxn.java   
@Override
public void setClientCertificateChain(Certificate[] chain) {
    if (chain == null)
    {
        clientChain = null;
    } else {
        clientChain = Arrays.copyOf(chain, chain.length);
    }
}
项目:OpenJSharp    文件:X509CertImpl.java   
/**
 * Returned the encoding of the given certificate for internal use.
 * Callers must guarantee that they neither modify it nor expose it
 * to untrusted code. Uses getEncodedInternal() if the certificate
 * is instance of X509CertImpl, getEncoded() otherwise.
 */
public static byte[] getEncodedInternal(Certificate cert)
        throws CertificateEncodingException {
    if (cert instanceof X509CertImpl) {
        return ((X509CertImpl)cert).getEncodedInternal();
    } else {
        return cert.getEncoded();
    }
}
项目:xitk    文件:XiKeyStoreSpi.java   
@Override
public String engineGetCertificateAlias(Certificate cert) {
    for (String alias : keyCerts.keySet()) {
        if (keyCerts.get(alias).getCertificate().equals(cert)) {
            return alias;
        }
    }

    return null;
}
项目:openjdk-jdk10    文件:DefineClass.java   
public static void main(String[] args) throws Exception {

        Security.addProvider(new TestProvider());

        MySecureClassLoader scl = new MySecureClassLoader();

        File policyFile = new File(System.getProperty("test.src", "."),
                                   "DefineClass.policy");
        Policy p = Policy.getInstance("JavaPolicy",
                                      new URIParameter(policyFile.toURI()));
        Policy.setPolicy(p);

        System.setSecurityManager(new SecurityManager());
        ArrayList<Permission> perms1 = getPermissions(scl, p,
                                                      "http://localhost/",
                                                      "foo.Foo", FOO_CLASS,
                                                      null);
        checkPerms(perms1, GRANTED_PERMS);
        ArrayList<Permission> perms2 = getPermissions(scl, p,
                                                      "http://127.0.0.1/",
                                                      "bar.Bar", BAR_CLASS,
                                                      null);
        checkPerms(perms2, GRANTED_PERMS);
        assert(perms1.equals(perms2));

        // check that class signed by baz is granted an additional permission
        Certificate[] chain = new Certificate[] {getCert(BAZ_CERT)};
        ArrayList<Permission> perms3 = getPermissions(scl, p,
                                                      "http://localhost/",
                                                      "baz.Baz", BAZ_CLASS,
                                                      chain);
        List<Permission> perms = new ArrayList<>(Arrays.asList(GRANTED_PERMS));
        perms.add(new PropertyPermission("user.dir", "read"));
        checkPerms(perms3, perms.toArray(new Permission[0]));
    }
项目:OpenJSharp    文件:Main.java   
void validateCertChain(List<? extends Certificate> certs) throws Exception {
    int cpLen = 0;
    out: for (; cpLen<certs.size(); cpLen++) {
        for (TrustAnchor ta: pkixParameters.getTrustAnchors()) {
            if (ta.getTrustedCert().equals(certs.get(cpLen))) {
                break out;
            }
        }
    }
    if (cpLen > 0) {
        CertPath cp = certificateFactory.generateCertPath(
                (cpLen == certs.size())? certs: certs.subList(0, cpLen));
        validator.validate(cp, pkixParameters);
    }
}
项目:ditb    文件:KeyStoreTestUtil.java   
public static void createKeyStore(String filename,
                                  String password, String alias,
                                  Key privateKey, Certificate cert)
  throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setKeyEntry(alias, privateKey, password.toCharArray(),
                 new Certificate[]{cert});
  saveKeyStore(ks, filename, password);
}
项目:openjdk-jdk10    文件:PolicyFile.java   
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();
    }
}
项目:jdk8u-jdk    文件:KeychainStore.java   
/**
    * Assigns the given certificate to the given alias.
 *
 * <p>If the given alias already exists in this keystore and identifies a
 * <i>trusted certificate entry</i>, the certificate associated with it is
 * overridden by the given certificate.
 *
 * @param alias the alias name
 * @param cert the certificate
 *
 * @exception KeyStoreException if the given alias already exists and does
 * not identify a <i>trusted certificate entry</i>, or this operation
 * fails for some other reason.
 */
public void engineSetCertificateEntry(String alias, Certificate cert)
    throws KeyStoreException
{
    permissionCheck();

    synchronized(entries) {

        Object entry = entries.get(alias.toLowerCase());
        if ((entry != null) && (entry instanceof KeyEntry)) {
            throw new KeyStoreException
            ("Cannot overwrite key entry with certificate");
        }

        // This will be slow, but necessary.  Enumerate the values and then see if the cert matches the one in the trusted cert entry.
        // Security framework doesn't support the same certificate twice in a keychain.
        Collection allValues = entries.values();

        for (Object value : allValues) {
            if (value instanceof TrustedCertEntry) {
                TrustedCertEntry tce = (TrustedCertEntry)value;
                if (tce.cert.equals(cert)) {
                    throw new KeyStoreException("Keychain does not support mulitple copies of same certificate.");
                }
            }
        }

        TrustedCertEntry trustedCertEntry = new TrustedCertEntry();
        trustedCertEntry.cert = cert;
        trustedCertEntry.date = new Date();
        String lowerAlias = alias.toLowerCase();
        if (entries.get(lowerAlias) != null) {
            deletedEntries.put(lowerAlias, entries.get(lowerAlias));
        }
        entries.put(lowerAlias, trustedCertEntry);
        addedEntries.put(lowerAlias, trustedCertEntry);
    }
}
项目:OpenJSharp    文件:PrivateKeyResolver.java   
private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?");

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {

            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                XMLX509SubjectName certSN =
                    new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert);

                if (certSN.equals(x509SubjectName)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");

                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    } catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                        // Keep searching
                    }
                }
            }
        }
    }

    return null;
}
项目:openjdk-jdk10    文件: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()]);
}
项目:OpenJSharp    文件:Timestamp.java   
/**
 * 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();
}
项目:OpenJSharp    文件:ClassLoader.java   
private void postDefineClass(Class<?> c, ProtectionDomain pd)
{
    if (pd.getCodeSource() != null) {
        Certificate certs[] = pd.getCodeSource().getCertificates();
        if (certs != null)
            setSigners(c, certs);
    }
}
项目:mi-firma-android    文件:AOXAdESASiCSTriPhaseSigner.java   
@Override
public byte[] cosign(final byte[] data,
                     final byte[] sign,
                     final String algorithm,
                     final PrivateKey key,
                     final Certificate[] certChain,
                     final Properties xParams) throws AOException {
    throw new UnsupportedOperationException("No se soportan cofirmas trifasicas XAdES-ASiC-S"); //$NON-NLS-1$
}