Java Code Examples for java.security.cert.Certificate

The following are top voted examples for showing how to use java.security.cert.Certificate. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: MVJarSigningTest.java   View source code 7 votes vote down vote up
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);
        }
    }
}
 
Example 2
Project: openjdk-jdk10   File: JceKeyStore.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 3
Project: osc-core   File: X509TrustManagerFactory.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: GitHub   File: Cache.java   View source code 6 votes vote down vote up
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());
  }
}
 
Example 5
Project: cas-5.1.0   File: FileTrustStoreSslSocketFactory.java   View source code 6 votes vote down vote up
@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");
    }
}
 
Example 6
Project: GitHub   File: Handshake.java   View source code 6 votes vote down vote up
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);
}
 
Example 7
Project: mi-firma-android   File: AOXAdESTriPhaseSigner.java   View source code 6 votes vote down vote up
@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
	);
}
 
Example 8
Project: openjdk-jdk10   File: JavaKeyStore.java   View source code 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 9
Project: wowza-letsencrypt-converter   File: PemCertKeyTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 10
Project: OpenJSharp   File: Main.java   View source code 6 votes vote down vote up
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;
    }
 
Example 11
Project: openjdk-jdk10   File: HandshakeCompletedEvent.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: jdk8u-jdk   File: ConvertP12Test.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 13
Project: OpenJSharp   File: JavaKeyStore.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: jdk8u-jdk   File: JavaKeyStore.java   View source code 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 15
Project: GitHub   File: CallTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 16
Project: OpenJSharp   File: DomainKeyStore.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 17
Project: openjdk-jdk10   File: PKCS12KeyStore.java   View source code 6 votes vote down vote up
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;
}
 
Example 18
Project: neoscada   File: XMLSignatureWidgetFactory.java   View source code 6 votes vote down vote up
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 () ) );
    }
}
 
Example 19
Project: GetApkSignInfo   File: Main.java   View source code 6 votes vote down vote up
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;
}
 
Example 20
Project: jdk8u-jdk   File: JceKeyStore.java   View source code 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) {
    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;
}
 
Example 21
Project: ats-framework   File: SslUtils.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 22
Project: jdk8u-jdk   File: PKCS12KeyStore.java   View source code 6 votes vote down vote up
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 +
            "'");
    }
}
 
Example 23
Project: cyberduck   File: AbstractX509KeyManager.java   View source code 6 votes vote down vote up
/**
 * @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;
}
 
Example 24
Project: OpenJSharp   File: JceKeyStore.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: jdk8u-jdk   File: PrivateKeyResolver.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: javaide   File: DebugKeyProvider.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 27
Project: BTNotifierAndroid   File: SslUtils.java   View source code 5 votes vote down vote up
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);
}
 
Example 28
Project: https-github.com-apache-zookeeper   File: NettyServerCnxn.java   View source code 5 votes vote down vote up
@Override
public void setClientCertificateChain(Certificate[] chain) {
    if (chain == null)
    {
        clientChain = null;
    } else {
        clientChain = Arrays.copyOf(chain, chain.length);
    }
}
 
Example 29
Project: OpenJSharp   File: X509CertImpl.java   View source code 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 30
Project: xitk   File: XiKeyStoreSpi.java   View source code 5 votes vote down vote up
@Override
public String engineGetCertificateAlias(Certificate cert) {
    for (String alias : keyCerts.keySet()) {
        if (keyCerts.get(alias).getCertificate().equals(cert)) {
            return alias;
        }
    }

    return null;
}
 
Example 31
Project: openjdk-jdk10   File: DefineClass.java   View source code 5 votes vote down vote up
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]));
    }
 
Example 32
Project: OpenJSharp   File: Main.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 33
Project: ditb   File: KeyStoreTestUtil.java   View source code 5 votes vote down vote up
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);
}
 
Example 34
Project: openjdk-jdk10   File: PolicyFile.java   View source code 5 votes vote down vote up
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 35
Project: jdk8u-jdk   File: KeychainStore.java   View source code 5 votes vote down vote up
/**
    * 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);
    }
}
 
Example 36
Project: OpenJSharp   File: PrivateKeyResolver.java   View source code 5 votes vote down vote up
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;
}
 
Example 37
Project: openjdk-jdk10   File: HandshakeMessage.java   View source code 5 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 38
Project: OpenJSharp   File: Timestamp.java   View source code 5 votes vote down vote up
/**
 * 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 39
Project: OpenJSharp   File: ClassLoader.java   View source code 5 votes vote down vote up
private void postDefineClass(Class<?> c, ProtectionDomain pd)
{
    if (pd.getCodeSource() != null) {
        Certificate certs[] = pd.getCodeSource().getCertificates();
        if (certs != null)
            setSigners(c, certs);
    }
}
 
Example 40
Project: mi-firma-android   File: AOXAdESASiCSTriPhaseSigner.java   View source code 5 votes vote down vote up
@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$
}