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   Source Code and License 8 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: jdk8u-jdk   File: PKCS12KeyStore.java   Source Code and License 7 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 3
Project: openjdk-jdk10   File: JceKeyStore.java   Source Code and License 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 4
Project: osc-core   File: X509TrustManagerFactory.java   Source Code and License 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 5
Project: GitHub   File: Cache.java   Source Code and License 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 6
Project: cas-5.1.0   File: FileTrustStoreSslSocketFactory.java   Source Code and License 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 7
Project: GitHub   File: Handshake.java   Source Code and License 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 8
Project: mi-firma-android   File: AOXAdESTriPhaseSigner.java   Source Code and License 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 9
Project: openjdk-jdk10   File: JavaKeyStore.java   Source Code and License 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 10
Project: wowza-letsencrypt-converter   File: PemCertKeyTest.java   Source Code and License 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 11
Project: OpenJSharp   File: Main.java   Source Code and License 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 12
Project: openjdk-jdk10   File: HandshakeCompletedEvent.java   Source Code and License 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 13
Project: jdk8u-jdk   File: ConvertP12Test.java   Source Code and License 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 14
Project: OpenJSharp   File: JavaKeyStore.java   Source Code and License 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 15
Project: jdk8u-jdk   File: JavaKeyStore.java   Source Code and License 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 16
Project: GitHub   File: CallTest.java   Source Code and License 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 17
Project: OpenJSharp   File: DomainKeyStore.java   Source Code and License 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 18
Project: openjdk-jdk10   File: PKCS12KeyStore.java   Source Code and License 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 19
Project: neoscada   File: XMLSignatureWidgetFactory.java   Source Code and License 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 20
Project: GetApkSignInfo   File: Main.java   Source Code and License 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 21
Project: jdk8u-jdk   File: JceKeyStore.java   Source Code and License 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 22
Project: ats-framework   File: SslUtils.java   Source Code and License 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 23
Project: cyberduck   File: AbstractX509KeyManager.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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$
}
 
Example 41
Project: jdk8u-jdk   File: P11KeyStore.java   Source Code and License 5 votes vote down vote up
/**
 * Assigns the given key to the given alias, protecting it with the given
 * password.
 *
 * <p>If the given 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 to be associated with the alias
 * @param password the password to protect the key
 * @param chain the certificate chain for the corresponding public
 * key (only required if the given key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if the given key cannot be protected, or
 * this operation fails for some other reason
 */
public synchronized void engineSetKeyEntry(String alias, Key key,
                               char[] password,
                               Certificate[] chain)
            throws KeyStoreException {

    token.ensureValid();
    checkWrite();

    if (!(key instanceof PrivateKey) && !(key instanceof SecretKey)) {
        throw new KeyStoreException("key must be PrivateKey or SecretKey");
    } else if (key instanceof PrivateKey && chain == null) {
        throw new KeyStoreException
            ("PrivateKey must be accompanied by non-null chain");
    } else if (key instanceof SecretKey && chain != null) {
        throw new KeyStoreException
            ("SecretKey must be accompanied by null chain");
    } else if (password != null &&
                !token.config.getKeyStoreCompatibilityMode()) {
        throw new KeyStoreException("Password must be null");
    }

    KeyStore.Entry entry = null;
    try {
        if (key instanceof PrivateKey) {
            entry = new KeyStore.PrivateKeyEntry((PrivateKey)key, chain);
        } else if (key instanceof SecretKey) {
            entry = new KeyStore.SecretKeyEntry((SecretKey)key);
        }
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new KeyStoreException(e);
    }
    engineSetEntry(alias, entry, new KeyStore.PasswordProtection(password));
}
 
Example 42
Project: RISE-V2G   File: SecurityUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the leaf certificate from a given certificate chain.
 * 
 * @param certChain The certificate chain given as an array of Certificate instances
 * @return The leaf certificate (begin not a CA)
 */
public static X509Certificate getLeafCertificate(Certificate[] certChain) {
	for (Certificate cert : certChain) {
		X509Certificate x509Cert = (X509Certificate) cert;
		// Check whether the pathLen constraint is set which indicates if this certificate is a CA
		if (x509Cert.getBasicConstraints() == -1) return x509Cert;
	}
	
	getLogger().warn("No leaf certificate found in given certificate chain");
	return null;
}
 
