get Certificate Issuer - Java Security

Java examples for Security:Certificate

Description

get Certificate Issuer

Demo Code


import org.apache.log4j.Logger;
import javax.security.auth.x500.X500Principal;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class Main{
    private static transient final Logger log = Logger
            .getLogger(CertificateChainUtil.class);
    public static final boolean ALLOW_LOG_SELF_SIGN_TESTS = false;
    public static X509Certificate getIssuer(X509Certificate subject,
            Collection<X509Certificate> certs) {
        for (X509Certificate cert : certs) {
            if (cert.getSubjectX500Principal().equals(
                    subject.getIssuerX500Principal())) {
                if (isSignedBy(subject, cert.getPublicKey())) {
                    return cert;
                }/*from   w w  w.ja  v a  2 s. co m*/
            }
        }

        return null;
    }
    @SuppressWarnings("unused")
    public static boolean isSignedBy(X509Certificate subject,
            PublicKey signer) {
        try {
            subject.verify(signer);

            // if verify does not throw an exception then it's a self-signed certificate
            return true;
        } catch (Exception e) {
            if (ALLOW_LOG_SELF_SIGN_TESTS && log.isTraceEnabled()) {
                final String dn = subject.getIssuerX500Principal()
                        .getName();

                log.trace("{isSignedBy} " + dn + " not signed by " + signer
                        + ":" + e.getMessage(), e);
            }

            return false;
        }

    }
}

Related Tutorials