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

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

Introduction

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

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

Return the default BER or DER encoding for this object.

Usage

From source file:org.xipki.commons.security.shell.CertInfoCmd.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    Certificate cert = Certificate.getInstance(IoUtil.read(inFile));

    if (serial != null && serial) {
        return getNumber(cert.getSerialNumber().getPositiveValue());
    } else if (subject != null && subject) {
        return cert.getSubject().toString();
    } else if (issuer != null && issuer) {
        return cert.getIssuer().toString();
    } else if (notBefore != null && notBefore) {
        return toUtcTimeyyyyMMddhhmmssZ(cert.getStartDate().getDate());
    } else if (notAfter != null && notAfter) {
        return toUtcTimeyyyyMMddhhmmssZ(cert.getEndDate().getDate());
    } else if (fingerprint != null && fingerprint) {
        byte[] encoded = cert.getEncoded();
        return HashAlgoType.getHashAlgoType(hashAlgo).hexHash(encoded);
    }/*from   w  w  w  .  j  a va2s. co  m*/

    return null;
}

From source file:org.xipki.commons.security.shell.ExtractCertFromCrlCmd.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    X509CRL crl = X509Util.parseCrl(crlFile);
    String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId();
    byte[] extnValue = crl.getExtensionValue(oidExtnCerts);
    if (extnValue == null) {
        throw new IllegalCmdParamException("no certificate is contained in " + crlFile);
    }/*from  ww w .  j a va2 s . c  o  m*/

    extnValue = removingTagAndLenFromExtensionValue(extnValue);
    ASN1Set asn1Set = DERSet.getInstance(extnValue);
    final int n = asn1Set.size();
    if (n == 0) {
        throw new CmdFailure("no certificate is contained in " + crlFile);
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(out);

    for (int i = 0; i < n; i++) {
        ASN1Encodable asn1 = asn1Set.getObjectAt(i);
        Certificate cert;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            cert = Certificate.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException ex) {
            // backwards compatibility
            cert = Certificate.getInstance(asn1);
        }

        byte[] certBytes = cert.getEncoded();
        String sha1FpCert = HashAlgoType.SHA1.hexHash(certBytes);
        ZipEntry certZipEntry = new ZipEntry(sha1FpCert + ".der");
        zip.putNextEntry(certZipEntry);
        try {
            zip.write(certBytes);
        } finally {
            zip.closeEntry();
        }
    }

    zip.flush();
    zip.close();

    saveVerbose("extracted " + n + " certificates to", new File(outFile), out.toByteArray());
    return null;
}

From source file:org.xipki.ocsp.server.impl.certstore.CrlCertStatusStore.java

License:Open Source License

private static Map<HashAlgoType, byte[]> getCertHashes(final Certificate cert) throws CertStatusStoreException {
    byte[] encodedCert;
    try {/*from ww w .ja v  a  2 s.  c  o m*/
        encodedCert = cert.getEncoded();
    } catch (IOException e) {
        throw new CertStatusStoreException(e.getMessage(), e);
    }

    Map<HashAlgoType, byte[]> certHashes = new ConcurrentHashMap<>();
    for (HashAlgoType hashAlgo : HashAlgoType.values()) {
        byte[] certHash = HashCalculator.hash(hashAlgo, encodedCert);
        certHashes.put(hashAlgo, certHash);
    }

    return certHashes;
}

From source file:org.xipki.pki.ca.client.shell.loadtest.DbGoodCertSerialIterator.java

License:Open Source License

public DbGoodCertSerialIterator(final Certificate caCert, final DataSourceWrapper caDataSource)
        throws Exception {
    ParamUtil.requireNonNull("caCert", caCert);
    this.caDataSource = ParamUtil.requireNonNull("caDataSource", caDataSource);
    this.caSerial = caCert.getSerialNumber().getPositiveValue();

    this.sqlNextSerials = caDataSource.buildSelectFirstSql("ID,SN FROM CERT WHERE REV=0 AND CA_ID=? AND ID>=?",
            numSqlEntries, "ID");

    String b64Sha1Fp = HashAlgoType.SHA1.base64Hash(caCert.getEncoded());
    String sql = "SELECT ID FROM CS_CA WHERE SHA1_CERT='" + b64Sha1Fp + "'";
    Statement stmt = caDataSource.getConnection().createStatement();
    try {//from  ww w  .ja  va2 s.co m
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            caInfoId = rs.getInt("ID");
        } else {
            throw new Exception("CA Certificate and database configuration does not match");
        }
        rs.close();

        sql = "SELECT MIN(ID) FROM CERT WHERE REV=0 AND CA_ID=" + caInfoId;
        rs = stmt.executeQuery(sql);
        rs.next();
        minId = rs.getLong(1);
        nextStartId = minId;
    } finally {
        caDataSource.releaseResources(stmt, null);
    }

    currentSerial = readNextNumber();
}

From source file:org.xipki.pki.ca.server.impl.X509Ca.java

