Example usage for org.bouncycastle.asn1.x509 Certificate getInstance

List of usage examples for org.bouncycastle.asn1.x509 Certificate getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Certificate getInstance.

Prototype

public static Certificate getInstance(Object obj) 

Source Link

Usage

From source file:org.xipki.ca.qa.api.X509IssuerInfo.java

License:Open Source License

public X509IssuerInfo(final List<String> caIssuerURLs, final List<String> ocspURLs, final List<String> crlURLs,
        final List<String> deltaCrlURLs, final byte[] certBytes) throws CertificateException {
    ParamChecker.assertNotNull("certBytes", certBytes);

    if (CollectionUtil.isEmpty(caIssuerURLs)) {
        this.caIssuerURLs = null;
    } else {/*from   w w w  . j  a v  a2s .co m*/
        Set<String> set = new HashSet<>();
        set.addAll(caIssuerURLs);
        this.caIssuerURLs = Collections.unmodifiableSet(set);
    }

    if (CollectionUtil.isEmpty(ocspURLs)) {
        this.ocspURLs = null;
    } else {
        Set<String> set = new HashSet<>();
        set.addAll(ocspURLs);
        this.ocspURLs = Collections.unmodifiableSet(set);
    }

    if (CollectionUtil.isEmpty(crlURLs)) {
        this.crlURLs = null;
    } else {
        Set<String> set = new HashSet<>();
        set.addAll(crlURLs);
        this.crlURLs = Collections.unmodifiableSet(set);
    }

    if (CollectionUtil.isEmpty(deltaCrlURLs)) {
        this.deltaCrlURLs = null;
    } else {
        Set<String> set = new HashSet<>();
        set.addAll(deltaCrlURLs);
        this.deltaCrlURLs = Collections.unmodifiableSet(set);
    }

    try {
        this.cert = X509Util.parseCert(certBytes);
    } catch (IOException e) {
        throw new CertificateException(e.getMessage(), e);
    }
    this.bcCert = Certificate.getInstance(certBytes);
    this.ski = X509Util.extractSKI(cert);
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

@Override
public ValidationResult checkCert(final byte[] certBytes, final X509IssuerInfo issuerInfo,
        final X500Name requestedSubject, final SubjectPublicKeyInfo requestedPublicKey,
        final Extensions requestedExtensions) {
    ParamChecker.assertNotNull("certBytes", certBytes);
    ParamChecker.assertNotNull("issuerInfo", issuerInfo);
    ParamChecker.assertNotNull("requestedSubject", requestedSubject);
    ParamChecker.assertNotNull("requestedPublicKey", requestedPublicKey);

    List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();

    Certificate bcCert;//from   w  ww  .j a va2s .  c o m
    X509Certificate cert;

    // certificate encoding
    {
        ValidationIssue issue = new ValidationIssue("X509.ENCODING", "certificate encoding");
        resultIssues.add(issue);
        try {
            bcCert = Certificate.getInstance(certBytes);
            cert = X509Util.parseCert(certBytes);
        } catch (CertificateException | IOException e) {
            issue.setFailureMessage("certificate is not corrected encoded");
            return new ValidationResult(resultIssues);
        }
    }

    // syntax version
    {
        ValidationIssue issue = new ValidationIssue("X509.VERSION", "certificate version");
        resultIssues.add(issue);
        int versionNumber = cert.getVersion();
        if (versionNumber != version.getVersion()) {
            issue.setFailureMessage("is '" + versionNumber + "' but expected '" + version.getVersion() + "'");
        }
    }

    // signatureAlgorithm
    if (CollectionUtil.isNotEmpty(signatureAlgorithms)) {
        ValidationIssue issue = new ValidationIssue("X509.SIGALG", "signature algorithm");
        resultIssues.add(issue);

        AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm();
        AlgorithmIdentifier tbsSigAlgId = bcCert.getTBSCertificate().getSignature();
        if (tbsSigAlgId.equals(sigAlgId) == false) {
            issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm");
        } else {
            try {
                String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId);
                if (signatureAlgorithms.contains(sigAlgo) == false) {
                    issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed");
                }
            } catch (NoSuchAlgorithmException e) {
                issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId());
            }
        }
    }

    // notBefore
    if (notBeforeMidnight) {
        ValidationIssue issue = new ValidationIssue("X509.NOTBEFORE", "not before midnight");
        resultIssues.add(issue);
        Calendar c = Calendar.getInstance(UTC);
        c.setTime(cert.getNotBefore());
        int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);

        if (hourOfDay != 0 || minute != 0 || second != 0) {
            issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)");
        }
    }

    // validity
    {
        ValidationIssue issue = new ValidationIssue("X509.VALIDITY", "cert validity");
        resultIssues.add(issue);

        Date expectedNotAfter = validity.add(cert.getNotBefore());
        if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) {
            issue.setFailureMessage("cert validity is not within " + validity.toString());
        }
    }

    // public key
    {
        SubjectPublicKeyInfo publicKey = bcCert.getSubjectPublicKeyInfo();
        if (keyAlgorithms != null) {
            ValidationIssue issue = new ValidationIssue("X509.PUBKEY.SYN", "whether public key is permitted");
            resultIssues.add(issue);
            try {
                checkPublicKey(publicKey);
            } catch (BadCertTemplateException e) {
                issue.setFailureMessage(e.getMessage());
            }
        }

        ValidationIssue issue = new ValidationIssue("X509.PUBKEY.REQ",
                "whether public key matches the request one");
        resultIssues.add(issue);
        SubjectPublicKeyInfo c14nRequestedPublicKey;
        try {
            c14nRequestedPublicKey = X509Util.toRfc3279Style(requestedPublicKey);
            if (c14nRequestedPublicKey.equals(publicKey) == false) {
                issue.setFailureMessage("public key in the certificate does not equal the requested one");
            }
        } catch (InvalidKeySpecException e) {
            issue.setFailureMessage("public key in request is invalid");
        }
    }

    // Signature
    {
        ValidationIssue issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA");
        resultIssues.add(issue);
        try {
            cert.verify(issuerInfo.getCert().getPublicKey(), "BC");
        } catch (Exception e) {
            issue.setFailureMessage("invalid signature");
        }
    }

    // issuer
    {
        ValidationIssue issue = new ValidationIssue("X509.ISSUER", "certificate issuer");
        resultIssues.add(issue);
        if (cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal()) == false) {
            issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate");
        }
    }

    // subject
    X500Name subject = bcCert.getTBSCertificate().getSubject();
    resultIssues.addAll(checkSubject(subject, requestedSubject));

    // extensions
    resultIssues.addAll(checkExtensions(bcCert, cert, issuerInfo, requestedExtensions));

    return new ValidationResult(resultIssues);
}

