use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project android_frameworks_base by DirtyUnicorns.
the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.
@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
ASN1ObjectIdentifier sigAlgOid;
AlgorithmIdentifier sigAlgId;
byte[] signature;
switch(mKeymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_EC:
sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
sigAlgId = new AlgorithmIdentifier(sigAlgOid);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(0));
signature = new DERSequence().getEncoded();
break;
case KeymasterDefs.KM_ALGORITHM_RSA:
sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
signature = new byte[1];
break;
default:
throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
}
try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
}
tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
tbsGenerator.setSubject(subject);
tbsGenerator.setIssuer(subject);
tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
tbsGenerator.setSignature(sigAlgId);
TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
ASN1EncodableVector result = new ASN1EncodableVector();
result.add(tbsCertificate);
result.add(sigAlgId);
result.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.
the class AbstractOcspRequestor method buildRequest.
// method ask
private OCSPRequest buildRequest(X509Certificate caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
if (hashAlgo == null) {
throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
}
List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
XiOCSPReqBuilder reqBuilder = new XiOCSPReqBuilder();
List<Extension> extensions = new LinkedList<>();
if (nonce != null) {
extensions.add(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
}
if (prefSigAlgs != null && prefSigAlgs.size() > 0) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (AlgorithmIdentifier algId : prefSigAlgs) {
vec.add(new DERSequence(algId));
}
ASN1Sequence extnValue = new DERSequence(vec);
Extension extn;
try {
extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
} catch (IOException ex) {
throw new OcspRequestorException(ex.getMessage(), ex);
}
extensions.add(extn);
}
if (CollectionUtil.isNonEmpty(extensions)) {
reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
}
try {
DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubjectX500Principal().getEncoded()));
TBSCertificate tbsCert;
try {
tbsCert = TBSCertificate.getInstance(caCert.getTBSCertificate());
} catch (CertificateEncodingException ex) {
throw new OcspRequestorException(ex);
}
DEROctetString issuerKeyHash = new DEROctetString(hashAlgo.hash(tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
for (BigInteger serialNumber : serialNumbers) {
CertID certId = new CertID(hashAlgo.getAlgorithmIdentifier(), issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
reqBuilder.addRequest(certId);
}
if (requestOptions.isSignRequest()) {
synchronized (signerLock) {
if (signer == null) {
if (StringUtil.isBlank(signerType)) {
throw new OcspRequestorException("signerType is not configured");
}
if (StringUtil.isBlank(signerConf)) {
throw new OcspRequestorException("signerConf is not configured");
}
X509Certificate cert = null;
if (StringUtil.isNotBlank(signerCertFile)) {
try {
cert = X509Util.parseCert(signerCertFile);
} catch (CertificateException ex) {
throw new OcspRequestorException("could not parse certificate " + signerCertFile + ": " + ex.getMessage());
}
}
try {
signer = getSecurityFactory().createSigner(signerType, new SignerConf(signerConf), cert);
} catch (Exception ex) {
throw new OcspRequestorException("could not create signer: " + ex.getMessage());
}
}
// end if
}
// end synchronized
reqBuilder.setRequestorName(signer.getBcCertificate().getSubject());
X509CertificateHolder[] certChain0 = signer.getBcCertificateChain();
Certificate[] certChain = new Certificate[certChain0.length];
for (int i = 0; i < certChain.length; i++) {
certChain[i] = certChain0[i].toASN1Structure();
}
ConcurrentBagEntrySigner signer0;
try {
signer0 = signer.borrowSigner();
} catch (NoIdleSignerException ex) {
throw new OcspRequestorException("NoIdleSignerException: " + ex.getMessage());
}
try {
return reqBuilder.build(signer0.value(), certChain);
} finally {
signer.requiteSigner(signer0);
}
} else {
return reqBuilder.build();
}
// end if
} catch (OCSPException | IOException ex) {
throw new OcspRequestorException(ex.getMessage(), ex);
}
}
use of com.github.zhenwei.core.asn1.x509.TBSCertificate 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);
}
use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project pdfbox by apache.
the class PublicKeySecurityHandler method computeRecipientInfo.
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws IOException, CertificateEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
TBSCertificate certificate;
try (ASN1InputStream input = new ASN1InputStream(x509certificate.getTBSCertificate())) {
certificate = TBSCertificate.getInstance(input.readObject());
}
AlgorithmIdentifier algorithmId = certificate.getSubjectPublicKeyInfo().getAlgorithm();
IssuerAndSerialNumber serial = new IssuerAndSerialNumber(certificate.getIssuer(), certificate.getSerialNumber().getValue());
Cipher cipher;
try {
cipher = Cipher.getInstance(algorithmId.getAlgorithm().getId(), SecurityProvider.getProvider());
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// should never happen, if this happens throw IOException instead
throw new RuntimeException("Could not find a suitable javax.crypto provider", e);
}
cipher.init(1, x509certificate.getPublicKey());
DEROctetString octets = new DEROctetString(cipher.doFinal(abyte0));
RecipientIdentifier recipientId = new RecipientIdentifier(serial);
return new KeyTransRecipientInfo(recipientId, algorithmId, octets);
}
use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.
the class OcspCertStoreFromCaDbImporter method importCert0.
// method importCert
private long importCert0(HashAlgo certhashAlgo, PreparedStatement psCert, String certsZipFile, boolean revokedOnly, List<Integer> caIds, long minId, File processLogFile, ProcessLog processLog, int numProcessedInLastProcess, ProcessLog importLog) throws Exception {
ZipFile zipFile = new ZipFile(new File(certsZipFile));
ZipEntry certsEntry = zipFile.getEntry("overview.json");
CaCertstore.Certs certs;
try {
certs = JSON.parseObject(zipFile.getInputStream(certsEntry), StandardCharsets.UTF_8, CaCertstore.Certs.class);
} catch (Exception ex) {
try {
zipFile.close();
} catch (Exception e2) {
LOG.error("could not close ZIP file {}: {}", certsZipFile, e2.getMessage());
LOG.debug("could not close ZIP file " + certsZipFile, e2);
}
throw ex;
}
certs.validate();
disableAutoCommit();
try {
int numProcessedEntriesInBatch = 0;
int numImportedEntriesInBatch = 0;
long lastSuccessfulCertId = 0;
List<CaCertstore.Cert> list = certs.getCerts();
final int n = list.size();
for (int i = 0; i < n; i++) {
if (stopMe.get()) {
throw new InterruptedException("interrupted by the user");
}
CaCertstore.Cert cert = list.get(i);
long id = cert.getId();
lastSuccessfulCertId = id;
if (id < minId) {
continue;
}
numProcessedEntriesInBatch++;
if (!revokedOnly || (cert.getRev() != null && cert.getRev() == 1)) {
int caId = cert.getCaId();
if (caIds.contains(caId)) {
numImportedEntriesInBatch++;
String filename = cert.getFile();
// rawcert
ZipEntry certZipEnty = zipFile.getEntry(filename);
// rawcert
byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));
String certhash = certhashAlgo.base64Hash(encodedCert);
TBSCertificate tbsCert;
try {
Certificate cc = Certificate.getInstance(encodedCert);
tbsCert = cc.getTBSCertificate();
} catch (RuntimeException ex) {
LogUtil.error(LOG, ex, "could not parse certificate in file " + filename);
throw new CertificateException(ex.getMessage(), ex);
}
String subject = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);
// cert
try {
int idx = 1;
psCert.setLong(idx++, id);
psCert.setInt(idx++, caId);
psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
psCert.setLong(idx++, cert.getUpdate());
psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
setInt(psCert, idx++, cert.getRev());
setInt(psCert, idx++, cert.getRr());
setLong(psCert, idx++, cert.getRt());
setLong(psCert, idx++, cert.getRit());
psCert.setString(idx++, certhash);
psCert.setString(idx++, subject);
psCert.setNull(idx, Types.INTEGER);
psCert.addBatch();
} catch (SQLException ex) {
throw translate(SQL_ADD_CERT, ex);
}
}
// end if (caIds.contains(caId))
}
// end if (revokedOnly
boolean isLastBlock = i == n - 1;
if (numImportedEntriesInBatch > 0 && (numImportedEntriesInBatch % this.numCertsPerCommit == 0 || isLastBlock)) {
try {
psCert.executeBatch();
commit("(commit import cert to OCSP)");
} catch (Throwable th) {
rollback();
deleteCertGreatherThan(lastSuccessfulCertId, LOG);
if (th instanceof SQLException) {
throw translate(SQL_ADD_CERT, (SQLException) th);
} else if (th instanceof Exception) {
throw (Exception) th;
} else {
throw new Exception(th);
}
}
lastSuccessfulCertId = id;
processLog.addNumProcessed(numProcessedEntriesInBatch);
importLog.addNumProcessed(numImportedEntriesInBatch);
numProcessedEntriesInBatch = 0;
numImportedEntriesInBatch = 0;
String filename = (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulCertId;
echoToFile(filename, processLogFile);
processLog.printStatus();
} else if (isLastBlock) {
lastSuccessfulCertId = id;
processLog.addNumProcessed(numProcessedEntriesInBatch);
importLog.addNumProcessed(numImportedEntriesInBatch);
numProcessedEntriesInBatch = 0;
numImportedEntriesInBatch = 0;
String filename = (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulCertId;
echoToFile(filename, processLogFile);
processLog.printStatus();
}
// if (numImportedEntriesInBatch)
}
return lastSuccessfulCertId;
} finally {
recoverAutoCommit();
zipFile.close();
}
}
Aggregations