Search in sources :

Example 66 with Time

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);
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.spongycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ContentSigner(org.spongycastle.operator.ContentSigner) GregorianCalendar(java.util.GregorianCalendar) SecureRandom(java.security.SecureRandom) Time(org.spongycastle.asn1.x509.Time) SubjectPublicKeyInfo(org.spongycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralNames(org.spongycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.spongycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.spongycastle.cert.X509CertificateHolder) GeneralName(org.spongycastle.asn1.x509.GeneralName)

Example 67 with Time

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;
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 68 with Time

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");
    }
}
Also used : X509CRL(java.security.cert.X509CRL) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CertificateRevokedException(java.security.cert.CertificateRevokedException) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) X509CertSelector(java.security.cert.X509CertSelector) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) CertPathValidator(java.security.cert.CertPathValidator) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) PKIXRevocationChecker(java.security.cert.PKIXRevocationChecker) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath)

Example 69 with Time

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);
}
Also used : SQLException(java.sql.SQLException) AtomicLong(java.util.concurrent.atomic.AtomicLong) CertificateEncodingException(java.security.cert.CertificateEncodingException) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 70 with Time

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);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String)

Aggregations

Time (com.android.calendarcommon2.Time)178 IOException (java.io.IOException)50 Date (java.util.Date)43 X509Certificate (java.security.cert.X509Certificate)37 BigInteger (java.math.BigInteger)32 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)32 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)32 X500Name (org.bouncycastle.asn1.x500.X500Name)28 DEROctetString (org.bouncycastle.asn1.DEROctetString)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)26 ArrayList (java.util.ArrayList)25 Paint (android.graphics.Paint)20 DERSequence (org.bouncycastle.asn1.DERSequence)17 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 ByteArrayInputStream (java.io.ByteArrayInputStream)15 CertificateException (java.security.cert.CertificateException)15 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)15 Time (org.bouncycastle.asn1.x509.Time)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 SecureRandom (java.security.SecureRandom)14