use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.
the class XmlX509Certprofile method getExtensions.
@Override
public ExtensionValues getExtensions(Map<ASN1ObjectIdentifier, ExtensionControl> extensionOccurences, X500Name requestedSubject, X500Name grantedSubject, Extensions requestedExtensions, Date notBefore, Date notAfter, PublicCaInfo caInfo) throws CertprofileException, BadCertTemplateException {
ExtensionValues values = new ExtensionValues();
if (CollectionUtil.isEmpty(extensionOccurences)) {
return values;
}
ParamUtil.requireNonNull("requestedSubject", requestedSubject);
ParamUtil.requireNonNull("notBefore", notBefore);
ParamUtil.requireNonNull("notAfter", notAfter);
Set<ASN1ObjectIdentifier> occurences = new HashSet<>(extensionOccurences.keySet());
// AuthorityKeyIdentifier
// processed by the CA
// SubjectKeyIdentifier
// processed by the CA
// KeyUsage
// processed by the CA
// CertificatePolicies
ASN1ObjectIdentifier type = Extension.certificatePolicies;
if (certificatePolicies != null) {
if (occurences.remove(type)) {
values.addExtension(type, certificatePolicies);
}
}
// Policy Mappings
type = Extension.policyMappings;
if (policyMappings != null) {
if (occurences.remove(type)) {
values.addExtension(type, policyMappings);
}
}
// SubjectAltName
type = Extension.subjectAlternativeName;
if (occurences.contains(type)) {
GeneralNames genNames = createRequestedSubjectAltNames(requestedSubject, grantedSubject, requestedExtensions);
if (genNames != null) {
ExtensionValue value = new ExtensionValue(extensionControls.get(type).isCritical(), genNames);
values.addExtension(type, value);
occurences.remove(type);
}
}
// IssuerAltName
// processed by the CA
// Subject Directory Attributes
type = Extension.subjectDirectoryAttributes;
if (occurences.contains(type) && subjectDirAttrsControl != null) {
Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type);
if (extension == null) {
throw new BadCertTemplateException("no SubjectDirecotryAttributes extension is contained in the request");
}
ASN1GeneralizedTime dateOfBirth = null;
String placeOfBirth = null;
String gender = null;
List<String> countryOfCitizenshipList = new LinkedList<>();
List<String> countryOfResidenceList = new LinkedList<>();
Map<ASN1ObjectIdentifier, List<ASN1Encodable>> otherAttrs = new HashMap<>();
Vector<?> reqSubDirAttrs = SubjectDirectoryAttributes.getInstance(extension.getParsedValue()).getAttributes();
final int n = reqSubDirAttrs.size();
for (int i = 0; i < n; i++) {
Attribute attr = (Attribute) reqSubDirAttrs.get(i);
ASN1ObjectIdentifier attrType = attr.getAttrType();
ASN1Encodable attrVal = attr.getAttributeValues()[0];
if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(attrType)) {
dateOfBirth = ASN1GeneralizedTime.getInstance(attrVal);
} else if (ObjectIdentifiers.DN_PLACE_OF_BIRTH.equals(attrType)) {
placeOfBirth = DirectoryString.getInstance(attrVal).getString();
} else if (ObjectIdentifiers.DN_GENDER.equals(attrType)) {
gender = DERPrintableString.getInstance(attrVal).getString();
} else if (ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP.equals(attrType)) {
String country = DERPrintableString.getInstance(attrVal).getString();
countryOfCitizenshipList.add(country);
} else if (ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE.equals(attrType)) {
String country = DERPrintableString.getInstance(attrVal).getString();
countryOfResidenceList.add(country);
} else {
List<ASN1Encodable> otherAttrVals = otherAttrs.get(attrType);
if (otherAttrVals == null) {
otherAttrVals = new LinkedList<>();
otherAttrs.put(attrType, otherAttrVals);
}
otherAttrVals.add(attrVal);
}
}
Vector<Attribute> attrs = new Vector<>();
for (ASN1ObjectIdentifier attrType : subjectDirAttrsControl.getTypes()) {
if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(attrType)) {
if (dateOfBirth != null) {
String timeStirng = dateOfBirth.getTimeString();
if (!SubjectDnSpec.PATTERN_DATE_OF_BIRTH.matcher(timeStirng).matches()) {
throw new BadCertTemplateException("invalid dateOfBirth " + timeStirng);
}
attrs.add(new Attribute(attrType, new DERSet(dateOfBirth)));
continue;
}
} else if (ObjectIdentifiers.DN_PLACE_OF_BIRTH.equals(attrType)) {
if (placeOfBirth != null) {
ASN1Encodable attrVal = new DERUTF8String(placeOfBirth);
attrs.add(new Attribute(attrType, new DERSet(attrVal)));
continue;
}
} else if (ObjectIdentifiers.DN_GENDER.equals(attrType)) {
if (gender != null && !gender.isEmpty()) {
char ch = gender.charAt(0);
if (!(gender.length() == 1 && (ch == 'f' || ch == 'F' || ch == 'm' || ch == 'M'))) {
throw new BadCertTemplateException("invalid gender " + gender);
}
ASN1Encodable attrVal = new DERPrintableString(gender);
attrs.add(new Attribute(attrType, new DERSet(attrVal)));
continue;
}
} else if (ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP.equals(attrType)) {
if (!countryOfCitizenshipList.isEmpty()) {
for (String country : countryOfCitizenshipList) {
if (!SubjectDnSpec.isValidCountryAreaCode(country)) {
throw new BadCertTemplateException("invalid countryOfCitizenship code " + country);
}
ASN1Encodable attrVal = new DERPrintableString(country);
attrs.add(new Attribute(attrType, new DERSet(attrVal)));
}
continue;
}
} else if (ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE.equals(attrType)) {
if (!countryOfResidenceList.isEmpty()) {
for (String country : countryOfResidenceList) {
if (!SubjectDnSpec.isValidCountryAreaCode(country)) {
throw new BadCertTemplateException("invalid countryOfResidence code " + country);
}
ASN1Encodable attrVal = new DERPrintableString(country);
attrs.add(new Attribute(attrType, new DERSet(attrVal)));
}
continue;
}
} else if (otherAttrs.containsKey(attrType)) {
for (ASN1Encodable attrVal : otherAttrs.get(attrType)) {
attrs.add(new Attribute(attrType, new DERSet(attrVal)));
}
continue;
}
throw new BadCertTemplateException("could not process type " + attrType.getId() + " in extension SubjectDirectoryAttributes");
}
SubjectDirectoryAttributes subjDirAttrs = new SubjectDirectoryAttributes(attrs);
ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), subjDirAttrs);
values.addExtension(type, extValue);
occurences.remove(type);
}
// Basic Constraints
// processed by the CA
// Name Constraints
type = Extension.nameConstraints;
if (nameConstraints != null) {
if (occurences.remove(type)) {
values.addExtension(type, nameConstraints);
}
}
// PolicyConstrains
type = Extension.policyConstraints;
if (policyConstraints != null) {
if (occurences.remove(type)) {
values.addExtension(type, policyConstraints);
}
}
// ExtendedKeyUsage
// processed by CA
// CRL Distribution Points
// processed by the CA
// Inhibit anyPolicy
type = Extension.inhibitAnyPolicy;
if (inhibitAnyPolicy != null) {
if (occurences.remove(type)) {
values.addExtension(type, inhibitAnyPolicy);
}
}
// Freshest CRL
// processed by the CA
// Authority Information Access
// processed by the CA
// Subject Information Access
// processed by the CA
// Admission
type = ObjectIdentifiers.id_extension_admission;
if (occurences.contains(type) && admission != null) {
if (admission.isInputFromRequestRequired()) {
Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type);
if (extension == null) {
throw new BadCertTemplateException("No Admission extension is contained in the request");
}
Admissions[] reqAdmissions = org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax.getInstance(extension.getParsedValue()).getContentsOfAdmissions();
final int n = reqAdmissions.length;
List<List<String>> reqRegNumsList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
Admissions reqAdmission = reqAdmissions[i];
ProfessionInfo[] reqPis = reqAdmission.getProfessionInfos();
List<String> reqNums = new ArrayList<>(reqPis.length);
reqRegNumsList.add(reqNums);
for (ProfessionInfo reqPi : reqPis) {
String reqNum = reqPi.getRegistrationNumber();
reqNums.add(reqNum);
}
}
values.addExtension(type, admission.getExtensionValue(reqRegNumsList));
occurences.remove(type);
} else {
values.addExtension(type, admission.getExtensionValue(null));
occurences.remove(type);
}
}
// OCSP Nocheck
// processed by the CA
// restriction
type = ObjectIdentifiers.id_extension_restriction;
if (restriction != null) {
if (occurences.remove(type)) {
values.addExtension(type, restriction);
}
}
// AdditionalInformation
type = ObjectIdentifiers.id_extension_additionalInformation;
if (additionalInformation != null) {
if (occurences.remove(type)) {
values.addExtension(type, additionalInformation);
}
}
// ValidityModel
type = ObjectIdentifiers.id_extension_validityModel;
if (validityModel != null) {
if (occurences.remove(type)) {
values.addExtension(type, validityModel);
}
}
// PrivateKeyUsagePeriod
type = Extension.privateKeyUsagePeriod;
if (occurences.contains(type)) {
Date tmpNotAfter;
if (privateKeyUsagePeriod == null) {
tmpNotAfter = notAfter;
} else {
tmpNotAfter = privateKeyUsagePeriod.add(notBefore);
if (tmpNotAfter.after(notAfter)) {
tmpNotAfter = notAfter;
}
}
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(notBefore)));
vec.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(tmpNotAfter)));
ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), new DERSequence(vec));
values.addExtension(type, extValue);
occurences.remove(type);
}
// QCStatements
type = Extension.qCStatements;
if (occurences.contains(type) && (qcStatments != null || qcStatementsOption != null)) {
if (qcStatments != null) {
values.addExtension(type, qcStatments);
occurences.remove(type);
} else if (requestedExtensions != null && qcStatementsOption != null) {
// extract the euLimit data from request
Extension extension = requestedExtensions.getExtension(type);
if (extension == null) {
throw new BadCertTemplateException("No QCStatement extension is contained in the request");
}
ASN1Sequence seq = ASN1Sequence.getInstance(extension.getParsedValue());
Map<String, int[]> qcEuLimits = new HashMap<>();
final int n = seq.size();
for (int i = 0; i < n; i++) {
QCStatement stmt = QCStatement.getInstance(seq.getObjectAt(i));
if (!ObjectIdentifiers.id_etsi_qcs_QcLimitValue.equals(stmt.getStatementId())) {
continue;
}
MonetaryValue monetaryValue = MonetaryValue.getInstance(stmt.getStatementInfo());
int amount = monetaryValue.getAmount().intValue();
int exponent = monetaryValue.getExponent().intValue();
Iso4217CurrencyCode currency = monetaryValue.getCurrency();
String currencyS = currency.isAlphabetic() ? currency.getAlphabetic().toUpperCase() : Integer.toString(currency.getNumeric());
qcEuLimits.put(currencyS, new int[] { amount, exponent });
}
ASN1EncodableVector vec = new ASN1EncodableVector();
for (QcStatementOption m : qcStatementsOption) {
if (m.getStatement() != null) {
vec.add(m.getStatement());
continue;
}
MonetaryValueOption monetaryOption = m.getMonetaryValueOption();
String currencyS = monetaryOption.getCurrencyString();
int[] limit = qcEuLimits.get(currencyS);
if (limit == null) {
throw new BadCertTemplateException("no EuLimitValue is specified for currency '" + currencyS + "'");
}
int amount = limit[0];
Range2Type range = monetaryOption.getAmountRange();
if (amount < range.getMin() || amount > range.getMax()) {
throw new BadCertTemplateException("amount for currency '" + currencyS + "' is not within [" + range.getMin() + ", " + range.getMax() + "]");
}
int exponent = limit[1];
range = monetaryOption.getExponentRange();
if (exponent < range.getMin() || exponent > range.getMax()) {
throw new BadCertTemplateException("exponent for currency '" + currencyS + "' is not within [" + range.getMin() + ", " + range.getMax() + "]");
}
MonetaryValue monetaryVale = new MonetaryValue(monetaryOption.getCurrency(), amount, exponent);
QCStatement qcStatment = new QCStatement(m.getStatementId(), monetaryVale);
vec.add(qcStatment);
}
ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), new DERSequence(vec));
values.addExtension(type, extValue);
occurences.remove(type);
} else {
throw new RuntimeException("should not reach here");
}
}
// BiometricData
type = Extension.biometricInfo;
if (occurences.contains(type) && biometricInfo != null) {
Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type);
if (extension == null) {
throw new BadCertTemplateException("no biometricInfo extension is contained in the request");
}
ASN1Sequence seq = ASN1Sequence.getInstance(extension.getParsedValue());
final int n = seq.size();
if (n < 1) {
throw new BadCertTemplateException("biometricInfo extension in request contains empty sequence");
}
ASN1EncodableVector vec = new ASN1EncodableVector();
for (int i = 0; i < n; i++) {
BiometricData bd = BiometricData.getInstance(seq.getObjectAt(i));
TypeOfBiometricData bdType = bd.getTypeOfBiometricData();
if (!biometricInfo.isTypePermitted(bdType)) {
throw new BadCertTemplateException("biometricInfo[" + i + "].typeOfBiometricData is not permitted");
}
ASN1ObjectIdentifier hashAlgo = bd.getHashAlgorithm().getAlgorithm();
if (!biometricInfo.isHashAlgorithmPermitted(hashAlgo)) {
throw new BadCertTemplateException("biometricInfo[" + i + "].hashAlgorithm is not permitted");
}
int expHashValueSize;
try {
expHashValueSize = AlgorithmUtil.getHashOutputSizeInOctets(hashAlgo);
} catch (NoSuchAlgorithmException ex) {
throw new CertprofileException("should not happen, unknown hash algorithm " + hashAlgo);
}
byte[] hashValue = bd.getBiometricDataHash().getOctets();
if (hashValue.length != expHashValueSize) {
throw new BadCertTemplateException("biometricInfo[" + i + "].biometricDataHash has incorrect length");
}
DERIA5String sourceDataUri = bd.getSourceDataUri();
switch(biometricInfo.getSourceDataUriOccurrence()) {
case FORBIDDEN:
sourceDataUri = null;
break;
case REQUIRED:
if (sourceDataUri == null) {
throw new BadCertTemplateException("biometricInfo[" + i + "].sourceDataUri is not specified in request but is required");
}
break;
case OPTIONAL:
break;
default:
throw new BadCertTemplateException("could not reach here, unknown tripleState");
}
AlgorithmIdentifier newHashAlg = new AlgorithmIdentifier(hashAlgo, DERNull.INSTANCE);
BiometricData newBiometricData = new BiometricData(bdType, newHashAlg, new DEROctetString(hashValue), sourceDataUri);
vec.add(newBiometricData);
}
ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), new DERSequence(vec));
values.addExtension(type, extValue);
occurences.remove(type);
}
// TlsFeature
type = ObjectIdentifiers.id_pe_tlsfeature;
if (tlsFeature != null) {
if (occurences.remove(type)) {
values.addExtension(type, tlsFeature);
}
}
// AuthorizationTemplate
type = ObjectIdentifiers.id_xipki_ext_authorizationTemplate;
if (authorizationTemplate != null) {
if (occurences.remove(type)) {
values.addExtension(type, authorizationTemplate);
}
}
// SMIME
type = ObjectIdentifiers.id_smimeCapabilities;
if (smimeCapabilities != null) {
if (occurences.remove(type)) {
values.addExtension(type, smimeCapabilities);
}
}
// constant extensions
if (constantExtensions != null) {
for (ASN1ObjectIdentifier m : constantExtensions.keySet()) {
if (!occurences.remove(m)) {
continue;
}
ExtensionValue extensionValue = constantExtensions.get(m);
if (extensionValue != null) {
values.addExtension(m, extensionValue);
}
}
}
ExtensionValues extraExtensions = getExtraExtensions(extensionOccurences, requestedSubject, grantedSubject, requestedExtensions, notBefore, notAfter, caInfo);
if (extraExtensions != null) {
for (ASN1ObjectIdentifier m : extraExtensions.getExtensionTypes()) {
values.addExtension(m, extraExtensions.getExtensionValue(m));
}
}
return values;
}
use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.
the class X509CmpRequestor method buildUnrevokeOrRemoveCertRequest.
// method buildRevokeCertRequest
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request, int reasonCode) throws CmpRequestorException {
PKIHeader header = buildPkiHeader(null);
List<UnrevokeOrRemoveCertEntry> requestEntries = request.getRequestEntries();
List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
for (UnrevokeOrRemoveCertEntry requestEntry : requestEntries) {
CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
certTempBuilder.setIssuer(requestEntry.getIssuer());
certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
byte[] aki = requestEntry.getAuthorityKeyIdentifier();
if (aki != null) {
Extensions certTempExts = getCertTempExtensions(aki);
certTempBuilder.setExtensions(certTempExts);
}
Extension[] extensions = new Extension[1];
try {
ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
} catch (IOException ex) {
throw new CmpRequestorException(ex.getMessage(), ex);
}
Extensions exts = new Extensions(extensions);
RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
revDetailsArray.add(revDetails);
}
RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
return new PKIMessage(header, body);
}
use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.
the class CaCertStoreDbImporter method importEntries.
private long importEntries(CaDbEntryType type, String entriesZipFile, long minId, File processLogFile, ProcessLog processLog, int numProcessedInLastProcess, PreparedStatement[] statements, String[] sqls) throws Exception {
final int numEntriesPerCommit = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerCommit));
ZipFile zipFile = new ZipFile(new File(entriesZipFile));
ZipEntry entriesXmlEntry = zipFile.getEntry("overview.xml");
DbiXmlReader entries;
try {
entries = createReader(type, zipFile.getInputStream(entriesXmlEntry));
} catch (Exception ex) {
try {
zipFile.close();
} catch (Exception e2) {
LOG.error("could not close ZIP file {}: {}", entriesZipFile, e2.getMessage());
LOG.debug("could not close ZIP file " + entriesZipFile, e2);
}
throw ex;
}
disableAutoCommit();
try {
int numEntriesInBatch = 0;
long lastSuccessfulEntryId = 0;
while (entries.hasNext()) {
if (stopMe.get()) {
throw new InterruptedException("interrupted by the user");
}
IdentifidDbObjectType entry = (IdentifidDbObjectType) entries.next();
long id = entry.getId();
if (id < minId) {
continue;
}
numEntriesInBatch++;
if (CaDbEntryType.CERT == type) {
CertType cert = (CertType) entry;
int certArt = (cert.getArt() == null) ? 1 : cert.getArt();
String filename = cert.getFile();
// rawcert
ZipEntry certZipEnty = zipFile.getEntry(filename);
// rawcert
byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));
TBSCertificate tbsCert;
try {
Certificate cc = Certificate.getInstance(encodedCert);
tbsCert = cc.getTBSCertificate();
} catch (RuntimeException ex) {
LOG.error("could not parse certificate in file {}", filename);
LOG.debug("could not parse certificate in file " + filename, ex);
throw new CertificateException(ex.getMessage(), ex);
}
byte[] encodedKey = tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
String b64Sha1FpCert = HashAlgo.SHA1.base64Hash(encodedCert);
// cert
String subjectText = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);
PreparedStatement psCert = statements[0];
PreparedStatement psRawcert = statements[1];
try {
int idx = 1;
psCert.setLong(idx++, id);
psCert.setInt(idx++, certArt);
psCert.setLong(idx++, cert.getUpdate());
psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
psCert.setString(idx++, subjectText);
long fpSubject = X509Util.fpCanonicalizedName(tbsCert.getSubject());
psCert.setLong(idx++, fpSubject);
if (cert.getFpRs() != null) {
psCert.setLong(idx++, cert.getFpRs());
} else {
psCert.setNull(idx++, Types.BIGINT);
}
psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
setBoolean(psCert, idx++, cert.getRev());
setInt(psCert, idx++, cert.getRr());
setLong(psCert, idx++, cert.getRt());
setLong(psCert, idx++, cert.getRit());
setInt(psCert, idx++, cert.getPid());
setInt(psCert, idx++, cert.getCaId());
setInt(psCert, idx++, cert.getRid());
setInt(psCert, idx++, cert.getUid());
psCert.setLong(idx++, FpIdCalculator.hash(encodedKey));
Extension extension = tbsCert.getExtensions().getExtension(Extension.basicConstraints);
boolean ee = true;
if (extension != null) {
ASN1Encodable asn1 = extension.getParsedValue();
ee = !BasicConstraints.getInstance(asn1).isCA();
}
psCert.setInt(idx++, ee ? 1 : 0);
psCert.setInt(idx++, cert.getReqType());
String tidS = null;
if (cert.getTid() != null) {
tidS = cert.getTid();
}
psCert.setString(idx++, tidS);
psCert.addBatch();
} catch (SQLException ex) {
throw translate(SQL_ADD_CERT, ex);
}
try {
int idx = 1;
psRawcert.setLong(idx++, cert.getId());
psRawcert.setString(idx++, b64Sha1FpCert);
psRawcert.setString(idx++, cert.getRs());
psRawcert.setString(idx++, Base64.encodeToString(encodedCert));
psRawcert.addBatch();
} catch (SQLException ex) {
throw translate(SQL_ADD_CRAW, ex);
}
} else if (CaDbEntryType.CRL == type) {
PreparedStatement psAddCrl = statements[0];
CrlType crl = (CrlType) entry;
String filename = crl.getFile();
// CRL
ZipEntry zipEnty = zipFile.getEntry(filename);
// rawcert
byte[] encodedCrl = IoUtil.read(zipFile.getInputStream(zipEnty));
X509CRL x509crl = null;
try {
x509crl = X509Util.parseCrl(encodedCrl);
} catch (Exception ex) {
LOG.error("could not parse CRL in file {}", filename);
LOG.debug("could not parse CRL in file " + filename, ex);
if (ex instanceof CRLException) {
throw (CRLException) ex;
} else {
throw new CRLException(ex.getMessage(), ex);
}
}
try {
byte[] octetString = x509crl.getExtensionValue(Extension.cRLNumber.getId());
if (octetString == null) {
LOG.warn("CRL without CRL number, ignore it");
continue;
}
byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
// CHECKSTYLE:SKIP
BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
BigInteger baseCrlNumber = null;
octetString = x509crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
if (octetString != null) {
extnValue = DEROctetString.getInstance(octetString).getOctets();
baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
}
int idx = 1;
psAddCrl.setLong(idx++, crl.getId());
psAddCrl.setInt(idx++, crl.getCaId());
psAddCrl.setLong(idx++, crlNumber.longValue());
psAddCrl.setLong(idx++, x509crl.getThisUpdate().getTime() / 1000);
if (x509crl.getNextUpdate() != null) {
psAddCrl.setLong(idx++, x509crl.getNextUpdate().getTime() / 1000);
} else {
psAddCrl.setNull(idx++, Types.INTEGER);
}
if (baseCrlNumber == null) {
setBoolean(psAddCrl, idx++, false);
psAddCrl.setNull(idx++, Types.BIGINT);
} else {
setBoolean(psAddCrl, idx++, true);
psAddCrl.setLong(idx++, baseCrlNumber.longValue());
}
String str = Base64.encodeToString(encodedCrl);
psAddCrl.setString(idx++, str);
psAddCrl.addBatch();
} catch (SQLException ex) {
System.err.println("could not import CRL with ID=" + crl.getId() + ", message: " + ex.getMessage());
throw ex;
}
} else if (CaDbEntryType.REQUEST == type) {
PreparedStatement psAddRequest = statements[0];
RequestType request = (RequestType) entry;
String filename = request.getFile();
ZipEntry zipEnty = zipFile.getEntry(filename);
byte[] encodedRequest = IoUtil.read(zipFile.getInputStream(zipEnty));
try {
int idx = 1;
psAddRequest.setLong(idx++, request.getId());
psAddRequest.setLong(idx++, request.getUpdate());
psAddRequest.setString(idx++, Base64.encodeToString(encodedRequest));
psAddRequest.addBatch();
} catch (SQLException ex) {
System.err.println("could not import REQUEST with ID=" + request.getId() + ", message: " + ex.getMessage());
throw ex;
}
} else if (CaDbEntryType.REQCERT == type) {
PreparedStatement psAddReqCert = statements[0];
RequestCertType reqCert = (RequestCertType) entry;
try {
int idx = 1;
psAddReqCert.setLong(idx++, reqCert.getId());
psAddReqCert.setLong(idx++, reqCert.getRid());
psAddReqCert.setLong(idx++, reqCert.getCid());
psAddReqCert.addBatch();
} catch (SQLException ex) {
System.err.println("could not import REQUEST with ID=" + reqCert.getId() + ", message: " + ex.getMessage());
throw ex;
}
} else {
throw new RuntimeException("Unknown CaDbEntryType " + type);
}
boolean isLastBlock = !entries.hasNext();
if (numEntriesInBatch > 0 && (numEntriesInBatch % numEntriesPerCommit == 0 || isLastBlock)) {
if (evaulateOnly) {
for (PreparedStatement m : statements) {
m.clearBatch();
}
} else {
String sql = null;
try {
for (int i = 0; i < sqls.length; i++) {
sql = sqls[i];
statements[i].executeBatch();
}
sql = null;
commit("(commit import to CA)");
} catch (Throwable th) {
rollback();
deleteFromTableWithLargerId(type.getTableName(), "ID", id, LOG);
if (CaDbEntryType.CERT == type) {
deleteFromTableWithLargerId("CRAW", "CID", id, LOG);
}
if (th instanceof SQLException) {
throw translate(sql, (SQLException) th);
} else if (th instanceof Exception) {
throw (Exception) th;
} else {
throw new Exception(th);
}
}
}
lastSuccessfulEntryId = id;
processLog.addNumProcessed(numEntriesInBatch);
numEntriesInBatch = 0;
echoToFile(type + ":" + (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulEntryId, processLogFile);
processLog.printStatus();
}
}
return lastSuccessfulEntryId;
} finally {
recoverAutoCommit();
zipFile.close();
}
}
use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.
the class OcspStatusCmd method processResponse.
@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
ParamUtil.requireNonNull("response", response);
ParamUtil.requireNonNull("issuerHash", issuerHash);
ParamUtil.requireNonNull("serialNumbers", serialNumbers);
BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
SingleResp[] singleResponses = basicResp.getResponses();
if (singleResponses == null || singleResponses.length == 0) {
throw new CmdFailure("received no status from server");
}
final int n = singleResponses.length;
if (n != serialNumbers.size()) {
throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
}
Date[] thisUpdates = new Date[n];
for (int i = 0; i < n; i++) {
thisUpdates[i] = singleResponses[i].getThisUpdate();
}
// check the signature if available
if (null == basicResp.getSignature()) {
println("response is not signed");
} else {
X509CertificateHolder[] responderCerts = basicResp.getCerts();
if (responderCerts == null || responderCerts.length < 1) {
throw new CmdFailure("no responder certificate is contained in the response");
}
ResponderID respId = basicResp.getResponderId().toASN1Primitive();
X500Name respIdByName = respId.getName();
byte[] respIdByKey = respId.getKeyHash();
X509CertificateHolder respSigner = null;
for (X509CertificateHolder cert : responderCerts) {
if (respIdByName != null) {
if (cert.getSubject().equals(respIdByName)) {
respSigner = cert;
}
} else {
byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
if (Arrays.equals(respIdByKey, spkiSha1)) {
respSigner = cert;
}
}
if (respSigner != null) {
break;
}
}
if (respSigner == null) {
throw new CmdFailure("no responder certificate match the ResponderId");
}
boolean validOn = true;
for (Date thisUpdate : thisUpdates) {
validOn = respSigner.isValidOn(thisUpdate);
if (!validOn) {
throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
}
}
if (validOn) {
PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
boolean sigValid = basicResp.isSignatureValid(cvp);
if (!sigValid) {
throw new CmdFailure("response is equipped with invalid signature");
}
// verify the OCSPResponse signer
if (respIssuer != null) {
boolean certValid = true;
X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
if (X509Util.issues(respIssuer, jceRespSigner)) {
try {
jceRespSigner.verify(respIssuer.getPublicKey());
} catch (SignatureException ex) {
certValid = false;
}
}
if (!certValid) {
throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
}
} else {
println("response is equipped with valid signature");
}
// end if(respIssuer)
}
if (verbose.booleanValue()) {
println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
}
}
for (int i = 0; i < n; i++) {
if (n > 1) {
println("---------------------------- " + i + "----------------------------");
}
SingleResp singleResp = singleResponses[i];
CertificateStatus singleCertStatus = singleResp.getCertStatus();
String status;
if (singleCertStatus == null) {
status = "good";
} else if (singleCertStatus instanceof RevokedStatus) {
RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
Date revTime = revStatus.getRevocationTime();
Date invTime = null;
Extension ext = singleResp.getExtension(Extension.invalidityDate);
if (ext != null) {
invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
}
if (revStatus.hasRevocationReason()) {
int reason = revStatus.getRevocationReason();
if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
status = "unknown (RFC6960)";
} else {
status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
}
} else {
status = "revoked, no reason, revocationTime = " + revTime;
}
} else if (singleCertStatus instanceof UnknownStatus) {
status = "unknown (RFC2560)";
} else {
status = "ERROR";
}
StringBuilder msg = new StringBuilder();
CertificateID certId = singleResp.getCertID();
HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
BigInteger serialNumber = certId.getSerialNumber();
msg.append("issuer matched: ").append(issuerMatch);
msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
msg.append("\nCertificate status: ").append(status);
if (verbose.booleanValue()) {
msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
if (extension != null) {
msg.append("\nCertHash is provided:\n");
ASN1Encodable extensionValue = extension.getParsedValue();
CertHash certHash = CertHash.getInstance(extensionValue);
ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
byte[] hashValue = certHash.getCertificateHash();
msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
if (encodedCerts != null) {
byte[] encodedCert = encodedCerts.get(serialNumber);
MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
byte[] expectedHashValue = md.digest(encodedCert);
if (Arrays.equals(expectedHashValue, hashValue)) {
msg.append("\tThis matches the requested certificate");
} else {
msg.append("\tThis differs from the requested certificate");
}
}
}
// end if (extension != null)
extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
if (extension != null) {
ASN1Encodable extensionValue = extension.getParsedValue();
ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
msg.append("\nArchive-CutOff: ");
msg.append(time.getTimeString());
}
AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
if (sigAlg == null) {
msg.append(("\nresponse is not signed"));
} else {
String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
if (sigAlgName == null) {
sigAlgName = "unknown";
}
msg.append("\nresponse is signed with ").append(sigAlgName);
}
// extensions
msg.append("\nExtensions: ");
List<?> extensionOids = basicResp.getExtensionOIDs();
if (extensionOids == null || extensionOids.size() == 0) {
msg.append("-");
} else {
int size = extensionOids.size();
for (int j = 0; j < size; j++) {
ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
if (name == null) {
msg.append(extensionOid.getId());
} else {
msg.append(name);
}
if (j != size - 1) {
msg.append(", ");
}
}
}
}
// end if (verbose.booleanValue())
println(msg.toString());
}
// end for
println("");
return null;
}
use of com.github.zhenwei.core.asn1.x509.Extension in project Spark by igniterealtime.
the class SparkTrustManager method loadCRL.
public Collection<X509CRL> loadCRL(X509Certificate[] chain) throws IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, CRLException {
// for each certificate in chain
for (X509Certificate cert : chain) {
if (cert.getExtensionValue(Extension.cRLDistributionPoints.getId()) != null) {
ASN1Primitive primitive = JcaX509ExtensionUtils.parseExtensionValue(cert.getExtensionValue(Extension.cRLDistributionPoints.getId()));
// extract distribution point extension
CRLDistPoint distPoint = CRLDistPoint.getInstance(primitive);
DistributionPoint[] dp = distPoint.getDistributionPoints();
// each distribution point extension can hold number of distribution points
for (DistributionPoint d : dp) {
DistributionPointName dpName = d.getDistributionPoint();
// Look for URIs in fullName
if (dpName != null && dpName.getType() == DistributionPointName.FULL_NAME) {
GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
// Look for an URI
for (GeneralName genName : genNames) {
// extract url
URL url = new URL(genName.getName().toString());
try {
// download from Internet to the collection
crlCollection.add(downloadCRL(url));
} catch (CertificateException | CRLException e) {
throw new CRLException("Couldn't download CRL");
}
}
}
}
} else {
Log.warning("Certificate " + cert.getSubjectX500Principal().getName() + " have no CRLs");
}
// parameters for cert store is collection type, using collection with crl create parameters
CollectionCertStoreParameters params = new CollectionCertStoreParameters(crlCollection);
// this parameters are next used for creation of certificate store with crls
crlStore = CertStore.getInstance("Collection", params);
}
return crlCollection;
}
Aggregations