Search in sources :

Example 66 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xipki by xipki.

the class X509Util method parseCert.

public static X509Certificate parseCert(InputStream certStream) throws CertificateException {
    ParamUtil.requireNonNull("certStream", certStream);
    X509Certificate cert = (X509Certificate) getCertFactory().generateCertificate(certStream);
    if (cert == null) {
        throw new CertificateEncodingException("the given one is not a valid X.509 certificate");
    }
    return cert;
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate)

Example 67 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xipki by xipki.

the class X509Util method extractSki.

public static byte[] extractSki(org.bouncycastle.asn1.x509.Certificate cert) throws CertificateEncodingException {
    ParamUtil.requireNonNull("cert", cert);
    Extension encodedSkiValue = cert.getTBSCertificate().getExtensions().getExtension(Extension.subjectKeyIdentifier);
    if (encodedSkiValue == null) {
        return null;
    }
    try {
        return ASN1OctetString.getInstance(encodedSkiValue.getParsedValue()).getOctets();
    } catch (IllegalArgumentException ex) {
        throw new CertificateEncodingException("invalid extension SubjectKeyIdentifier: " + ex.getMessage());
    }
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 68 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException 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 69 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xipki by xipki.

the class ImportCrl method importCa.

private int importCa(Connection conn) throws DataAccessException, ImportCrlException {
    byte[] encodedCaCert;
    try {
        encodedCaCert = caCert.getEncoded();
    } catch (CertificateEncodingException ex) {
        throw new ImportCrlException("could not encode CA certificate");
    }
    String fpCaCert = HashAlgo.SHA1.base64Hash(encodedCaCert);
    Integer issuerId = null;
    CrlInfo crlInfo = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = null;
    try {
        sql = "SELECT ID,CRL_INFO FROM ISSUER WHERE S1C=?";
        ps = datasource.prepareStatement(conn, sql);
        ps.setString(1, fpCaCert);
        rs = ps.executeQuery();
        if (rs.next()) {
            issuerId = rs.getInt("ID");
            String str = rs.getString("CRL_INFO");
            if (str == null) {
                throw new ImportCrlException("RequestIssuer for the given CA of CRL exists, but not imported from CRL");
            }
            crlInfo = new CrlInfo(str);
        }
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseResources(ps, rs);
    }
    boolean addNew = (issuerId == null);
    if (addNew) {
        if (isDeltaCrl) {
            throw new ImportCrlException("Given CRL is a deltaCRL for the full CRL with number " + baseCrlNumber + ", please import this full CRL first.");
        } else {
            crlInfo = new CrlInfo(crlNumber, null, useCrlUpdates, crl.getThisUpdate(), crl.getNextUpdate(), crlId);
        }
    } else {
        if (crlNumber.compareTo(crlInfo.getCrlNumber()) < 0) {
            // which enables the resume of importing process if error occurred.
            throw new ImportCrlException("Given CRL is not newer than existing CRL.");
        }
        if (isDeltaCrl) {
            BigInteger lastFullCrlNumber = crlInfo.getBaseCrlNumber();
            if (lastFullCrlNumber == null) {
                lastFullCrlNumber = crlInfo.getCrlNumber();
            }
            if (!baseCrlNumber.equals(lastFullCrlNumber)) {
                throw new ImportCrlException("Given CRL is a deltaCRL for the full CRL with number " + crlNumber + ", please import this full CRL first.");
            }
        }
        crlInfo.setCrlNumber(crlNumber);
        crlInfo.setBaseCrlNumber(isDeltaCrl ? baseCrlNumber : null);
        crlInfo.setThisUpdate(crl.getThisUpdate());
        crlInfo.setNextUpdate(crl.getNextUpdate());
    }
    ps = null;
    rs = null;
    sql = null;
    try {
        // issuer exists
        if (addNew) {
            int maxId = (int) datasource.getMax(conn, "ISSUER", "ID");
            issuerId = maxId + 1;
            sql = "INSERT INTO ISSUER (ID,SUBJECT,NBEFORE,NAFTER,S1C,CERT,REV,RT,RIT,CRL_INFO)" + " VALUES(?,?,?,?,?,?,?,?,?,?)";
        } else {
            sql = "UPDATE ISSUER SET REV=?,RT=?,RIT=?,CRL_INFO=? WHERE ID=?";
        }
        ps = datasource.prepareStatement(conn, sql);
        int offset = 1;
        if (addNew) {
            String subject = X509Util.getRfc4519Name(caCert.getSubjectX500Principal());
            ps.setInt(offset++, issuerId);
            ps.setString(offset++, subject);
            ps.setLong(offset++, caCert.getNotBefore().getTime() / 1000);
            ps.setLong(offset++, caCert.getNotAfter().getTime() / 1000);
            ps.setString(offset++, fpCaCert);
            ps.setString(offset++, Base64.encodeToString(encodedCaCert));
        }
        ps.setInt(offset++, (caRevInfo == null) ? 0 : 1);
        Date revTime = null;
        Date revInvTime = null;
        if (caRevInfo != null) {
            revTime = caRevInfo.getRevocationTime();
            revInvTime = caRevInfo.getInvalidityTime();
        }
        if (revTime != null) {
            ps.setLong(offset++, revTime.getTime() / 1000);
        } else {
            ps.setNull(offset++, Types.BIGINT);
        }
        if (revInvTime != null) {
            ps.setLong(offset++, revInvTime.getTime() / 1000);
        } else {
            ps.setNull(offset++, Types.BIGINT);
        }
        // CRL info
        try {
            ps.setString(offset++, crlInfo.getEncoded());
        } catch (IOException ex) {
            throw new ImportCrlException("could not encode the Crlinfo", ex);
        }
        if (!addNew) {
            ps.setInt(offset++, issuerId.intValue());
        }
        ps.executeUpdate();
        return issuerId.intValue();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseResources(ps, rs);
    }
}
Also used : SQLException(java.sql.SQLException) CertificateEncodingException(java.security.cert.CertificateEncodingException) PreparedStatement(java.sql.PreparedStatement) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) Date(java.util.Date) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) CrlInfo(org.xipki.ocsp.api.CrlInfo) ResultSet(java.sql.ResultSet) BigInteger(java.math.BigInteger)

