use of com.android.apksig.internal.x509.Certificate in project xipki by xipki.
the class X509Ca method addXipkiCertset.
// method generateCrl
/**
* Add XiPKI extension CrlCertSet.
*
* <pre>
* Xipki-CrlCertSet ::= SET OF Xipki-CrlCert
*
* Xipki-CrlCert ::= SEQUENCE {
* serial INTEGER
* cert [0] EXPLICIT Certificate OPTIONAL
* profileName [1] EXPLICIT UTF8String OPTIONAL
* }
* </pre>
*/
private void addXipkiCertset(X509v2CRLBuilder crlBuilder, boolean deltaCrl, CrlControl control, Date notExpireAt, boolean onlyCaCerts, boolean onlyUserCerts) throws OperationException {
if (deltaCrl || !control.isXipkiCertsetIncluded()) {
return;
}
ASN1EncodableVector vector = new ASN1EncodableVector();
final int numEntries = 100;
long startId = 1;
List<SerialWithId> serials;
do {
serials = certstore.getCertSerials(caIdent, notExpireAt, startId, numEntries, false, onlyCaCerts, onlyUserCerts);
long maxId = 1;
for (SerialWithId sid : serials) {
if (sid.getId() > maxId) {
maxId = sid.getId();
}
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new ASN1Integer(sid.getSerial()));
Integer profileId = null;
if (control.isXipkiCertsetCertIncluded()) {
X509CertificateInfo certInfo;
try {
certInfo = certstore.getCertificateInfoForId(caIdent, caCert, sid.getId(), caIdNameMap);
} catch (CertificateException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CertificateException: " + ex.getMessage());
}
Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert());
vec.add(new DERTaggedObject(true, 0, cert));
if (control.isXipkiCertsetProfilenameIncluded()) {
profileId = certInfo.getProfile().getId();
}
} else if (control.isXipkiCertsetProfilenameIncluded()) {
profileId = certstore.getCertProfileForId(caIdent, sid.getId());
}
if (profileId != null) {
String profileName = caIdNameMap.getCertprofileName(profileId);
vec.add(new DERTaggedObject(true, 1, new DERUTF8String(profileName)));
}
vector.add(new DERSequence(vec));
}
// end for
startId = maxId + 1;
} while (serials.size() >= numEntries);
try {
crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector));
} catch (CertIOException ex) {
throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + ex.getMessage());
}
}
use of com.android.apksig.internal.x509.Certificate in project xipki by xipki.
the class CsrGenAction method execute0.
@Override
protected Object execute0() throws Exception {
hashAlgo = hashAlgo.trim().toUpperCase();
if (hashAlgo.indexOf('-') != -1) {
hashAlgo = hashAlgo.replaceAll("-", "");
}
if (needExtensionTypes == null) {
needExtensionTypes = new LinkedList<>();
}
if (wantExtensionTypes == null) {
wantExtensionTypes = new LinkedList<>();
}
// SubjectAltNames
List<Extension> extensions = new LinkedList<>();
ASN1OctetString extnValue = createExtnValueSubjectAltName();
if (extnValue != null) {
ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
extensions.add(new Extension(oid, false, extnValue));
needExtensionTypes.add(oid.getId());
}
// SubjectInfoAccess
extnValue = createExtnValueSubjectInfoAccess();
if (extnValue != null) {
ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
extensions.add(new Extension(oid, false, extnValue));
needExtensionTypes.add(oid.getId());
}
// Keyusage
if (isNotEmpty(keyusages)) {
Set<KeyUsage> usages = new HashSet<>();
for (String usage : keyusages) {
usages.add(KeyUsage.getKeyUsage(usage));
}
org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
ASN1ObjectIdentifier extType = Extension.keyUsage;
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// ExtendedKeyusage
if (isNotEmpty(extkeyusages)) {
ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// QcEuLimitValue
if (isNotEmpty(qcEuLimits)) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (String m : qcEuLimits) {
StringTokenizer st = new StringTokenizer(m, ":");
try {
String currencyS = st.nextToken();
String amountS = st.nextToken();
String exponentS = st.nextToken();
Iso4217CurrencyCode currency;
try {
int intValue = Integer.parseInt(currencyS);
currency = new Iso4217CurrencyCode(intValue);
} catch (NumberFormatException ex) {
currency = new Iso4217CurrencyCode(currencyS);
}
int amount = Integer.parseInt(amountS);
int exponent = Integer.parseInt(exponentS);
MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue);
vec.add(statment);
} catch (Exception ex) {
throw new Exception("invalid qc-eu-limit '" + m + "'");
}
}
ASN1ObjectIdentifier extType = Extension.qCStatements;
ASN1Sequence extValue = new DERSequence(vec);
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// biometricInfo
if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType) ? new TypeOfBiometricData(Integer.parseInt(biometricType)) : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));
ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
byte[] biometricBytes = IoUtil.read(biometricFile);
MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
md.reset();
byte[] tmpBiometricDataHash = md.digest(biometricBytes);
DERIA5String tmpSourceDataUri = null;
if (biometricUri != null) {
tmpSourceDataUri = new DERIA5String(biometricUri);
}
BiometricData biometricData = new BiometricData(tmpBiometricType, new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash), tmpSourceDataUri);
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(biometricData);
ASN1ObjectIdentifier extType = Extension.biometricInfo;
ASN1Sequence extValue = new DERSequence(vec);
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
} else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
// Do nothing
} else {
throw new Exception("either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set");
}
for (Extension addExt : getAdditionalExtensions()) {
extensions.add(addExt);
}
needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());
if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes), textToAsn1ObjectIdentifers(wantExtensionTypes));
extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded()));
}
ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain, gm));
Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
if (CollectionUtil.isNonEmpty(extensions)) {
attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions.toArray(new Extension[0])));
}
if (StringUtil.isNotBlank(challengePassword)) {
attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
}
SubjectPublicKeyInfo subjectPublicKeyInfo;
if (signer.getCertificate() != null) {
Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
} else {
subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
}
X500Name subjectDn = getSubject(subject);
PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);
File file = new File(outputFilename);
saveVerbose("saved CSR to file", file, csr.getEncoded());
return null;
}
use of com.android.apksig.internal.x509.Certificate in project xipki by xipki.
the class GetCrlCmd method execute0.
@Override
protected Object execute0() throws Exception {
Certificate cert = Certificate.getInstance(IoUtil.read(certFile));
ScepClient client = getScepClient();
X509CRL crl = client.scepGetCrl(getIdentityKey(), getIdentityCert(), cert.getIssuer(), cert.getSerialNumber().getPositiveValue());
if (crl == null) {
throw new CmdFailure("received no CRL from server");
}
saveVerbose("saved CRL to file", new File(outputFile), crl.getEncoded());
return null;
}
use of com.android.apksig.internal.x509.Certificate in project xipki by xipki.
the class CaLoadTestRevokeCmd method execute0.
@Override
protected Object execute0() throws Exception {
if (numThreads < 1) {
throw new IllegalCmdParamException("invalid number of threads " + numThreads);
}
if (!(serialNumberFile == null ^ caDbConfFile == null)) {
throw new IllegalCmdParamException("exactly one of ca-db and serial-file must be specified");
}
String description = StringUtil.concatObjectsCap(200, "issuer: ", issuerCertFile, "\ncadb: ", caDbConfFile, "\nserialNumberFile: ", serialNumberFile, "\nmaxCerts: ", maxCerts, "\n#certs/req: ", num, "\nunit: ", num, " certificate", (num > 1 ? "s" : ""), "\n");
Certificate caCert = Certificate.getInstance(IoUtil.read(issuerCertFile));
Properties props = new Properties();
props.load(new FileInputStream(IoUtil.expandFilepath(caDbConfFile)));
props.setProperty("autoCommit", "false");
props.setProperty("readOnly", "true");
props.setProperty("maximumPoolSize", "1");
props.setProperty("minimumIdle", "1");
DataSourceWrapper caDataSource = null;
Iterator<BigInteger> serialNumberIterator;
if (caDbConfFile != null) {
caDataSource = new DataSourceFactory().createDataSource("ds-" + caDbConfFile, props, securityFactory.getPasswordResolver());
serialNumberIterator = new DbGoodCertSerialIterator(caCert, caDataSource);
} else {
serialNumberIterator = new FileBigIntegerIterator(serialNumberFile, hex, false);
}
try {
CaLoadTestRevoke loadTest = new CaLoadTestRevoke(caClient, caCert, serialNumberIterator, maxCerts, num, description);
loadTest.setDuration(duration);
loadTest.setThreads(numThreads);
loadTest.test();
} finally {
if (caDataSource != null) {
caDataSource.close();
}
if (serialNumberIterator instanceof FileBigIntegerIterator) {
((FileBigIntegerIterator) serialNumberIterator).close();
}
}
return null;
}
use of com.android.apksig.internal.x509.Certificate in project xipki by xipki.
the class X509CertprofileQa method checkCert.
// constructor
public ValidationResult checkCert(byte[] certBytes, X509IssuerInfo issuerInfo, X500Name requestedSubject, SubjectPublicKeyInfo requestedPublicKey, Extensions requestedExtensions) {
ParamUtil.requireNonNull("certBytes", certBytes);
ParamUtil.requireNonNull("issuerInfo", issuerInfo);
ParamUtil.requireNonNull("requestedSubject", requestedSubject);
ParamUtil.requireNonNull("requestedPublicKey", requestedPublicKey);
List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();
Certificate bcCert;
TBSCertificate tbsCert;
X509Certificate cert;
ValidationIssue issue;
// certificate size
issue = new ValidationIssue("X509.SIZE", "certificate size");
resultIssues.add(issue);
Integer maxSize = certProfile.getMaxSize();
if (maxSize != 0) {
int size = certBytes.length;
if (size > maxSize) {
issue.setFailureMessage(String.format("certificate exceeds the maximal allowed size: %d > %d", size, maxSize));
}
}
// certificate encoding
issue = new ValidationIssue("X509.ENCODING", "certificate encoding");
resultIssues.add(issue);
try {
bcCert = Certificate.getInstance(certBytes);
tbsCert = bcCert.getTBSCertificate();
cert = X509Util.parseCert(certBytes);
} catch (CertificateException ex) {
issue.setFailureMessage("certificate is not corrected encoded");
return new ValidationResult(resultIssues);
}
// syntax version
issue = new ValidationIssue("X509.VERSION", "certificate version");
resultIssues.add(issue);
int versionNumber = tbsCert.getVersionNumber();
X509CertVersion expVersion = certProfile.getVersion();
if (versionNumber != expVersion.getVersionNumber()) {
issue.setFailureMessage("is '" + versionNumber + "' but expected '" + expVersion.getVersionNumber() + "'");
}
// serialNumber
issue = new ValidationIssue("X509.serialNumber", "certificate serial number");
resultIssues.add(issue);
BigInteger serialNumber = tbsCert.getSerialNumber().getValue();
if (serialNumber.signum() != 1) {
issue.setFailureMessage("not positive");
} else {
if (serialNumber.bitLength() >= 160) {
issue.setFailureMessage("serial number has more than 20 octets");
}
}
// signatureAlgorithm
List<String> signatureAlgorithms = certProfile.getSignatureAlgorithms();
if (CollectionUtil.isNonEmpty(signatureAlgorithms)) {
issue = new ValidationIssue("X509.SIGALG", "signature algorithm");
resultIssues.add(issue);
AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm();
AlgorithmIdentifier tbsSigAlgId = tbsCert.getSignature();
if (!tbsSigAlgId.equals(sigAlgId)) {
issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm");
}
try {
String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId);
if (!issue.isFailed()) {
if (!signatureAlgorithms.contains(sigAlgo)) {
issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed");
}
}
// check parameters
if (!issue.isFailed()) {
AlgorithmIdentifier expSigAlgId = AlgorithmUtil.getSigAlgId(sigAlgo);
if (!expSigAlgId.equals(sigAlgId)) {
issue.setFailureMessage("invalid parameters");
}
}
} catch (NoSuchAlgorithmException ex) {
issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId());
}
}
// notBefore encoding
issue = new ValidationIssue("X509.NOTBEFORE.ENCODING", "notBefore encoding");
checkTime(tbsCert.getStartDate(), issue);
// notAfter encoding
issue = new ValidationIssue("X509.NOTAFTER.ENCODING", "notAfter encoding");
checkTime(tbsCert.getStartDate(), issue);
// notBefore
if (certProfile.isNotBeforeMidnight()) {
issue = new ValidationIssue("X509.NOTBEFORE", "notBefore midnight");
resultIssues.add(issue);
Calendar cal = Calendar.getInstance(UTC);
cal.setTime(cert.getNotBefore());
int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
if (hourOfDay != 0 || minute != 0 || second != 0) {
issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)");
}
}
// validity
issue = new ValidationIssue("X509.VALIDITY", "cert validity");
resultIssues.add(issue);
if (cert.getNotAfter().before(cert.getNotBefore())) {
issue.setFailureMessage("notAfter must not be before notBefore");
} else if (cert.getNotBefore().before(issuerInfo.getCaNotBefore())) {
issue.setFailureMessage("notBefore must not be before CA's notBefore");
} else {
CertValidity validity = certProfile.getValidity();
Date expectedNotAfter = validity.add(cert.getNotBefore());
if (expectedNotAfter.getTime() > MAX_CERT_TIME_MS) {
expectedNotAfter = new Date(MAX_CERT_TIME_MS);
}
if (issuerInfo.isCutoffNotAfter() && expectedNotAfter.after(issuerInfo.getCaNotAfter())) {
expectedNotAfter = issuerInfo.getCaNotAfter();
}
if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) {
issue.setFailureMessage("cert validity is not within " + validity.toString());
}
}
// subjectPublicKeyInfo
resultIssues.addAll(publicKeyChecker.checkPublicKey(bcCert.getSubjectPublicKeyInfo(), requestedPublicKey));
// Signature
issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA");
resultIssues.add(issue);
try {
cert.verify(issuerInfo.getCert().getPublicKey(), "BC");
} catch (Exception ex) {
issue.setFailureMessage("invalid signature");
}
// issuer
issue = new ValidationIssue("X509.ISSUER", "certificate issuer");
resultIssues.add(issue);
if (!cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal())) {
issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate");
}
// subject
resultIssues.addAll(subjectChecker.checkSubject(bcCert.getSubject(), requestedSubject));
// issuerUniqueID
issue = new ValidationIssue("X509.IssuerUniqueID", "issuerUniqueID");
resultIssues.add(issue);
if (tbsCert.getIssuerUniqueId() != null) {
issue.setFailureMessage("is present but not permitted");
}
// subjectUniqueID
issue = new ValidationIssue("X509.SubjectUniqueID", "subjectUniqueID");
resultIssues.add(issue);
if (tbsCert.getSubjectUniqueId() != null) {
issue.setFailureMessage("is present but not permitted");
}
// extensions
issue = new ValidationIssue("X509.GrantedSubject", "grantedSubject");
resultIssues.add(issue);
resultIssues.addAll(extensionsChecker.checkExtensions(bcCert, issuerInfo, requestedExtensions, requestedSubject));
return new ValidationResult(resultIssues);
}
Aggregations