From source file:org.xipki.ca.server.impl.publisher.OCSPStoreQueryExecutor.java

License:Open Source License

void addIssuer(final X509CertWithDBCertId issuerCert) throws CertificateEncodingException, DataAccessException {
    if (issuerStore.getIdForCert(issuerCert.getEncodedCert()) != null) {
        return;//w w w  .j a v a2s  . c  om
    }

    String hexSha1FpCert = HashCalculator.hexHash(HashAlgoType.SHA1, issuerCert.getEncodedCert());

    Certificate bcCert = Certificate.getInstance(issuerCert.getEncodedCert());
    byte[] encodedName;
    try {
        encodedName = bcCert.getSubject().getEncoded("DER");
    } catch (IOException e) {
        throw new CertificateEncodingException(e.getMessage(), e);
    }
    byte[] encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

    long maxId = dataSource.getMax(null, "ISSUER", "ID");
    int id = (int) maxId + 1;

    final String sql = "INSERT INTO ISSUER (ID, SUBJECT, NOTBEFORE, NOTAFTER,"
            + " SHA1_NAME, SHA1_KEY, SHA224_NAME, SHA224_KEY, SHA256_NAME, SHA256_KEY,"
            + " SHA384_NAME, SHA384_KEY, SHA512_NAME, SHA512_KEY,SHA1_CERT, CERT)"
            + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement ps = borrowPreparedStatement(sql);

    try {
        String b64Cert = Base64.toBase64String(issuerCert.getEncodedCert());
        String subject = issuerCert.getSubject();
        int idx = 1;
        ps.setInt(idx++, id);
        ps.setString(idx++, subject);
        ps.setLong(idx++, issuerCert.getCert().getNotBefore().getTime() / 1000);
        ps.setLong(idx++, issuerCert.getCert().getNotAfter().getTime() / 1000);
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedName));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedName));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedKey));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedName));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedKey));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedName));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedKey));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedName));
        ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedKey));
        ps.setString(idx++, hexSha1FpCert);
        ps.setString(idx++, b64Cert);

        ps.execute();

        IssuerEntry newInfo = new IssuerEntry(id, subject, hexSha1FpCert, b64Cert);
        issuerStore.addIdentityEntry(newInfo);
    } catch (SQLException e) {
        throw dataSource.translate(sql, e);
    } finally {
        releaseDbResources(ps, null);
    }
}