Example 43
Project: openjdk-jdk10   File: ScanSignedJar.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        System.out.println("Opening " + JAR_LOCATION + "...");
        JarInputStream inStream =
            new JarInputStream(new URL(JAR_LOCATION).openStream(), true);
        JarEntry entry;
        byte[] buffer = new byte[1024];

        while ((entry = inStream.getNextJarEntry()) != null) {

            // need to read the entry's data to see the certs.
            while(inStream.read(buffer) != -1)
                ;

            String name = entry.getName();
            long size = entry.getSize();
            Certificate[] certificates = entry.getCertificates();
            CodeSigner[] signers = entry.getCodeSigners();

            if (signers == null && certificates == null) {
                System.out.println("[unsigned]\t" + name + "\t(" + size +
                    " bytes)");
                if (name.equals("Count.class")) {
                    throw new Exception("Count.class should be signed");
                }
            } else if (signers != null && certificates != null) {
                System.out.println("[" + signers.length +
                    (signers.length == 1 ? " signer" : " signers") + "]\t" +
                    name + "\t(" + size + " bytes)");
            } else {
                System.out.println("[*ERROR*]\t" + name + "\t(" + size +
                    " bytes)");
                throw new Exception("Cannot determine whether the entry is " +
                    "signed or unsigned (signers[] doesn't match certs[]).");
            }
        }
    }
 
Example 44
Project: opencps-v2   File: CertUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @param url
 * @return
 * @throws CertificateException
 * @throws FileNotFoundException
 * @throws URISyntaxException
 */
public static Certificate getCertificateByURL(String url)
	throws CertificateException, FileNotFoundException, URISyntaxException {

	CertificateFactory cf = CertificateFactory
		.getInstance("X.509");

	Certificate cert = cf
		.generateCertificate(new FileInputStream(new File(new URI(url))));

	return cert;
}
 
Example 45
Project: openjdk-jdk10   File: ProbeLargeKeystore.java   Source Code and License 5 votes vote down vote up
private static final Certificate loadCertificate(String certFile)
        throws Exception {
    try (FileInputStream certStream = new FileInputStream(certFile)) {
         CertificateFactory factory =
             CertificateFactory.getInstance("X.509");
        return factory.generateCertificate(certStream);
    }
}
 
Example 46
Project: jdk8u-jdk   File: SSLSocketSNISensitive.java   Source Code and License 5 votes vote down vote up
private static void checkCertificate(Certificate[] certs,
        String hostname) throws Exception {
    if (certs != null && certs.length != 0) {
        X509Certificate x509Cert = (X509Certificate)certs[0];

        String subject = x509Cert.getSubjectX500Principal().getName();

        if (!subject.contains(hostname)) {
            throw new Exception(
                    "Not the expected certificate: " + subject);
        }
    }
}
 
Example 47
Project: jdk8u-jdk   File: BasicChecker.java   Source Code and License 5 votes vote down vote up
/**
 * Performs the signature, timestamp, and subject/issuer name chaining
 * checks on the certificate using its internal state. This method does
 * not remove any critical extensions from the Collection.
 *
 * @param cert the Certificate
 * @param unresolvedCritExts a Collection of the unresolved critical
 * extensions
 * @throws CertPathValidatorException if certificate does not verify
 */
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts)
    throws CertPathValidatorException
{
    X509Certificate currCert = (X509Certificate)cert;

    if (!sigOnly) {
        verifyTimestamp(currCert);
        verifyNameChaining(currCert);
    }
    verifySignature(currCert);

    updateState(currCert);
}
 
Example 48
Project: zabbkit-android   File: SSLManager.java   Source Code and License 5 votes vote down vote up
public void getCertificates(final HttpsURLConnection conn, final AsyncRequestListener listener) {
	new AsyncTask<Void, Void, Void>() {

		@Override
		protected Void doInBackground(Void... params) {

			keyStore = loadTrustStore();
			Certificate[] certs = null;
			try {
				certs = conn.getServerCertificates();
			} catch (SSLPeerUnverifiedException e) {
				// Toast.makeText(mContext, e.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}
			int i = 0;
			X509Certificate[] chain = new X509Certificate[certs.length];
			for (Certificate cert : certs) {
				if (cert instanceof X509Certificate) {
					chain[i] = (X509Certificate) cert;
					i++;
				}
			}
			if (chain != null) {
				try {
					MyX509TrustManager.getInstance().checkServerTrusted(chain, "RSA");
					listener.onCertificateRequest(null);
				} catch (java.security.cert.CertificateException e1) {
					listener.onCertificateRequest(chain);
				}
			}
			return null;
		}
	}.execute();
}
 
Example 49
Project: jdk8u-jdk   File: ScanSignedJar.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        System.out.println("Opening " + JAR_LOCATION + "...");
        JarInputStream inStream =
            new JarInputStream(new URL(JAR_LOCATION).openStream(), true);
        JarEntry entry;
        byte[] buffer = new byte[1024];

        while ((entry = inStream.getNextJarEntry()) != null) {

            // need to read the entry's data to see the certs.
            while(inStream.read(buffer) != -1)
                ;

            String name = entry.getName();
            long size = entry.getSize();
            Certificate[] certificates = entry.getCertificates();
            CodeSigner[] signers = entry.getCodeSigners();

            if (signers == null && certificates == null) {
                System.out.println("[unsigned]\t" + name + "\t(" + size +
                    " bytes)");
                if (name.equals("Count.class")) {
                    throw new Exception("Count.class should be signed");
                }
            } else if (signers != null && certificates != null) {
                System.out.println("[" + signers.length +
                    (signers.length == 1 ? " signer" : " signers") + "]\t" +
                    name + "\t(" + size + " bytes)");
            } else {
                System.out.println("[*ERROR*]\t" + name + "\t(" + size +
                    " bytes)");
                throw new Exception("Cannot determine whether the entry is " +
                    "signed or unsigned (signers[] doesn't match certs[]).");
            }
        }
    }
 