License:Open Source License

private X509CertificateInfo doGenerateCertificate(final GrantedCertTemplate gct, final boolean requestedByRa,
        final RequestorInfo requestor, final String user, final boolean keyUpdate, final RequestType reqType,
        final byte[] transactionId, final AuditEvent event) throws OperationException {
    ParamUtil.requireNonNull("gct", gct);

    event.addEventData(CaAuditConstants.NAME_reqSubject, X509Util.getRfc4519Name(gct.requestedSubject));
    event.addEventData(CaAuditConstants.NAME_certprofile, gct.certprofile.getName());
    event.addEventData(CaAuditConstants.NAME_notBefore, DateUtil.toUtcTimeyyyyMMddhhmmss(gct.grantedNotBefore));
    event.addEventData(CaAuditConstants.NAME_notAfter, DateUtil.toUtcTimeyyyyMMddhhmmss(gct.grantedNotAfter));
    if (user != null) {
        event.addEventData(CaAuditConstants.NAME_user, user);
    }//from   w w w.  ja v  a  2s.c  o  m

    adaptGrantedSubejct(gct);

    IdentifiedX509Certprofile certprofile = gct.certprofile;

    boolean publicKeyCertInProcessExisted = publicKeyCertsInProcess.add(gct.fpPublicKey);
    if (!publicKeyCertInProcessExisted) {
        if (!certprofile.isDuplicateKeyPermitted()) {
            throw new OperationException(ErrorCode.ALREADY_ISSUED,
                    "certificate with the given public key already in process");
        }
    }

    if (!subjectCertsInProcess.add(gct.fpSubject)) {
        if (!certprofile.isDuplicateSubjectPermitted()) {
            if (!publicKeyCertInProcessExisted) {
                publicKeyCertsInProcess.remove(gct.fpPublicKey);
            }

            throw new OperationException(ErrorCode.ALREADY_ISSUED,
                    "certificate with the given subject " + gct.grantedSubjectText + " already in process");
        }
    }

    try {
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                caInfo.getPublicCaInfo().getX500Subject(), caInfo.nextSerial(), gct.grantedNotBefore,
                gct.grantedNotAfter, gct.grantedSubject, gct.grantedPublicKey);

        X509CertificateInfo ret;

        try {
            X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
            X509Certificate crlSignerCert = (crlSigner == null) ? null : crlSigner.getCert();

            ExtensionValues extensionTuples = certprofile.getExtensions(gct.requestedSubject,
                    gct.grantedSubject, gct.extensions, gct.grantedPublicKey, caInfo.getPublicCaInfo(),
                    crlSignerCert, gct.grantedNotBefore, gct.grantedNotAfter);
            if (extensionTuples != null) {
                for (ASN1ObjectIdentifier extensionType : extensionTuples.getExtensionTypes()) {
                    ExtensionValue extValue = extensionTuples.getExtensionValue(extensionType);
                    certBuilder.addExtension(extensionType, extValue.isCritical(), extValue.getValue());
                }
            }

            X509CertificateHolder certHolder;
            try {
                certHolder = gct.signer.build(certBuilder);
            } catch (NoIdleSignerException ex) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
            }

            Certificate bcCert = certHolder.toASN1Structure();
            byte[] encodedCert = bcCert.getEncoded();
            int maxCertSize = gct.certprofile.getMaxCertSize();
            if (maxCertSize > 0) {
                int certSize = encodedCert.length;
                if (certSize > maxCertSize) {
                    throw new OperationException(ErrorCode.NOT_PERMITTED, String.format(
                            "certificate exceeds the maximal allowed size: %d > %d", certSize, maxCertSize));
                }
            }

            X509Certificate cert;
            try {
                cert = X509Util.toX509Cert(bcCert);
            } catch (CertificateException ex) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                        "should not happen, could not parse generated certificate");
            }

            if (!verifySignature(cert)) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                        "could not verify the signature of generated certificate");
            }

            X509CertWithDbId certWithMeta = new X509CertWithDbId(cert, encodedCert);
            ret = new X509CertificateInfo(certWithMeta, caInfo.getCertificate(), gct.grantedPublicKeyData,
                    gct.certprofile.getName());
            ret.setUser(user);
            ret.setRequestor(requestor);
            ret.setReqType(reqType);
            ret.setTransactionId(transactionId);
            ret.setRequestedSubject(gct.requestedSubject);

            if (doPublishCertificate(ret) == 1) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not save certificate");
            }
        } catch (BadCertTemplateException ex) {
            throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
        } catch (OperationException ex) {
            throw ex;
        } catch (Throwable th) {
            LogUtil.error(LOG, th, "could not generate certificate");
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, th);
        }

        if (gct.warning != null) {
            ret.setWarningMessage(gct.warning);
        }

        return ret;
    } finally {
        publicKeyCertsInProcess.remove(gct.fpPublicKey);
        subjectCertsInProcess.remove(gct.fpSubject);
    }
}

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

License:Open Source License