From source file:org.xipki.ca.server.impl.store.CertStoreQueryExecutor.java

License:Open Source License

X509CertificateInfo getCertificateInfo(final X509CertWithDBCertId caCert, final BigInteger serial)
        throws DataAccessException, OperationException, CertificateException {
    ParamChecker.assertNotNull("caCert", caCert);
    ParamChecker.assertNotNull("serial", serial);

    Integer caId = getCaId(caCert);
    if (caId == null) {
        return null;
    }/*from ww w. j a v a2s  .  c om*/

    StringBuilder m = new StringBuilder(200);
    m.append("T1.PROFILE_ID PROFILE_ID, T1.REVOKED REVOKED, T1.REV_REASON REV_REASON,");
    m.append("T1.REV_TIME REV_TIME, T1.REV_INV_TIME REV_INV_TIME, T2.CERT CERT");
    m.append(" FROM CERT T1, RAWCERT T2");
    m.append(" WHERE T1.CA_ID=? AND T1.SERIAL=? AND T2.CERT_ID=T1.ID");

    final String sql = dataSource.createFetchFirstSelectSQL(m.toString(), 1);
    ResultSet rs = null;
    PreparedStatement ps = borrowPreparedStatement(sql);

    try {
        int idx = 1;
        ps.setInt(idx++, caId.intValue());
        ps.setLong(idx++, serial.longValue());
        rs = ps.executeQuery();

        if (rs.next()) {
            String b64Cert = rs.getString("CERT");
            byte[] encodedCert = Base64.decode(b64Cert);
            X509Certificate cert = X509Util.parseCert(encodedCert);

            int certprofile_id = rs.getInt("PROFILE_ID");
            String certprofileName = certprofileStore.getName(certprofile_id);

            X509CertWithDBCertId certWithMeta = new X509CertWithDBCertId(cert, encodedCert);

            byte[] subjectPublicKeyInfo = Certificate.getInstance(encodedCert).getTBSCertificate()
                    .getSubjectPublicKeyInfo().getEncoded();
            X509CertificateInfo certInfo = new X509CertificateInfo(certWithMeta, caCert, subjectPublicKeyInfo,
                    certprofileName);

            boolean revoked = rs.getBoolean("REVOKED");
            if (revoked == false) {
                return certInfo;
            }

            int rev_reasonCode = rs.getInt("REV_REASON");
            CRLReason rev_reason = CRLReason.forReasonCode(rev_reasonCode);
            long rev_time = rs.getLong("REV_TIME");
            long invalidity_time = rs.getLong("REV_INV_TIME");

            Date invalidityTime = invalidity_time == 0 ? null : new Date(invalidity_time * 1000);
            CertRevocationInfo revInfo = new CertRevocationInfo(rev_reason, new Date(rev_time * 1000),
                    invalidityTime);
            certInfo.setRevocationInfo(revInfo);
            return certInfo;
        }
    } catch (IOException e) {
        LOG.warn("getCertificateInfo()", e);
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "IOException: " + e.getMessage());
    } catch (SQLException e) {
        throw dataSource.translate(sql, e);
    } finally {
        releaseDbResources(ps, rs);
    }

    return null;
}

