Java examples for Security:Certificate
Verifies that a certificate chain is valid
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{ public static void main(String[] argv) throws Exception{ List chain = java.util.Arrays.asList("asdf","java2s.com"); verifyChain(chain);//from w ww. ja v a 2 s . c o m } /** * Verifies that a certificate chain is valid * * @param chain * a certificate chain with the root certificate first * * @throws IllegalArgumentException * if the chain is invalid, null or empty */ public static void verifyChain(List<X509Certificate> chain) { if (chain == null || chain.isEmpty()) throw new IllegalArgumentException( "Must provide a chain that is non-null and non-empty"); for (int i = 0; i < chain.size(); i++) { final X509Certificate certificate = chain.get(i); final int issuerIndex = (i != 0) ? i - 1 : 0; // The index of the issuer is the previous cert (& the root must, of course, sign itself) final X509Certificate issuer = chain.get(issuerIndex); // Verify the certificate was indeed issued by the previous certificate in the chain try { certificate.verify(issuer.getPublicKey()); } catch (GeneralSecurityException e) { final String msg = "Failure verifying " + certificate + " against claimed issuer " + issuer; throw new IllegalArgumentException(msg + ": " + e.getMessage(), e); } } } }