java - 根据 X509Certificate CA 的名称约束扩展验证名称
问题描述
我有一个 CA 证书被解析为X509Certificate
对象,它可能有也可能没有名称约束扩展。
在使用此 CA 证书签署新证书之前,我想手动验证 CA 是否允许给定的主机名或 IP 地址。我怎样才能做到这一点?
解决方案
尽管我可以看到 JDK 对此提供了不错的 API,但它们都是内部的。所以我最终使用了 Bouncy Castle。
public boolean validateAgainstNamingConstraints(X509Certificate certificate, GeneralName name) {
NameConstraints nameConstraints = null;
try {
nameConstraints = NameConstraints.getInstance(
JcaX509ExtensionUtils.parseExtensionValue(certificate.getExtensionValue(Extension.nameConstraints.getId())));
} catch (IOException e) {
log.warn("Failed to parse name constraint. Skipping validation. {}", e.getMessage());
return true;
}
if (nameConstraints == null) {
return true;
}
var nameConstraintValidator = new PKIXNameConstraintValidator();
if (nameConstraints.getPermittedSubtrees() != null) {
nameConstraintValidator.intersectPermittedSubtree(nameConstraints.getPermittedSubtrees());
}
if (nameConstraints.getExcludedSubtrees() != null) {
for (int i = 0; i < nameConstraints.getExcludedSubtrees().length; i++) {
nameConstraintValidator.addExcludedSubtree(nameConstraints.getExcludedSubtrees()[i]);
}
}
try {
nameConstraintValidator.checkPermitted(name);
nameConstraintValidator.checkExcluded(name);
return true;
} catch (NameConstraintValidatorException e) {
return false;
}
}
如何使用:
validateAgainstNamingConstraints(certificate, new GeneralName(GeneralName.dNSName, "test.google.com"))
validateAgainstNamingConstraints(certificate, new GeneralName(GeneralName.iPAddress, "192.168.111.1"))
推荐阅读
- java - 在 ExecutorService.submit 之后未调用 Java Runnable 实例上的 Run 方法
- hadoop - 如何根据连接列的条件连接配置单元表
- javascript - 2 setInterval() 实例正在运行,如何运行一个?
- git - GitKraken 与 git-crypt 的互操作性
- pandas - 如何在具有唯一键和序列值的列中唯一求和
- postgresql - 使用 CanCanCan 进行不区分大小写的搜索?
- django - Paypal - 将订单保存到数据库的最佳时间是什么时候
- docker - 码头集装箱内关闭的端口
- javascript - 当您到达滚动时的原始位置时,将位置从固定到最底部切换到 div 的初始位置
- c++ - 无法使用 QMediaPlayer 加载音乐文件