Example 50
Project: easyssl   File: SSLContextCreator.java   Source Code and License 5 votes vote down vote up
private static File createCertChainPEMFile(Certificate[] cchain)throws Exception{
  
	  StringBuilder sb = new StringBuilder();
      for (Certificate c : cchain) {
        sb.append("-----BEGIN CERTIFICATE-----\n");
        sb.append(new String(Base64.getEncoder().encode(c.getEncoded())));
        sb.append("\n");
        sb.append("-----END CERTIFICATE-----\n");
      }
      return tempFile("certchain", "pem", sb.toString());
}
 
Example 51
Project: openjdk-jdk10   File: KeyStoreResolver.java   Source Code and License 5 votes vote down vote up
private Certificate findNextCert() {
    while (this.aliases.hasMoreElements()) {
        String alias = this.aliases.nextElement();
        try {
            Certificate cert = this.keyStore.getCertificate(alias);
            if (cert != null) {
                return cert;
            }
        } catch (KeyStoreException ex) {
            return null;
        }
    }

    return null;
}
 
Example 52
Project: kubernetes-client   File: LoggingApiClient.java   Source Code and License 5 votes vote down vote up
protected KeyManager[] gkm(String cert, String k2) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    if (cert == null && k2 == null)
        return new KeyManager[0];
    String keyStoreType = "JKS";

    KeyStore ks = KeyStore.getInstance(keyStoreType);
    ks.load(null, "".toCharArray());

    List<java.security.cert.Certificate> certs = new ArrayList<java.security.cert.Certificate>();

    certs.add(PEMSupport.getInstance().parseCertificate(cert));

    Object key = PEMSupport.getInstance().parseKey(k2);
    Key k = key instanceof Key ? (Key) key : ((KeyPair)key).getPrivate();
    if (k instanceof RSAPrivateCrtKey && certs.get(0).getPublicKey() instanceof RSAPublicKey) {
        RSAPrivateCrtKey privkey = (RSAPrivateCrtKey)k;
        RSAPublicKey pubkey = (RSAPublicKey) certs.get(0).getPublicKey();
        if (!(privkey.getModulus().equals(pubkey.getModulus()) && privkey.getPublicExponent().equals(pubkey.getPublicExponent())))
            LOG.warn("Certificate does not fit to key.");
    }

    ks.setKeyEntry("inlinePemKeyAndCertificate", k, "".toCharArray(),  certs.toArray(new Certificate[certs.size()]));

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    String keyPassword = "";
    kmf.init(ks, keyPassword.toCharArray());
    return kmf.getKeyManagers();
}
 
