use of org.bouncycastle.asn1.x509.Time in project fdroidclient by f-droid.
the class LocalRepoKeyStore method generateSelfSignedCertChain.
private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname) throws CertificateException, OperatorCreationException, IOException {
SecureRandom rand = new SecureRandom();
PrivateKey privKey = kp.getPrivate();
PublicKey pubKey = kp.getPublic();
ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);
SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(pubKey.getEncoded()));
// now
Date now = new Date();
/* force it to use a English/Gregorian dates for the cert, hardly anyone
ever looks at the cert metadata anyway, and its very likely that they
understand English/Gregorian dates */
Calendar c = new GregorianCalendar(Locale.ENGLISH);
c.setTime(now);
c.add(Calendar.YEAR, 1);
Time startTime = new Time(now, Locale.ENGLISH);
Time endTime = new Time(c.getTime(), Locale.ENGLISH);
X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(subject, BigInteger.valueOf(rand.nextLong()), startTime, endTime, subject, subPubKeyInfo);
if (hostname != null) {
GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.iPAddress, hostname));
v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
}
X509CertificateHolder certHolder = v3CertGen.build(sigGen);
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
use of org.bouncycastle.asn1.x509.Time in project azure-iot-sdk-java by Azure.
the class X509CertificateGenerator method createX509CertificateFromKeyPair.
/**
* Create a new self signed x509 certificate with the specified common name
*/
private static X509Certificate createX509CertificateFromKeyPair(KeyPair keyPair, String commonName) throws OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
StringBuilder issuerStringBuilder = new StringBuilder(ISSUER_STRING);
if (commonName != null && !commonName.isEmpty()) {
issuerStringBuilder.append(", CN=").append(commonName);
}
X500Name issuer = new X500Name(issuerStringBuilder.toString());
BigInteger serial = BigInteger.ONE;
// valid from 24 hours earlier as well, to avoid clock skew issues with start time
Date notBefore = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(24));
// 2 hour lifetime
Date notAfter = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(2));
X500Name subject = new X500Name(issuerStringBuilder.toString());
PublicKey publicKey = keyPair.getPublic();
JcaX509v3CertificateBuilder v3Bldr = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKey);
X509CertificateHolder certHldr = v3Bldr.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(keyPair.getPrivate()));
X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHldr);
cert.checkValidity(new Date());
cert.verify(keyPair.getPublic());
return cert;
}
use of org.bouncycastle.asn1.x509.Time in project Spark by igniterealtime.
the class SparkTrustManager method validatePath.
/**
* Validate certificate path
*
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws InvalidAlgorithmParameterException
* @throws CertPathValidatorException
* @throws CertPathBuilderException
* @throws CertificateException
*/
private void validatePath(X509Certificate[] chain) throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException, CertPathBuilderException, CertificateException {
// PKIX algorithm is defined in rfc3280
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
X509CertSelector certSelector = new X509CertSelector();
// set last certificate (often root CA) from chain for CertSelector so trust store must contain it
certSelector.setCertificate(chain[chain.length - 1]);
// checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[]
// chain)
certSelector.setCertificateValid(null);
// create parameters using trustStore as source of Trust Anchors and using X509CertSelector
PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
// will use PKIXRevocationChecker (or nothing if revocation mechanisms are
// disabled) instead of the default revocation checker
parameters.setRevocationEnabled(false);
// certificates from blacklist will be rejected
if (acceptRevoked == false) {
// OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8:
// https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker
PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class);
// is enabled then in case of network issues revocation checking is omitted
if (allowSoftFail) {
checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL);
}
// check OCSP, CRL serve as backup
if (checkOCSP && checkCRL) {
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
} else if (!checkOCSP && checkCRL) {
// check only CRL, if CRL fail then there is no fallback to OCSP
checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS);
checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK);
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
}
}
try {
CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
CertPath certPath = pathResult.getCertPath();
PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPath, parameters);
X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();
if (trustedCert == null) {
throw new CertificateException("certificate path failed: Trusted CA is NULL");
}
// this extension is last certificate: root CA
for (int i = 0; i < chain.length - 1; i++) {
checkBasicConstraints(chain[i]);
}
} catch (CertificateRevokedException e) {
Log.warning("Certificate was revoked", e);
for (X509Certificate cert : chain) {
for (X509CRL crl : crlCollection) {
if (crl.isRevoked(cert)) {
try {
addToBlackList(cert);
} catch (IOException | HeadlessException | InvalidNameException e1) {
Log.error("Couldn't move to the blacklist", e1);
}
break;
}
}
}
throw new CertificateException("Certificate was revoked");
}
}
use of org.bouncycastle.asn1.x509.Time in project xipki by xipki.
the class ImportCrl method addCertificate.
private void addCertificate(AtomicLong maxId, int caId, Certificate cert, String profileName, String certLogId) throws DataAccessException, ImportCrlException {
// not issued by the given issuer
if (!caSubject.equals(cert.getIssuer())) {
LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
return;
}
// we don't use the binary read from file, since it may contains redundant ending bytes.
byte[] encodedCert;
try {
encodedCert = cert.getEncoded();
} catch (IOException ex) {
throw new ImportCrlException("could not encode certificate {}" + certLogId, ex);
}
String b64CertHash = certhashAlgo.base64Hash(encodedCert);
if (caSpki != null) {
byte[] aki = null;
try {
aki = X509Util.extractAki(cert);
} catch (CertificateEncodingException ex) {
LogUtil.error(LOG, ex, "invalid AuthorityKeyIdentifier of certificate {}" + certLogId + ", ignore it");
return;
}
if (aki == null || !Arrays.equals(caSpki, aki)) {
LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
return;
}
}
// end if
LOG.info("Importing certificate {}", certLogId);
Long id = getId(caId, cert.getSerialNumber().getPositiveValue());
boolean tblCertIdExists = (id != null);
PreparedStatement ps;
String sql;
// first update the table CERT
if (tblCertIdExists) {
sql = SQL_UPDATE_CERT;
ps = psUpdateCert;
} else {
sql = SQL_INSERT_CERT;
ps = psInsertCert;
id = maxId.incrementAndGet();
}
try {
int offset = 1;
if (sql == SQL_INSERT_CERT) {
ps.setLong(offset++, id);
// ISSUER ID IID
ps.setInt(offset++, caId);
// serial number SN
ps.setString(offset++, cert.getSerialNumber().getPositiveValue().toString(16));
// whether revoked REV
ps.setInt(offset++, 0);
// revocation reason RR
ps.setNull(offset++, Types.SMALLINT);
// revocation time RT
ps.setNull(offset++, Types.BIGINT);
ps.setNull(offset++, Types.BIGINT);
}
// last update LUPDATE
ps.setLong(offset++, System.currentTimeMillis() / 1000);
TBSCertificate tbsCert = cert.getTBSCertificate();
// not before NBEFORE
ps.setLong(offset++, tbsCert.getStartDate().getDate().getTime() / 1000);
// not after NAFTER
ps.setLong(offset++, tbsCert.getEndDate().getDate().getTime() / 1000);
// profile name PN
if (StringUtil.isBlank(profileName)) {
ps.setNull(offset++, Types.VARCHAR);
} else {
ps.setString(offset++, profileName);
}
ps.setString(offset++, b64CertHash);
if (sql == SQL_UPDATE_CERT) {
ps.setLong(offset++, id);
}
ps.executeUpdate();
} catch (SQLException ex) {
throw datasource.translate(sql, ex);
}
// it is not required to add entry to table CRAW
LOG.info("Imported certificate {}", certLogId);
}
use of org.bouncycastle.asn1.x509.Time in project xipki by xipki.
the class ImportCrl method deleteEntriesNotUpdatedSince.
private void deleteEntriesNotUpdatedSince(Connection conn, Date time) throws DataAccessException {
// remove the unmodified entries
String sql = "DELETE FROM CERT WHERE LUPDATE<" + time.getTime() / 1000;
Statement stmt = datasource.createStatement(conn);
try {
stmt.executeUpdate(sql);
} catch (SQLException ex) {
throw datasource.translate(sql, ex);
} finally {
releaseResources(stmt, null);
}
}
Aggregations