From source file:org.xipki.ca.server.impl.X509CA.java

License:Open Source License

private X509CRL generateCRL(final boolean deltaCRL, final Date thisUpdate, final Date nextUpdate,
        final AuditEvent auditEvent) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "CRL generation is not allowed");
    }//from  w  w w  .j  a  v a  2  s  .  c  om

    LOG.info("     START generateCRL: ca={}, deltaCRL={}, nextUpdate={}",
            new Object[] { caInfo.getName(), deltaCRL, nextUpdate });

    if (auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("crlType", deltaCRL ? "DELTA_CRL" : "FULL_CRL"));
        if (nextUpdate != null) {
            String value;
            synchronized (dateFormat) {
                value = dateFormat.format(nextUpdate);
            }
            auditEvent.addEventData(new AuditEventData("nextUpdate", value));
        } else {
            auditEvent.addEventData(new AuditEventData("nextUpdate", "NULL"));
        }
    }

    if (nextUpdate != null) {
        if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
            // less than 10 minutes
            throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
        }
    }

    CRLControl crlControl = crlSigner.getCRLControl();
    boolean successfull = false;

    try {
        ConcurrentContentSigner _crlSigner = crlSigner.getSigner();

        CRLControl control = crlSigner.getCRLControl();

        boolean directCRL = _crlSigner == null;
        X500Name crlIssuer = directCRL ? caInfo.getPublicCAInfo().getX500Subject()
                : X500Name.getInstance(_crlSigner.getCertificate().getSubjectX500Principal().getEncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
        if (nextUpdate != null) {
            crlBuilder.setNextUpdate(nextUpdate);
        }

        BigInteger startSerial = BigInteger.ONE;
        final int numEntries = 100;

        X509CertWithDBCertId caCert = caInfo.getCertificate();
        List<CertRevInfoWithSerial> revInfos;
        boolean isFirstCRLEntry = true;

        Date notExpireAt;
        if (control.isIncludeExpiredCerts()) {
            notExpireAt = new Date(0);
        } else {
            // 10 minutes buffer
            notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
        }

        do {
            if (deltaCRL) {
                revInfos = certstore.getCertificatesForDeltaCRL(caCert, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            } else {
                revInfos = certstore.getRevokedCertificates(caCert, notExpireAt, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            }

            BigInteger maxSerial = BigInteger.ONE;

            for (CertRevInfoWithSerial revInfo : revInfos) {
                BigInteger serial = revInfo.getSerial();
                if (serial.compareTo(maxSerial) > 0) {
                    maxSerial = serial;
                }

                CRLReason reason = revInfo.getReason();
                Date revocationTime = revInfo.getRevocationTime();
                Date invalidityTime = revInfo.getInvalidityTime();
                if (invalidityTime != null && invalidityTime.equals(revocationTime)) {
                    invalidityTime = null;
                }

                if (directCRL || isFirstCRLEntry == false) {
                    if (invalidityTime != null) {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode(),
                                invalidityTime);
                    } else {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode());
                    }
                    continue;
                }

                List<Extension> extensions = new ArrayList<>(3);
                if (reason != CRLReason.UNSPECIFIED) {
                    Extension ext = createReasonExtension(reason.getCode());
                    extensions.add(ext);
                }
                if (invalidityTime != null) {
                    Extension ext = createInvalidityDateExtension(invalidityTime);
                    extensions.add(ext);
                }

                Extension ext = createCertificateIssuerExtension(caInfo.getPublicCAInfo().getX500Subject());
                extensions.add(ext);

                Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
                crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, asn1Extensions);
                isFirstCRLEntry = false;
            } // end for

            startSerial = maxSerial.add(BigInteger.ONE);

        } while (revInfos.size() >= numEntries);
        // end do

        BigInteger crlNumber = caInfo.nextCRLNumber();
        if (auditEvent != null) {
            auditEvent.addEventData(new AuditEventData("crlNumber", crlNumber.toString()));
        }

        boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
        boolean onlyCACerts = crlControl.isOnlyContainsCACerts();
        if (onlyUserCerts && onlyCACerts) {
            throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
        }

        try {
            // AuthorityKeyIdentifier
            byte[] akiValues = directCRL ? caInfo.getPublicCAInfo().getSubjectKeyIdentifer()
                    : crlSigner.getSubjectKeyIdentifier();
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
            crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);

            // add extension CRL Number
            crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));

            // IssuingDistributionPoint
            if (onlyUserCerts == true || onlyCACerts == true || directCRL == false) {
                IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint,
                        onlyUserCerts, // onlyContainsUserCerts,
                        onlyCACerts, // onlyContainsCACerts,
                        (ReasonFlags) null, // onlySomeReasons,
                        directCRL == false, // indirectCRL,
                        false // onlyContainsAttributeCerts
                );

                crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
            }
        } catch (CertIOException e) {
            final String message = "crlBuilder.addExtension";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(message, e);
            throw new OperationException(ErrorCode.INVALID_EXTENSION, e.getMessage());
        }

        startSerial = BigInteger.ONE;
        if (deltaCRL == false && control.isEmbedsCerts()) // XiPKI extension
        {
            ASN1EncodableVector vector = new ASN1EncodableVector();

            List<BigInteger> serials;

            do {
                serials = certstore.getCertSerials(caCert, notExpireAt, startSerial, numEntries, false,
                        onlyCACerts, onlyUserCerts);

                BigInteger maxSerial = BigInteger.ONE;
                for (BigInteger serial : serials) {
                    if (serial.compareTo(maxSerial) > 0) {
                        maxSerial = serial;
                    }

                    X509CertificateInfo certInfo;
                    try {
                        certInfo = certstore.getCertificateInfoForSerial(caCert, serial);
                    } catch (CertificateException e) {
                        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                                "CertificateException: " + e.getMessage());
                    }

                    Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert());

                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(cert);
                    String profileName = certInfo.getProfileName();
                    if (StringUtil.isNotBlank(profileName)) {
                        v.add(new DERUTF8String(certInfo.getProfileName()));
                    }
                    ASN1Sequence certWithInfo = new DERSequence(v);

                    vector.add(certWithInfo);
                } // end for

                startSerial = maxSerial.add(BigInteger.ONE);
            } while (serials.size() >= numEntries);
            // end fo

            try {
                crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector));
            } catch (CertIOException e) {
                throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + e.getMessage());
            }
        }

        ConcurrentContentSigner concurrentSigner = (_crlSigner == null) ? caInfo.getSigner(null) : _crlSigner;

        ContentSigner contentSigner;
        try {
            contentSigner = concurrentSigner.borrowContentSigner();
        } catch (NoIdleSignerException e) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage());
        }

        X509CRLHolder crlHolder;
        try {
            crlHolder = crlBuilder.build(contentSigner);
        } finally {
            concurrentSigner.returnContentSigner(contentSigner);
        }

        try {
            X509CRL crl = new X509CRLObject(crlHolder.toASN1Structure());
            publishCRL(crl);

            successfull = true;
            LOG.info("SUCCESSFUL generateCRL: ca={}, crlNumber={}, thisUpdate={}",
                    new Object[] { caInfo.getName(), crlNumber, crl.getThisUpdate() });

            if (deltaCRL) {
                return crl;
            }

            // clean up the CRL
            try {
                cleanupCRLs();
            } catch (Throwable t) {
                LOG.warn("could not cleanup CRLs.{}: {}", t.getClass().getName(), t.getMessage());
            }
            return crl;
        } catch (CRLException e) {
            throw new OperationException(ErrorCode.CRL_FAILURE, "CRLException: " + e.getMessage());
        }
    } finally {
        if (successfull == false) {
            LOG.info("    FAILED generateCRL: ca={}", caInfo.getName());
        }
    }
}