Example 70 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xipki by xipki.

the class IssuerEntry method getIssuerHashAndKeys.

private static Map<HashAlgo, byte[]> getIssuerHashAndKeys(byte[] encodedCert) throws CertificateEncodingException {
    byte[] encodedName;
    byte[] encodedKey;
    try {
        Certificate bcCert = Certificate.getInstance(encodedCert);
        encodedName = bcCert.getSubject().getEncoded("DER");
        encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    } catch (IllegalArgumentException | IOException ex) {
        throw new CertificateEncodingException(ex.getMessage(), ex);
    }
    Map<HashAlgo, byte[]> hashes = new HashMap<>();
    for (HashAlgo ha : HashAlgo.values()) {
        int hlen = ha.getLength();
        byte[] nameAndKeyHash = new byte[(2 + hlen) << 1];
        int offset = 0;
        nameAndKeyHash[offset++] = 0x04;
        nameAndKeyHash[offset++] = (byte) hlen;
        System.arraycopy(ha.hash(encodedName), 0, nameAndKeyHash, offset, hlen);
        offset += hlen;
        nameAndKeyHash[offset++] = 0x04;
        nameAndKeyHash[offset++] = (byte) hlen;
        System.arraycopy(ha.hash(encodedKey), 0, nameAndKeyHash, offset, hlen);
        offset += hlen;
        hashes.put(ha, nameAndKeyHash);
    }
    return hashes;
}
Also used : HashMap(java.util.HashMap) HashAlgo(org.xipki.security.HashAlgo) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Aggregations

CertificateEncodingException (java.security.cert.CertificateEncodingException)210 X509Certificate (java.security.cert.X509Certificate)94 IOException (java.io.IOException)76 Certificate (java.security.cert.Certificate)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)27 KeyStoreException (java.security.KeyStoreException)19 MessageDigest (java.security.MessageDigest)19 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)16 CertificateException (java.security.cert.CertificateException)14 BigInteger (java.math.BigInteger)11 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 Bundle (android.os.Bundle)9 PublicKey (java.security.PublicKey)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 File (java.io.File)8 PrivateKey (java.security.PrivateKey)8 DEROctetString (org.bouncycastle.asn1.DEROctetString)8