Example 53
Project: OpenJSharp   File: PrivateKeyResolver.java   Source Code and License 5 votes vote down vote up
private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?");

    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) {
                XMLX509IssuerSerial certSerial =
                    new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert);

                if (certSerial.equals(x509Serial)) {
                    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 54
Project: cas4.0.x-server-wechat   File: MockX509CRL.java   Source Code and License 5 votes vote down vote up
/**
 * @see java.security.cert.CRL#isRevoked(java.security.cert.Certificate)
 */
@Override
public boolean isRevoked(final Certificate cert) {
    if (cert instanceof X509Certificate) {
        final X509Certificate xcert = (X509Certificate) cert;
        for (X509CRLEntry entry : getRevokedCertificates()) {
            if (entry.getSerialNumber().equals(xcert.getSerialNumber())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 55
Project: opencps-v2   File: BCYSignatureUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @param fullPath
 * @param cert
 * @param imageBase64
 * @return
 */
public static ServerSigner getServerSigner(String fullPath,
		Certificate cert, String imageBase64, boolean showSignatureInfo) {
	ServerSigner signer = new ServerSigner(fullPath, cert);
	signer.setSignatureGraphic(imageBase64);
	if(showSignatureInfo) {
		signer.setSignatureAppearance(PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION);
	} else {
		signer.setSignatureAppearance(PdfSignatureAppearance.RenderingMode.GRAPHIC);
	}
	return signer;
}
 
Example 56
Project: CustomWorldGen   File: FMLPreInitializationEvent.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieve the FML signing certificates, if any. Validate these against the
 * published FML certificates in your mod, if you wish.
 *
 * Deprecated because mods should <b>NOT</b> trust this code. Rather
 * they should copy this, or something like this, into their own mods.
 *
 * @return Certificates used to sign FML and Forge
 */
@Deprecated
public Certificate[] getFMLSigningCertificates()
{
    CodeSource codeSource = getClass().getClassLoader().getParent().getClass().getProtectionDomain().getCodeSource();
    Certificate[] certs = codeSource.getCertificates();
    if (certs == null)
    {
        return new Certificate[0];
    }
    else
    {
        return certs;
    }
}
 
Example 57
Project: OpenJSharp   File: LDAPCertStore.java   Source Code and License 5 votes vote down vote up
private Collection<X509Certificate> getCertificates(LDAPRequest request,
    String id, X509CertSelector sel) throws CertStoreException {

    /* fetch encoded certs from storage */
    byte[][] encodedCert;
    try {
        encodedCert = request.getValues(id);
    } catch (NamingException namingEx) {
        throw new CertStoreException(namingEx);
    }

    int n = encodedCert.length;
    if (n == 0) {
        return Collections.emptySet();
    }

    List<X509Certificate> certs = new ArrayList<>(n);
    /* decode certs and check if they satisfy selector */
    for (int i = 0; i < n; i++) {
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert[i]);
        try {
            Certificate cert = cf.generateCertificate(bais);
            if (sel.match(cert)) {
              certs.add((X509Certificate)cert);
            }
        } catch (CertificateException e) {
            if (debug != null) {
                debug.println("LDAPCertStore.getCertificates() encountered "
                    + "exception while parsing cert, skipping the bad data: ");
                HexDumpEncoder encoder = new HexDumpEncoder();
                debug.println(
                    "[ " + encoder.encodeBuffer(encodedCert[i]) + " ]");
            }
        }
    }

    return certs;
}
 
Example 58
Project: boohee_v5.6   File: DelegatingHttpsURLConnection.java   Source Code and License 5 votes vote down vote up
public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
    Handshake handshake = handshake();
    if (handshake == null) {
        return null;
    }
    List<Certificate> result = handshake.peerCertificates();
    if (result.isEmpty()) {
        return null;
    }
    return (Certificate[]) result.toArray(new Certificate[result.size()]);
}
 
Example 59
Project: openjdk-jdk10   File: Main.java   Source Code and License 5 votes vote down vote up
/**
 * Writes an X.509 certificate in base64 or binary encoding to an output
 * stream.
 */
private void dumpCert(Certificate cert, PrintStream out)
    throws IOException, CertificateException
{
    if (rfc) {
        out.println(X509Factory.BEGIN_CERT);
        out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(cert.getEncoded()));
        out.println(X509Factory.END_CERT);
    } else {
        out.write(cert.getEncoded()); // binary
    }
}
 
Example 60
Project: openjdk-jdk10   File: MyKeyManager.java   Source Code and License 5 votes vote down vote up
MyKeyManager(KeyStore ks, char[] password)
    throws KeyStoreException, NoSuchAlgorithmException,
    UnrecoverableKeyException
{
    if (ks == null) {
        return;
    }

    Enumeration aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String)aliases.nextElement();
        if (ks.isKeyEntry(alias)) {
            Certificate[] certs;
            certs = ks.getCertificateChain(alias);
            if (certs != null && certs.length > 0 &&
                certs[0] instanceof X509Certificate) {
                if (!(certs instanceof X509Certificate[])) {
                    Certificate[] tmp = new X509Certificate[certs.length];
                    System.arraycopy(certs, 0, tmp, 0, certs.length);
                    certs = tmp;
                }
                Key key = ks.getKey(alias, password);
                certChainMap.put(alias, certs);
                keyMap.put(alias, key);
            }
        }
    }
}