From source file:org.xipki.ca.server.impl.X509CAInfo.java

License:Open Source License

public X509CAInfo(final X509CAEntry caEntry, final CertificateStore certStore) throws OperationException {
    ParamChecker.assertNotNull("caEntry", caEntry);
    ParamChecker.assertNotNull("certStore", certStore);
    this.caEntry = caEntry;
    this.certStore = certStore;

    X509Certificate cert = caEntry.getCertificate();
    this.notBefore = cert.getNotBefore();
    this.notAfter = cert.getNotAfter();
    this.serialNumber = cert.getSerialNumber();
    this.selfSigned = cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal());

    Certificate bcCert;//w ww.jav a  2  s.c o  m
    try {
        byte[] encodedCert = cert.getEncoded();
        bcCert = Certificate.getInstance(encodedCert);
    } catch (CertificateEncodingException e) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not encode the CA certificate");
    }
    this.certInCMPFormat = new CMPCertificate(bcCert);

    this.publicCAInfo = new PublicCAInfo(cert, caEntry.getCacertUris(), caEntry.getOcspUris(),
            caEntry.getCrlUris(), caEntry.getDeltaCrlUris());

    this.noNewCertificateAfter = this.notAfter.getTime() - MS_PER_DAY * caEntry.getExpirationPeriod();

    this.useRandomSerialNumber = caEntry.getNextSerial() < 1;
    if (this.useRandomSerialNumber) {
        randomSNGenerator = RandomSerialNumberGenerator.getInstance();
        return;
    }

    Long greatestSerialNumber = certStore.getGreatestSerialNumber(this.publicCAInfo.getCaCertificate());

    if (greatestSerialNumber == null) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                "could not retrieve the greatest serial number for ca " + caEntry.getName());
    }

    long nextSerial = greatestSerialNumber + 1;
    if (nextSerial < 2) {
        nextSerial = 2;
    }

    if (caEntry.getNextSerial() < nextSerial) {
        LOG.info("corrected the next_serial of {} from {} to {}",
                new Object[] { caEntry.getName(), caEntry.getNextSerial(), nextSerial });
        caEntry.setNextSerial(nextSerial);
        certStore.commitNextSerialIfLess(getName(), nextSerial);
    } else {
        nextSerial = caEntry.getNextSerial();
    }
}