private static X509Certificate generateCertificate(final ConcurrentContentSigner signer,
        final IdentifiedX509Certprofile certprofile, final CertificationRequest csr,
        final BigInteger serialNumber, final SubjectPublicKeyInfo publicKeyInfo, final List<String> cacertUris,
        final List<String> ocspUris, final List<String> crlUris, final List<String> deltaCrlUris)
        throws OperationException {

    SubjectPublicKeyInfo tmpPublicKeyInfo;
    try {//from  w w  w  .jav a  2s  .co m
        tmpPublicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo);
    } catch (InvalidKeySpecException ex) {
        LOG.warn("SecurityUtil.toRfc3279Style", ex);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }

    try {
        certprofile.checkPublicKey(tmpPublicKeyInfo);
    } catch (BadCertTemplateException ex) {
        LOG.warn("certprofile.checkPublicKey", ex);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }

    X500Name requestedSubject = csr.getCertificationRequestInfo().getSubject();

    SubjectInfo subjectInfo;
    // subject
    try {
        subjectInfo = certprofile.getSubject(requestedSubject);
    } catch (CertprofileException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                "exception in cert profile " + certprofile.getName());
    } catch (BadCertTemplateException ex) {
        LOG.warn("certprofile.getSubject", ex);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }

    Date notBefore = certprofile.getNotBefore(null);
    if (notBefore == null) {
        notBefore = new Date();
    }

    CertValidity validity = certprofile.getValidity();
    if (validity == null) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE,
                "no validity specified in the profile " + certprofile.getName());
    }

    Date notAfter = validity.add(notBefore);

    X500Name grantedSubject = subjectInfo.getGrantedSubject();

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, serialNumber, notBefore,
            notAfter, grantedSubject, tmpPublicKeyInfo);

    PublicCaInfo publicCaInfo = new PublicCaInfo(grantedSubject, serialNumber, null, null, cacertUris, ocspUris,
            crlUris, deltaCrlUris);

    Extensions extensions = null;
    ASN1Set attrs = csr.getCertificationRequestInfo().getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
        }
    }

    try {
        addExtensions(certBuilder, certprofile, requestedSubject, grantedSubject, extensions, tmpPublicKeyInfo,
                publicCaInfo, notBefore, notAfter);

        Certificate bcCert = signer.build(certBuilder).toASN1Structure();
        return X509Util.parseCert(bcCert.getEncoded());
    } catch (BadCertTemplateException ex) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    } catch (NoIdleSignerException | CertificateException | IOException | CertprofileException
            | NoSuchAlgorithmException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
}

From source file:org.xipki.pki.ocsp.server.impl.store.crl.CrlCertStatusStore.java

License:Open Source License

private Map<HashAlgoType, byte[]> getCertHashes(final Certificate cert) throws OcspStoreException {
    ParamUtil.requireNonNull("cert", cert);
    if (certHashAlgos.isEmpty()) {
        return null;
    }//  w  w  w . j  a v a2  s .c o m

    byte[] encodedCert;
    try {
        encodedCert = cert.getEncoded();
    } catch (IOException ex) {
        throw new OcspStoreException(ex.getMessage(), ex);
    }

    Map<HashAlgoType, byte[]> certHashes = new ConcurrentHashMap<>();
    for (HashAlgoType hashAlgo : certHashAlgos) {
        byte[] certHash = hashAlgo.hash(encodedCert);
        certHashes.put(hashAlgo, certHash);
    }

    return certHashes;
}

From source file:org.xipki.pki.scep.client.test.AbstractCaTest.java

License:Open Source License

private boolean equals(final Certificate bcCert, final X509Certificate cert)
        throws CertificateException, IOException {
    return Arrays.equals(cert.getEncoded(), bcCert.getEncoded());
}

From source file:org.xipki.pki.scep.serveremulator.CaEmulator.java

License:Open Source License

public CaEmulator(final PrivateKey caKey, final Certificate caCert, final boolean generateCrl)
        throws CertificateEncodingException {
    this.caKey = ParamUtil.requireNonNull("caKey", caKey);
    this.caCert = ParamUtil.requireNonNull("caCert", caCert);
    this.caSubject = caCert.getSubject();
    this.generateCrl = generateCrl;
    try {//  w  ww  . j  a  va  2s  . co  m
        this.caCertBytes = caCert.getEncoded();
    } catch (IOException ex) {
        throw new CertificateEncodingException(ex.getMessage(), ex);
    }
}

From source file:org.xipki.pki.scep.util.ScepUtil.java

License:Open Source License

public static X509Certificate toX509Cert(final org.bouncycastle.asn1.x509.Certificate asn1Cert)
        throws CertificateException {
    byte[] encodedCert;
    try {/*  www  . ja v a2  s  . co  m*/
        encodedCert = asn1Cert.getEncoded();
    } catch (IOException ex) {
        throw new CertificateEncodingException("could not get encoded certificate", ex);
    }
    return parseCert(encodedCert);
}