Checks whether given X.509 certificate is self-signed. - Java Security

Java examples for Security:Certificate

Description

Checks whether given X.509 certificate is self-signed.

Demo Code


//package com.java2s;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SignatureException;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

public class Main {
    /**/*from  w  w  w.j  a v  a  2s  .  c om*/
     * Checks whether given X.509 certificate is self-signed.
     */
    public static boolean isSelfSigned(X509Certificate cert)
            throws CertificateException, NoSuchAlgorithmException,
            NoSuchProviderException {
        try {
            // Try to verify certificate signature with its own public key
            PublicKey key = cert.getPublicKey();
            cert.verify(key);
            return true;
        } catch (SignatureException sigEx) {
            // Invalid signature --> not self-signed
            return false;
        } catch (InvalidKeyException keyEx) {
            // Invalid key --> not self-signed
            return false;
        }
    }
}

Related Tutorials