From source file:org.xipki.ca.server.impl.X509SelfSignedCertBuilder.java

License:Open Source License

public static GenerateSelfSignedResult generateSelfSigned(final SecurityFactory securityFactory,
        final String signerType, final String signerConf, final IdentifiedX509Certprofile certprofile,
        final CertificationRequest p10Request, final long serialNumber, final List<String> cacertUris,
        final List<String> ocspUris, final List<String> crlUris, final List<String> deltaCrlUris)
        throws OperationException, ConfigurationException {
    if (securityFactory.verifyPOPO(p10Request) == false) {
        throw new ConfigurationException("could not validate POP for the pkcs#10 requst");
    }//from w w w.java2s  .  co  m

    if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) {
        CmpUtf8Pairs keyValues = new CmpUtf8Pairs(signerConf);
        String keystoreConf = keyValues.getValue("keystore");
        if (keystoreConf == null) {
            throw new ConfigurationException(
                    "required parameter 'keystore', for types PKCS12 and JKS, is not specified");
        }
    }

    ConcurrentContentSigner signer;
    try {
        List<String[]> signerConfs = CAManagerImpl.splitCASignerConfs(signerConf);
        List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms();

        String thisSignerConf = null;
        if (CollectionUtil.isEmpty(restrictedSigAlgos)) {
            thisSignerConf = signerConfs.get(0)[1];
        } else {
            for (String algo : restrictedSigAlgos) {
                for (String[] m : signerConfs) {
                    if (m[0].equals(algo)) {
                        thisSignerConf = m[1];
                        break;
                    }
                }

                if (thisSignerConf != null) {
                    break;
                }
            }
        }

        if (thisSignerConf == null) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                    "CA does not support any signature algorithm restricted by the cert profile");
        }

        signer = securityFactory.createSigner(signerType, thisSignerConf, (X509Certificate[]) null);
    } catch (SignerException e) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, e.getClass().getName() + ": " + e.getMessage());
    }

    // this certificate is the dummy one which can be considered only as public key container
    Certificate bcCert;
    try {
        bcCert = Certificate.getInstance(signer.getCertificate().getEncoded());
    } catch (Exception e) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                "could not reparse certificate: " + e.getMessage());
    }
    SubjectPublicKeyInfo publicKeyInfo = bcCert.getSubjectPublicKeyInfo();

    X509Certificate newCert = generateCertificate(signer, certprofile, p10Request, serialNumber, publicKeyInfo,
            cacertUris, ocspUris, crlUris, deltaCrlUris);

    return new GenerateSelfSignedResult(signerConf, newCert);
}

