下面列出了java.security.cert.PKIXRevocationChecker.Option#java.security.cert.CertPathValidatorException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void check(Certificate cert,
Collection<String> unresolvedCritExts)
throws CertPathValidatorException {
X509Certificate currCert = (X509Certificate)cert;
if (UntrustedCertificates.isUntrusted(currCert)) {
if (debug != null) {
debug.println("UntrustedChecker: untrusted certificate " +
currCert.getSubjectX500Principal());
}
throw new CertPathValidatorException(
"Untrusted certificate: " + currCert.getSubjectX500Principal());
}
}
/**
* Internal method to create a new key with inherited key parameters.
*
* @param keyValueKey key from which to obtain key value
* @param keyParamsKey key from which to obtain key parameters
* @return new public key having value and parameters
* @throws CertPathValidatorException if keys are not appropriate types
* for this operation
*/
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
PublicKey keyParamsKey) throws CertPathValidatorException
{
if (!(keyValueKey instanceof DSAPublicKey) ||
!(keyParamsKey instanceof DSAPublicKey))
throw new CertPathValidatorException("Input key is not " +
"appropriate type for " +
"inheriting parameters");
DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
if (params == null)
throw new CertPathValidatorException("Key parameters missing");
try {
BigInteger y = ((DSAPublicKey)keyValueKey).getY();
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
params.getP(),
params.getQ(),
params.getG());
return kf.generatePublic(ks);
} catch (GeneralSecurityException e) {
throw new CertPathValidatorException("Unable to generate key with" +
" inherited parameters: " +
e.getMessage(), e);
}
}
/**
* Performs the basic constraints and name constraints
* checks on the certificate using its internal state.
*
* @param cert the <code>Certificate</code> to be checked
* @param unresCritExts a <code>Collection</code> of OID strings
* representing the current set of unresolved critical extensions
* @throws CertPathValidatorException if the specified certificate
* does not pass the check
*/
@Override
public void check(Certificate cert, Collection<String> unresCritExts)
throws CertPathValidatorException
{
X509Certificate currCert = (X509Certificate)cert;
i++;
// MUST run NC check second, since it depends on BC check to
// update remainingCerts
checkBasicConstraints(currCert);
verifyNameConstraints(currCert);
if (unresCritExts != null && !unresCritExts.isEmpty()) {
unresCritExts.remove(BasicConstraints_Id.toString());
unresCritExts.remove(NameConstraints_Id.toString());
}
}
public static RevocationStatus check(X509Certificate cert,
URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,
X509Certificate responderCert, Date date,
List<Extension> extensions, String variant)
throws IOException, CertPathValidatorException
{
CertId certId;
try {
X509CertImpl certImpl = X509CertImpl.toImpl(cert);
certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
} catch (CertificateException | IOException e) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", e);
}
OCSPResponse ocspResponse = check(Collections.singletonList(certId),
responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),
responderCert, date, extensions, variant);
return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
@Override
public void check(Certificate cert,
Collection<String> unresolvedCritExts)
throws CertPathValidatorException {
X509Certificate currCert = (X509Certificate)cert;
if (UntrustedCertificates.isUntrusted(currCert)) {
if (debug != null) {
debug.println("UntrustedChecker: untrusted certificate " +
currCert.getSubjectX500Principal());
}
throw new CertPathValidatorException(
"Untrusted certificate: " + currCert.getSubjectX500Principal());
}
}
/**
* Internal method to manage state information at each iteration
*/
private void updateState(X509Certificate currCert)
throws CertPathValidatorException
{
PublicKey cKey = currCert.getPublicKey();
if (debug != null) {
debug.println("BasicChecker.updateState issuer: " +
currCert.getIssuerX500Principal().toString() + "; subject: " +
currCert.getSubjectX500Principal() + "; serial#: " +
currCert.getSerialNumber().toString());
}
if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
// cKey needs to inherit DSA parameters from prev key
cKey = makeInheritedParamsKey(cKey, prevPubKey);
if (debug != null) debug.println("BasicChecker.updateState Made " +
"key with inherited params");
}
prevPubKey = cKey;
prevSubject = currCert.getSubjectX500Principal();
}
public static RevocationStatus check(X509Certificate cert,
URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,
X509Certificate responderCert, Date date,
List<Extension> extensions, String variant)
throws IOException, CertPathValidatorException
{
CertId certId;
try {
X509CertImpl certImpl = X509CertImpl.toImpl(cert);
certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
} catch (CertificateException | IOException e) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", e);
}
OCSPResponse ocspResponse = check(Collections.singletonList(certId),
responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),
responderCert, date, extensions, variant);
return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
/**
* Internal method to create a new key with inherited key parameters.
*
* @param keyValueKey key from which to obtain key value
* @param keyParamsKey key from which to obtain key parameters
* @return new public key having value and parameters
* @throws CertPathValidatorException if keys are not appropriate types
* for this operation
*/
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
PublicKey keyParamsKey) throws CertPathValidatorException
{
if (!(keyValueKey instanceof DSAPublicKey) ||
!(keyParamsKey instanceof DSAPublicKey))
throw new CertPathValidatorException("Input key is not " +
"appropriate type for " +
"inheriting parameters");
DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
if (params == null)
throw new CertPathValidatorException("Key parameters missing");
try {
BigInteger y = ((DSAPublicKey)keyValueKey).getY();
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
params.getP(),
params.getQ(),
params.getG());
return kf.generatePublic(ks);
} catch (GeneralSecurityException e) {
throw new CertPathValidatorException("Unable to generate key with" +
" inherited parameters: " +
e.getMessage(), e);
}
}
/**
* Performs the basic constraints and name constraints
* checks on the certificate using its internal state.
*
* @param cert the <code>Certificate</code> to be checked
* @param unresCritExts a <code>Collection</code> of OID strings
* representing the current set of unresolved critical extensions
* @throws CertPathValidatorException if the specified certificate
* does not pass the check
*/
@Override
public void check(Certificate cert, Collection<String> unresCritExts)
throws CertPathValidatorException
{
X509Certificate currCert = (X509Certificate)cert;
i++;
// MUST run NC check second, since it depends on BC check to
// update remainingCerts
checkBasicConstraints(currCert);
verifyNameConstraints(currCert);
if (unresCritExts != null && !unresCritExts.isEmpty()) {
unresCritExts.remove(BasicConstraints_Id.toString());
unresCritExts.remove(NameConstraints_Id.toString());
}
}
/**
* Internal method to manage state information at each iteration
*/
private void updateState(X509Certificate currCert)
throws CertPathValidatorException
{
PublicKey cKey = currCert.getPublicKey();
if (debug != null) {
debug.println("BasicChecker.updateState issuer: " +
currCert.getIssuerX500Principal().toString() + "; subject: " +
currCert.getSubjectX500Principal() + "; serial#: " +
currCert.getSerialNumber().toString());
}
if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
// cKey needs to inherit DSA parameters from prev key
cKey = makeInheritedParamsKey(cKey, prevPubKey);
if (debug != null) debug.println("BasicChecker.updateState Made " +
"key with inherited params");
}
prevPubKey = cKey;
prevSubject = currCert.getSubjectX500Principal();
}
/**
* When a failure happens during certificate checking from an
* {@link X509TrustManager}, determine what TLS alert description
* to use.
*
* @param cexc The exception thrown by the {@link X509TrustManager}
*
* @return A byte value corresponding to a TLS alert description number.
*/
private static Alert getCertificateAlert(
ClientHandshakeContext chc, CertificateException cexc) {
// The specific reason for the failure will determine how to
// set the alert description value
Alert alert = Alert.CERTIFICATE_UNKNOWN;
Throwable baseCause = cexc.getCause();
if (baseCause instanceof CertPathValidatorException) {
CertPathValidatorException cpve =
(CertPathValidatorException)baseCause;
Reason reason = cpve.getReason();
if (reason == BasicReason.REVOKED) {
alert = chc.staplingActive ?
Alert.BAD_CERT_STATUS_RESPONSE :
Alert.CERTIFICATE_REVOKED;
} else if (
reason == BasicReason.UNDETERMINED_REVOCATION_STATUS) {
alert = chc.staplingActive ?
Alert.BAD_CERT_STATUS_RESPONSE :
Alert.CERTIFICATE_UNKNOWN;
}
}
return alert;
}
/**
* Initialize the state.
*
* @param certPathCheckers the list of user-defined PKIXCertPathCheckers
*/
public void initState(List<PKIXCertPathChecker> certPathCheckers)
throws CertPathValidatorException
{
subjectNamesTraversed = new HashSet<GeneralNameInterface>();
traversedCACerts = 0;
/*
* Populate forwardCheckers with every user-defined checker
* that supports forward checking and initialize the forwardCheckers
*/
forwardCheckers = new ArrayList<PKIXCertPathChecker>();
for (PKIXCertPathChecker checker : certPathCheckers) {
if (checker.isForwardCheckingSupported()) {
checker.init(true);
forwardCheckers.add(checker);
}
}
init = true;
}
/**
* Internal method to manage state information at each iteration
*/
private void updateState(X509Certificate currCert)
throws CertPathValidatorException
{
PublicKey cKey = currCert.getPublicKey();
if (debug != null) {
debug.println("BasicChecker.updateState issuer: " +
currCert.getIssuerX500Principal().toString() + "; subject: " +
currCert.getSubjectX500Principal() + "; serial#: " +
currCert.getSerialNumber().toString());
}
if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
// cKey needs to inherit DSA parameters from prev key
cKey = makeInheritedParamsKey(cKey, prevPubKey);
if (debug != null) debug.println("BasicChecker.updateState Made " +
"key with inherited params");
}
prevPubKey = cKey;
prevSubject = currCert.getSubjectX500Principal();
}
protected static void processAttrCert4(X509Certificate acIssuerCert,
Set trustedACIssuers) throws CertPathValidatorException
{
Set set = trustedACIssuers;
boolean trusted = false;
for (Iterator it = set.iterator(); it.hasNext();)
{
TrustAnchor anchor = (TrustAnchor) it.next();
if (acIssuerCert.getSubjectX500Principal().getName("RFC2253")
.equals(anchor.getCAName())
|| acIssuerCert.equals(anchor.getTrustedCert()))
{
trusted = true;
}
}
if (!trusted)
{
throw new CertPathValidatorException(
"Attribute certificate issuer is not directly trusted.");
}
}
/**
* Initialize the state.
*
* @param certPathCheckers the list of user-defined PKIXCertPathCheckers
*/
public void initState(List<PKIXCertPathChecker> certPathCheckers)
throws CertPathValidatorException
{
subjectNamesTraversed = new HashSet<GeneralNameInterface>();
traversedCACerts = 0;
/*
* Populate forwardCheckers with every user-defined checker
* that supports forward checking and initialize the forwardCheckers
*/
forwardCheckers = new ArrayList<PKIXCertPathChecker>();
for (PKIXCertPathChecker checker : certPathCheckers) {
if (checker.isForwardCheckingSupported()) {
checker.init(true);
forwardCheckers.add(checker);
}
}
init = true;
}
/**
* Checks a validation failure to see if it failed for the reason we think
* it should. This comes in as an SSLException of some sort, but it
* encapsulates a ValidatorException which in turn encapsulates the
* CertPathValidatorException we are interested in.
*
* @param e the exception thrown at the top level
* @param reason the underlying CertPathValidatorException BasicReason
* we are expecting it to have.
*
* @return true if the reason matches up, false otherwise.
*/
static boolean checkClientValidationFailure(Exception e,
BasicReason reason) {
boolean result = false;
if (e instanceof SSLException) {
Throwable valExc = e.getCause();
if (valExc instanceof sun.security.validator.ValidatorException) {
Throwable cause = valExc.getCause();
if (cause instanceof CertPathValidatorException) {
CertPathValidatorException cpve =
(CertPathValidatorException)cause;
if (cpve.getReason() == reason) {
result = true;
}
}
}
}
return result;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
doTheChecks(chain, authType);
} catch (CertPathValidatorException e) {
try {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
certControll.addChain(chain);
}
});
} catch (HeadlessException e1) {
Log.error("Couldn't add certificate from presented chain");
}
throw new CertificateException(e);
}
}
@Override
public void permits(ConstraintsParameters cp)
throws CertPathValidatorException {
Key key = null;
if (cp.getPublicKey() != null) {
key = cp.getPublicKey();
} else if (cp.getCertificate() != null) {
key = cp.getCertificate().getPublicKey();
}
if (key != null && !permitsImpl(key)) {
if (nextConstraint != null) {
nextConstraint.permits(cp);
return;
}
throw new CertPathValidatorException(
"Algorithm constraints check failed on keysize limits. " +
algorithm + " " + KeyUtil.getKeySize(key) + "bit key" +
extendedMsg(cp),
null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
}
/**
* Initialize the state.
*
* @param certPathCheckers the list of user-defined PKIXCertPathCheckers
*/
public void initState(List<PKIXCertPathChecker> certPathCheckers)
throws CertPathValidatorException
{
subjectNamesTraversed = new HashSet<GeneralNameInterface>();
traversedCACerts = 0;
/*
* Populate forwardCheckers with every user-defined checker
* that supports forward checking and initialize the forwardCheckers
*/
forwardCheckers = new ArrayList<PKIXCertPathChecker>();
for (PKIXCertPathChecker checker : certPathCheckers) {
if (checker.isForwardCheckingSupported()) {
checker.init(true);
forwardCheckers.add(checker);
}
}
init = true;
}
/**
* Internal method to check that cert has a valid DN to be next in a chain
*/
private void verifyNameChaining(X509Certificate cert)
throws CertPathValidatorException
{
if (prevSubject != null) {
String msg = "subject/issuer name chaining";
if (debug != null)
debug.println("---checking " + msg + "...");
X500Principal currIssuer = cert.getIssuerX500Principal();
// reject null or empty issuer DNs
if (X500Name.asX500Name(currIssuer).isEmpty()) {
throw new CertPathValidatorException
(msg + " check failed: " +
"empty/null issuer DN in certificate is invalid", null,
null, -1, PKIXReason.NAME_CHAINING);
}
if (!(currIssuer.equals(prevSubject))) {
throw new CertPathValidatorException
(msg + " check failed", null, null, -1,
PKIXReason.NAME_CHAINING);
}
if (debug != null)
debug.println(msg + " verified.");
}
}
public static void main(String[] args) throws Exception {
Throwable[] causes = {
new Throwable(),
new Throwable("message"),
new Throwable("message", new Throwable()) };
for (Throwable cause: causes) {
CertPathValidatorException cpve =
new CertPathValidatorException(cause);
// from CertPathValidatorException(Throwable cause) spec:
// The detail message is set to (cause==null ? null : cause.toString() )
// (which typically contains the class and detail message of cause).
String expMsg = (cause == null ? null : cause.toString());
String actualMsg = cpve.getMessage();
boolean msgsEqual =
(expMsg == null ? actualMsg == null : expMsg.equals(actualMsg));
if (!msgsEqual) {
System.out.println("expected message:" + expMsg);
System.out.println("getMessage():" + actualMsg);
failed = true;
}
}
if (failed) {
throw new Exception("Some tests FAILED");
}
}
public static void main(String[] args) throws Exception {
String[] certs = { "sun.cer", "sun2labs1.cer" };
try {
createPath(certs);
validate(path, params);
throw new Exception
("CertPath should not have been validated succesfully");
} catch (CertPathValidatorException cpve) {
System.out.println("Test failed as expected: " + cpve);
}
}
/**
* Internal method to check the name constraints against a cert
*/
private void verifyNameConstraints(X509Certificate currCert)
throws CertPathValidatorException
{
String msg = "name constraints";
if (debug != null) {
debug.println("---checking " + msg + "...");
}
// check name constraints only if there is a previous name constraint
// and either the currCert is the final cert or the currCert is not
// self-issued
if (prevNC != null && ((i == certPathLength) ||
!X509CertImpl.isSelfIssued(currCert))) {
if (debug != null) {
debug.println("prevNC = " + prevNC +
", currDN = " + currCert.getSubjectX500Principal());
}
try {
if (!prevNC.verify(currCert)) {
throw new CertPathValidatorException(msg + " check failed",
null, null, -1, PKIXReason.INVALID_NAME);
}
} catch (IOException ioe) {
throw new CertPathValidatorException(ioe);
}
}
// merge name constraints regardless of whether cert is self-issued
prevNC = mergeNameConstraints(currCert, prevNC);
if (debug != null)
debug.println(msg + " verified.");
}
/**
* When a failure happens during certificate checking from an
* {@link X509TrustManager}, determine what TLS alert description
* to use.
*
* @param cexc The exception thrown by the {@link X509TrustManager}
*
* @return A byte value corresponding to a TLS alert description number.
*/
private static Alert getCertificateAlert(
ClientHandshakeContext chc, CertificateException cexc) {
// The specific reason for the failure will determine how to
// set the alert description value
Alert alert = Alert.CERTIFICATE_UNKNOWN;
Throwable baseCause = cexc.getCause();
if (baseCause instanceof CertPathValidatorException) {
CertPathValidatorException cpve =
(CertPathValidatorException)baseCause;
Reason reason = cpve.getReason();
if (reason == BasicReason.REVOKED) {
alert = chc.staplingActive ?
Alert.BAD_CERT_STATUS_RESPONSE :
Alert.CERTIFICATE_REVOKED;
} else if (
reason == BasicReason.UNDETERMINED_REVOCATION_STATUS) {
alert = chc.staplingActive ?
Alert.BAD_CERT_STATUS_RESPONSE :
Alert.CERTIFICATE_UNKNOWN;
} else if (reason == BasicReason.ALGORITHM_CONSTRAINED) {
alert = Alert.UNSUPPORTED_CERTIFICATE;
} else if (reason == BasicReason.EXPIRED) {
alert = Alert.CERTIFICATE_EXPIRED;
} else if (reason == BasicReason.INVALID_SIGNATURE ||
reason == BasicReason.NOT_YET_VALID) {
alert = Alert.BAD_CERTIFICATE;
}
}
return alert;
}
/**
* 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);
}
protected static void prepareNextCertO(
CertPath certPath,
int index,
Set criticalExtensions,
List pathCheckers)
throws CertPathValidatorException
{
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate)certs.get(index);
//
// (o)
//
Iterator tmpIter;
tmpIter = pathCheckers.iterator();
while (tmpIter.hasNext())
{
try
{
((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions);
}
catch (CertPathValidatorException e)
{
throw new CertPathValidatorException(e.getMessage(), e.getCause(), certPath, index);
}
}
if (!criticalExtensions.isEmpty())
{
throw new ExtCertPathValidatorException("Certificate has unsupported critical extension: " + criticalExtensions, null, certPath,
index);
}
}
public static void main(String[] args) throws Exception {
String[] certs = { "sun.cer", "sun2labs2.cer", "labs2isrg2.cer" };
try {
createPath(certs);
validate(path, params);
throw new Exception
("CertPath should not have been validated succesfully");
} catch (CertPathValidatorException cve) {
System.out.println("Test failed as expected: " + cve);
}
}
public static void main(String[] args) throws Exception {
String[] certs = { "sun.cer", "sun2labs2.cer", "labs2isrg2.cer" };
try {
createPath(certs);
validate(path, params);
throw new Exception
("CertPath should not have been validated succesfully");
} catch (CertPathValidatorException cve) {
System.out.println("Test failed as expected: " + cve);
}
}
/**
* Internal method to check that cert has a valid DN to be next in a chain
*/
private void verifyNameChaining(X509Certificate cert)
throws CertPathValidatorException
{
if (prevSubject != null) {
String msg = "subject/issuer name chaining";
if (debug != null)
debug.println("---checking " + msg + "...");
X500Principal currIssuer = cert.getIssuerX500Principal();
// reject null or empty issuer DNs
if (X500Name.asX500Name(currIssuer).isEmpty()) {
throw new CertPathValidatorException
(msg + " check failed: " +
"empty/null issuer DN in certificate is invalid", null,
null, -1, PKIXReason.NAME_CHAINING);
}
if (!(currIssuer.equals(prevSubject))) {
throw new CertPathValidatorException
(msg + " check failed", null, null, -1,
PKIXReason.NAME_CHAINING);
}
if (debug != null)
debug.println(msg + " verified.");
}
}
public static void main(String[] args) throws Exception {
String[] certs = { "sun.cer", "sun2labs2.cer", "labs2isrg2.cer" };
try {
createPath(certs);
validate(path, params);
throw new Exception
("CertPath should not have been validated succesfully");
} catch (CertPathValidatorException cve) {
System.out.println("Test failed as expected: " + cve);
}
}