use of org.bouncycastle.asn1.cms.Time in project cas by apereo.
the class X509SubjectAlternativeNameUPNPrincipalResolver method getUPNStringFromSequence.
/**
* Get UPN String.
*
* @param seq ASN1Sequence abstraction representing subject alternative name.
* First element is the object identifier, second is the object itself.
* @return UPN string or null
*/
private static String getUPNStringFromSequence(final ASN1Sequence seq) {
if (seq != null) {
// First in sequence is the object identifier, that we must check
final ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
if (id != null && UPN_OBJECTID.equals(id.getId())) {
final ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);
ASN1Primitive prim = obj.getObject();
// Due to bug in java cert.getSubjectAltName, it can be tagged an extra time
if (prim instanceof ASN1TaggedObject) {
prim = ASN1TaggedObject.getInstance(prim).getObject();
}
if (prim instanceof ASN1OctetString) {
return new String(((ASN1OctetString) prim).getOctets(), StandardCharsets.UTF_8);
} else if (prim instanceof ASN1String) {
return ((ASN1String) prim).getString();
} else {
return null;
}
}
}
return null;
}
use of org.bouncycastle.asn1.cms.Time in project Openfire by igniterealtime.
the class CertificateManager method createX509V3Certificate.
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerCommonName Issuer CN string
* @param subjectCommonName Subject CN string
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName, String subjectCommonName, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
// subjectDN
X500NameBuilder subjectBuilder = new X500NameBuilder();
subjectBuilder.addRDN(BCStyle.CN, subjectCommonName);
// issuerDN
X500NameBuilder issuerBuilder = new X500NameBuilder();
issuerBuilder.addRDN(BCStyle.CN, issuerCommonName);
return createX509V3Certificate(kp, days, issuerBuilder, subjectBuilder, domain, signAlgoritm);
}
use of org.bouncycastle.asn1.cms.Time in project helios by spotify.
the class X509CertificateFactory method generate.
private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity, final String username) {
final UUID uuid = new UUID();
final Calendar calendar = Calendar.getInstance();
final X500Name issuerdn = new X500Name("C=US,O=Spotify,CN=helios-client");
final X500Name subjectdn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
final Date notBefore = calendar.getTime();
calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
final Date notAfter = calendar.getTime();
// Reuse the UUID time as a SN
final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerdn, serialNumber, notBefore, notAfter, subjectdn, subjectPublicKeyInfo);
final DigestCalculator digestCalculator = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);
final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex, identity.getComment());
builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));
final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
log.debug("generated certificate:\n{}", asPemString(certificate));
return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
use of org.bouncycastle.asn1.cms.Time in project XobotOS by xamarin.
the class PKIXCertPathValidatorSpi method engineValidate.
// END android-added
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
if (!(params instanceof PKIXParameters)) {
throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
}
ExtendedPKIXParameters paramsPKIX;
if (params instanceof ExtendedPKIXParameters) {
paramsPKIX = (ExtendedPKIXParameters) params;
} else {
paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters) params);
}
if (paramsPKIX.getTrustAnchors() == null) {
throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
}
//
// 6.1.1 - inputs
//
//
// (a)
//
List certs = certPath.getCertificates();
int n = certs.size();
if (certs.isEmpty()) {
throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0);
}
// BEGIN android-added
{
X509Certificate cert = (X509Certificate) certs.get(0);
if (cert != null) {
BigInteger serial = cert.getSerialNumber();
if (serial != null && SERIAL_BLACKLIST.contains(serial)) {
// emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
String message = "Certificate revocation of serial 0x" + serial.toString(16);
System.out.println(message);
AnnotatedException e = new AnnotatedException(message);
throw new CertPathValidatorException(e.getMessage(), e, certPath, 0);
}
}
}
// END android-added
//
// (b)
//
// Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX);
//
// (c)
//
Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
//
// (d)
//
TrustAnchor trust;
try {
trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
} catch (AnnotatedException e) {
throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1);
}
if (trust == null) {
throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
}
//
// (e), (f), (g) are part of the paramsPKIX object.
//
Iterator certIter;
int index = 0;
int i;
// Certificate for each interation of the validation loop
// Signature information for each iteration of the validation loop
//
// 6.1.2 - setup
//
//
// (a)
//
List[] policyNodes = new ArrayList[n + 1];
for (int j = 0; j < policyNodes.length; j++) {
policyNodes[j] = new ArrayList();
}
Set policySet = new HashSet();
policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
policyNodes[0].add(validPolicyTree);
//
// (b) and (c)
//
PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
// (d)
//
int explicitPolicy;
Set acceptablePolicies = new HashSet();
if (paramsPKIX.isExplicitPolicyRequired()) {
explicitPolicy = 0;
} else {
explicitPolicy = n + 1;
}
//
// (e)
//
int inhibitAnyPolicy;
if (paramsPKIX.isAnyPolicyInhibited()) {
inhibitAnyPolicy = 0;
} else {
inhibitAnyPolicy = n + 1;
}
//
// (f)
//
int policyMapping;
if (paramsPKIX.isPolicyMappingInhibited()) {
policyMapping = 0;
} else {
policyMapping = n + 1;
}
//
// (g), (h), (i), (j)
//
PublicKey workingPublicKey;
X500Principal workingIssuerName;
X509Certificate sign = trust.getTrustedCert();
try {
if (sign != null) {
workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
workingPublicKey = sign.getPublicKey();
} else {
workingIssuerName = new X500Principal(trust.getCAName());
workingPublicKey = trust.getCAPublicKey();
}
} catch (IllegalArgumentException ex) {
throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
}
AlgorithmIdentifier workingAlgId = null;
try {
workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
} catch (CertPathValidatorException e) {
throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
}
DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId();
DEREncodable workingPublicKeyParameters = workingAlgId.getParameters();
//
// (k)
//
int maxPathLength = n;
if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
}
//
// initialize CertPathChecker's
//
List pathCheckers = paramsPKIX.getCertPathCheckers();
certIter = pathCheckers.iterator();
while (certIter.hasNext()) {
((PKIXCertPathChecker) certIter.next()).init(false);
}
X509Certificate cert = null;
for (index = certs.size() - 1; index >= 0; index--) {
// BEGIN android-added
if (isPublicKeyBlackListed(workingPublicKey)) {
// emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
String message = "Certificate revocation of public key " + workingPublicKey;
System.out.println(message);
AnnotatedException e = new AnnotatedException(message);
throw new CertPathValidatorException(e.getMessage(), e, certPath, index);
}
// END android-added
// try
// {
//
// i as defined in the algorithm description
//
i = n - index;
//
// set certificate to be checked in this round
// sign and workingPublicKey and workingIssuerName are set
// at the end of the for loop and initialized the
// first time from the TrustAnchor
//
cert = (X509Certificate) certs.get(index);
boolean verificationAlreadyPerformed = (index == certs.size() - 1);
//
// 6.1.3
//
RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator);
validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
if (i != n) {
if (cert != null && cert.getVersion() == 1) {
throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
}
RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
// (h)
explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
//
// (i)
//
explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
// (j)
inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
// (k)
RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
// (l)
maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
// (m)
maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
// (n)
RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
Set criticalExtensions = cert.getCriticalExtensionOIDs();
if (criticalExtensions != null) {
criticalExtensions = new HashSet(criticalExtensions);
// these extensions are handled by the algorithm
criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
} else {
criticalExtensions = new HashSet();
}
// (o)
RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
// set signing certificate for next round
sign = cert;
// (c)
workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
// (d)
try {
workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
}
workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
// (f)
workingPublicKeyAlgorithm = workingAlgId.getObjectId();
// (e)
workingPublicKeyParameters = workingAlgId.getParameters();
}
}
//
// 6.1.5 Wrap-up procedure
//
explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
//
// (c) (d) and (e) are already done
//
//
// (f)
//
Set criticalExtensions = cert.getCriticalExtensionOIDs();
if (criticalExtensions != null) {
criticalExtensions = new HashSet(criticalExtensions);
// these extensions are handled by the algorithm
criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
} else {
criticalExtensions = new HashSet();
}
RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
if ((explicitPolicy > 0) || (intersection != null)) {
return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
}
throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
use of org.bouncycastle.asn1.cms.Time in project oxAuth by GluuFederation.
the class OCSPCertificateVerifier method validate.
@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
X509Certificate issuer = issuers.get(0);
ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);
try {
Principal subjectX500Principal = certificate.getSubjectX500Principal();
String ocspUrl = getOCSPUrl(certificate);
if (ocspUrl == null) {
log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
return status;
}
log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");
DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());
// Generate OCSP request
OCSPReq ocspReq = generateOCSPRequest(certificateId);
// Get OCSP response from server
OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
log.error("OCSP response is invalid!");
status.setValidity(CertificateValidity.INVALID);
return status;
}
boolean foundResponse = false;
BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
SingleResp[] singleResps = basicOCSPResp.getResponses();
for (SingleResp singleResp : singleResps) {
CertificateID responseCertificateId = singleResp.getCertID();
if (!certificateId.equals(responseCertificateId)) {
continue;
}
foundResponse = true;
log.debug("OCSP validationDate: " + validationDate);
log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());
status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());
Object certStatus = singleResp.getCertStatus();
if (certStatus == CertificateStatus.GOOD) {
log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
status.setValidity(CertificateValidity.VALID);
} else {
if (singleResp.getCertStatus() instanceof RevokedStatus) {
log.warn("OCSP status is revoked for: " + subjectX500Principal);
if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
status.setValidity(CertificateValidity.VALID);
} else {
Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate);
status.setRevocationDate(revocationDate);
status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
status.setValidity(CertificateValidity.REVOKED);
}
}
}
}
if (!foundResponse) {
log.error("There is no matching OCSP response entries");
}
} catch (Exception ex) {
log.error("OCSP exception: ", ex);
}
return status;
}
Aggregations