From source file:org.xipki.commons.remotep11.server.CmpResponder.java

License:Open Source License

private PKIMessage doProcessPkiMessage(final LocalP11CryptServicePool p11CryptServicePool,
        final String moduleName, final InfoTypeAndValue itv, final PKIHeader respHeader)
        throws BadAsn1ObjectException, P11TokenException, CertificateException, XiSecurityException,
        InvalidKeyException {/*ww  w .  j a  v a2s.  co  m*/
    ASN1Sequence seq = Asn1Util.getSequence(itv.getInfoValue());
    Asn1Util.requireRange(seq, 3, 3);
    int protocolVersion = Asn1Util.getInteger(seq.getObjectAt(0)).intValue();
    int action = Asn1Util.getInteger(seq.getObjectAt(1)).intValue();
    ASN1Encodable reqValue = seq.getObjectAt(2);

    P11CryptService p11CryptService = p11CryptServicePool.getP11CryptService(moduleName);
    ASN1Encodable respItvInfoValue = null;

    if (P11ProxyConstants.ACTION_addCert == action) {
        Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
        X509Certificate cert = X509Util.toX509Cert(asn1.getCertificate());
        slot.addCert(asn1.getEntityId().getObjectId().getObjectId(), cert);
    } else if (P11ProxyConstants.ACTION_genKeypair_DSA == action) {
        Asn1GenDSAKeypairParams asn1 = Asn1GenDSAKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateDSAKeypair(asn1.getP(), asn1.getQ(), asn1.getG(),
                asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_genKeypair_EC == action) {
        Asn1GenECKeypairParams asn1 = Asn1GenECKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateECKeypair(asn1.getCurveId().getId(), asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_genKeypair_RSA == action) {
        Asn1GenRSAKeypairParams asn1 = Asn1GenRSAKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateRSAKeypair(asn1.getKeysize(), asn1.getPublicExponent(),
                asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_getCertificate == action) {
        P11EntityIdentifier entityId = Asn1P11EntityIdentifier.getInstance(reqValue).getEntityId();
        X509Certificate cert = p11CryptService.getIdentity(entityId).getCertificate();
        respItvInfoValue = Certificate.getInstance(cert.getEncoded());
    } else if (P11ProxyConstants.ACTION_getCertIdentifiers == action
            || P11ProxyConstants.ACTION_getIdentityIdentifiers == action) {
        Asn1P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(reqValue);
        P11Slot slot = p11CryptService.getModule().getSlot(slotId.getSlotId());
        Set<P11ObjectIdentifier> objectIds;
        if (P11ProxyConstants.ACTION_getCertIdentifiers == action) {
            objectIds = slot.getCertIdentifiers();
        } else {
            objectIds = slot.getIdentityIdentifiers();
        }
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (P11ObjectIdentifier objectId : objectIds) {
            vec.add(new Asn1P11ObjectIdentifier(objectId));
        }
        respItvInfoValue = new DERSequence(vec);
    } else if (P11ProxyConstants.ACTION_getMechanisms == action) {
        P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(reqValue).getSlotId();
        Set<Long> mechs = p11CryptService.getSlot(slotId).getMechanisms();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (Long mech : mechs) {
            vec.add(new ASN1Integer(mech));
        }
        respItvInfoValue = new DERSequence(vec);
    } else if (P11ProxyConstants.ACTION_getPublicKey == action) {
        P11EntityIdentifier identityId = Asn1P11EntityIdentifier.getInstance(reqValue).getEntityId();
        PublicKey pubKey = p11CryptService.getIdentity(identityId).getPublicKey();
        if (pubKey == null) {
            throw new P11UnknownEntityException(identityId);
        }

        respItvInfoValue = KeyUtil.createSubjectPublicKeyInfo(pubKey);
    } else if (P11ProxyConstants.ACTION_getSlotIds == action) {
        List<P11SlotIdentifier> slotIds = p11CryptService.getModule().getSlotIdentifiers();

        ASN1EncodableVector vector = new ASN1EncodableVector();
        for (P11SlotIdentifier slotId : slotIds) {
            vector.add(new Asn1P11SlotIdentifier(slotId));
        }
        respItvInfoValue = new DERSequence(vector);
    } else if (P11ProxyConstants.ACTION_removeCerts == action) {
        Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1);
        slot.removeCerts(asn1.getObjectId().getObjectId());
    } else if (P11ProxyConstants.ACTION_removeIdentity == action) {
        Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1);
        slot.removeIdentity(asn1.getObjectId().getObjectId());
    } else if (P11ProxyConstants.ACTION_sign == action) {
        Asn1SignTemplate signTemplate = Asn1SignTemplate.getInstance(reqValue);
        long mechanism = signTemplate.getMechanism().getMechanism();
        Asn1P11Params tmpParams = signTemplate.getMechanism().getParams();
        ASN1Encodable asn1Params = null;
        if (tmpParams != null) {
            asn1Params = tmpParams.getP11Params();
        }
        P11Params params = null;
        if (asn1Params instanceof Asn1RSAPkcsPssParams) {
            params = Asn1RSAPkcsPssParams.getInstance(asn1Params).getPkcsPssParams();
        } else if (asn1Params != null) {
            throw new BadAsn1ObjectException("unknown SignTemplate.params");
        }

        byte[] content = signTemplate.getMessage();
        P11Identity identity = p11CryptService.getIdentity(signTemplate.getIdentityId().getEntityId());
        byte[] signature = identity.sign(mechanism, params, content);
        respItvInfoValue = new DEROctetString(signature);
    } else if (P11ProxyConstants.ACTION_updateCerificate == action) {
        Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
        slot.updateCertificate(asn1.getEntityId().getObjectId().getObjectId(),
                X509Util.toX509Cert(asn1.getCertificate()));
    } else if (P11ProxyConstants.ACTION_removeObjects == action) {
        Asn1RemoveObjectsParams asn1 = Asn1RemoveObjectsParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        int num = slot.removeObjects(asn1.getObjectId(), asn1.getObjectLabel());
        respItvInfoValue = new ASN1Integer(num);
    } else {
        final String statusMessage = "unsupported XiPKI action code '" + action + "'";
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new ASN1Integer(protocolVersion));
    vec.add(new ASN1Integer(action));
    if (respItvInfoValue != null) {
        vec.add(respItvInfoValue);
    }

    InfoTypeAndValue respItv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp_cmpGenmsg,
            new DERSequence(vec));
    GenRepContent genRepContent = new GenRepContent(respItv);
    PKIBody respBody = new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
    return new PKIMessage(respHeader, respBody);
}

From source file:org.xipki.commons.security.pkcs11.proxy.Asn1EntityIdAndCert.java

License:Open Source License

public Asn1EntityIdAndCert(final P11EntityIdentifier entityId, final X509Certificate certificate) {
    ParamUtil.requireNonNull("entityId", entityId);
    ParamUtil.requireNonNull("certificate", certificate);
    this.entityId = new Asn1P11EntityIdentifier(entityId);
    byte[] encoded;
    try {/*from  ww  w  .j a  va  2  s  . c  o m*/
        encoded = certificate.getEncoded();
    } catch (CertificateEncodingException ex) {
        throw new IllegalArgumentException("could not encode certificate: " + ex.getMessage(), ex);
    }
    this.certificate = Certificate.getInstance(encoded);
}

From source file:org.xipki.commons.security.pkcs11.proxy.Asn1Util.java

License:Open Source License

public static Certificate getCertificate(final ASN1Encodable object) throws BadAsn1ObjectException {
    try {//from   ww  w.  j a v  a2  s  . c om
        return Certificate.getInstance(object);
    } catch (IllegalArgumentException ex) {
        throw new BadAsn1ObjectException("invalid object Certificate: " + ex.getMessage(), ex);
    }
}