Example usage for org.bouncycastle.cert X509CertificateHolder getEncoded

List of usage examples for org.bouncycastle.cert X509CertificateHolder getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.cert X509CertificateHolder getEncoded.

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

Return the ASN.1 encoding of this holder's certificate.

Usage

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

License:Open Source License

private byte[] getCmsData(byte[] cms) throws Exception {
    CMSSignedData cmsSignedData = new CMSSignedData(cms);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);

    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    // we trust SSL here, no need for explicit verification of CMS signing
    // certificate

    LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal());

    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);//from   www.  j  av  a2s . co m
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] responseData = (byte[]) signedContent.getContent();

    return responseData;
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

License:Open Source License

private void generateCertificate() {
    X500Name name = new X500Name(this.name);
    BigInteger serial = BigInteger.valueOf(1);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(this.keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(name, serial,
            this.notBefore, this.notAfter, name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {//w  w w. ja va  2  s. c o m
        asymmetricKeyParameter = PrivateKeyFactory.createKey(this.keyPair.getPrivate().getEncoded());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
}

From source file:be.e_contract.mycarenet.etee.EncryptionToken.java

License:Open Source License

private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken)
        throws CMSException, CertificateException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken);

    // get signer identifier
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    // get signer certificate
    Store certificateStore = cmsSignedData.getCertificates();
    LOG.debug("certificate store type: " + certificateStore.getClass().getName());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId);
    X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate signingCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded()));
    LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal());

    // verify CMS signature
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(signingCertificate);/*from www.j  a  v  a 2 s. co m*/
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("ETK signature invalid");
    }

    // get encryption certificate
    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    X509Certificate encryptionCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(data));

    LOG.debug("all available certificates:");
    logCertificates(certificateStore, null);

    // get authentication certificate
    CustomSelector authenticationSelector = new CustomSelector();
    authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> authenticationCertificates = certificateStore
            .getMatches(authenticationSelector);
    if (authenticationCertificates.size() != 1) {
        LOG.debug("no authentication certificate match");
    }
    X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next();
    this.authenticationCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded()));

    verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate);

    return encryptionCertificate;
}

From source file:be.e_contract.mycarenet.etee.Unsealer.java

License:Open Source License

private byte[] getVerifiedContent(byte[] cmsData)
        throws CertificateException, CMSException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(cmsData);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);
    if (null == this.senderCertificate) {
        if (certificateCollection.isEmpty()) {
            throw new SecurityException("no sender certificate present");
        }/* w ww . j av a2  s  .c o m*/
        X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

        this.senderCertificate = certificate;
        LOG.debug("signer certificate subject: " + certificate.getSubjectX500Principal());
    }

    /*
     * By reusing the sender certificate we have the guarantee that the
     * outer signature and inner signature share the same origin.
     */
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(this.senderCertificate);
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    return data;
}

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    URI ocspUri = getOcspUri(childCertificate);
    if (null == ocspUri) {
        return TrustLinkerResult.UNDECIDED;
    }//  www  . ja  va 2s .  com
    LOG.debug("OCSP URI: " + ocspUri);

    OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate,
            validationDate);
    if (null == ocspResp) {
        LOG.debug("OCSP response not found");
        return TrustLinkerResult.UNDECIDED;
    }

    int ocspRespStatus = ocspResp.getStatus();
    if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) {
        LOG.debug("OCSP response status: " + ocspRespStatus);
        return TrustLinkerResult.UNDECIDED;
    }

    Object responseObject = ocspResp.getResponseObject();
    BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject;

    X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts();
    for (X509CertificateHolder responseCertificate : responseCertificates) {
        LOG.debug("OCSP response cert: " + responseCertificate.getSubject());
        LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer());
    }

    algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate);

    if (0 == responseCertificates.length) {
        /*
         * This means that the OCSP response has been signed by the issuing
         * CA itself.
         */
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey());
        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
    } else {
        /*
         * We're dealing with a dedicated authorized OCSP Responder
         * certificate, or of course with a CA that issues the OCSP
         * Responses itself.
         */

        X509CertificateHolder ocspResponderCertificate = responseCertificates[0];
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate);

        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP Responser response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
        if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) {
            // check certificate signature algorithm
            algorithmPolicy.checkSignatureAlgorithm(
                    ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate);

            X509Certificate issuingCaCertificate;
            if (responseCertificates.length < 2) {
                // so the OCSP certificate chain only contains a single
                // entry
                LOG.debug("OCSP responder complete certificate chain missing");
                /*
                 * Here we assume that the OCSP Responder is directly signed
                 * by the CA.
                 */
                issuingCaCertificate = certificate;
            } else {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                issuingCaCertificate = (X509Certificate) certificateFactory
                        .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded()));
                /*
                 * Is next check really required?
                 */
                if (false == certificate.equals(issuingCaCertificate)) {
                    LOG.debug("OCSP responder certificate not issued by CA");
                    return TrustLinkerResult.UNDECIDED;
                }
            }
            // check certificate signature
            algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate);

            PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker();
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded()));
            LOG.debug("OCSP Responder public key fingerprint: "
                    + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded()));
            publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate,
                    validationDate, revocationData, algorithmPolicy);
            if (null == x509OcspResponderCertificate
                    .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) {
                LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck");
                /*
                 * TODO: perform CRL validation on the OCSP Responder
                 * certificate. On the other hand, do we really want to
                 * check the checker?
                 */
                return TrustLinkerResult.UNDECIDED;
            }
            List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage();
            if (null == extendedKeyUsage) {
                LOG.debug("OCSP Responder certificate has no extended key usage extension");
                return TrustLinkerResult.UNDECIDED;
            }
            if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage");
                return TrustLinkerResult.UNDECIDED;
            }
        } else {
            LOG.debug("OCSP Responder certificate equals the CA certificate");
            // and the CA certificate is already trusted at this point
        }
    }

    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
            new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber());

    SingleResp[] singleResps = basicOCSPResp.getResponses();
    for (SingleResp singleResp : singleResps) {
        CertificateID responseCertificateId = singleResp.getCertID();
        if (false == certificateId.equals(responseCertificateId)) {
            continue;
        }
        DateTime thisUpdate = new DateTime(singleResp.getThisUpdate());
        DateTime nextUpdate;
        if (null != singleResp.getNextUpdate()) {
            nextUpdate = new DateTime(singleResp.getNextUpdate());
        } else {
            LOG.debug("no OCSP nextUpdate");
            nextUpdate = thisUpdate;
        }
        LOG.debug("OCSP thisUpdate: " + thisUpdate);
        LOG.debug("(OCSP) nextUpdate: " + nextUpdate);
        DateTime beginValidity = thisUpdate.minus(this.freshnessInterval);
        DateTime endValidity = nextUpdate.plus(this.freshnessInterval);
        DateTime validationDateTime = new DateTime(validationDate);
        if (validationDateTime.isBefore(beginValidity)) {
            LOG.warn("OCSP response not yet valid");
            continue;
        }
        if (validationDateTime.isAfter(endValidity)) {
            LOG.warn("OCSP response expired");
            continue;
        }
        if (null == singleResp.getCertStatus()) {
            LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal());
            addRevocationData(revocationData, ocspResp, ocspUri);
            return TrustLinkerResult.TRUSTED;
        } else {
            LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName());
            if (singleResp.getCertStatus() instanceof RevokedStatus) {
                LOG.debug("OCSP status revoked");
            }
            addRevocationData(revocationData, ocspResp, ocspUri);
            throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                    "certificate revoked by OCSP");
        }
    }

    LOG.debug("no matching OCSP response entry");
    return TrustLinkerResult.UNDECIDED;
}

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey,
        boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage,
        String signatureAlgorithm, boolean tsa, boolean includeSKID, boolean includeAKID,
        PublicKey akidPublicKey, String certificatePolicy, Boolean qcCompliance, boolean ocspResponder,
        boolean qcSSCD) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {

    X500Name issuerName;/* w w w . j a va 2 s.c  o m*/
    if (null != issuerCertificate) {
        issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerName = new X500Name(subjectDn);
    }
    X500Name subjectName = new X500Name(subjectDn);
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    if (includeSKID) {
        x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(subjectPublicKey));
    }

    if (includeAKID) {

        PublicKey authorityPublicKey;
        if (null != akidPublicKey) {
            authorityPublicKey = akidPublicKey;
        } else if (null != issuerCertificate) {
            authorityPublicKey = issuerCertificate.getPublicKey();
        } else {
            authorityPublicKey = subjectPublicKey;
        }
        x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(authorityPublicKey));
    }

    if (caFlag) {
        if (-1 == pathLength) {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(2147483647));
        } else {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != crlUri) {
        GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(crlUri));
        GeneralNames generalNames = new GeneralNames(generalName);
        DistributionPointName distPointName = new DistributionPointName(generalNames);
        DistributionPoint distPoint = new DistributionPoint(distPointName, null, null);
        DistributionPoint[] crlDistPoints = new DistributionPoint[] { distPoint };
        CRLDistPoint crlDistPoint = new CRLDistPoint(crlDistPoints);
        x509v3CertificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint);
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        x509v3CertificateBuilder.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, keyUsage);
    }

    if (null != certificatePolicy) {
        ASN1ObjectIdentifier policyObjectIdentifier = new ASN1ObjectIdentifier(certificatePolicy);
        PolicyInformation policyInformation = new PolicyInformation(policyObjectIdentifier);
        x509v3CertificateBuilder.addExtension(Extension.certificatePolicies, false,
                new DERSequence(policyInformation));
    }

    if (null != qcCompliance) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        if (qcCompliance) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcCompliance));
        } else {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_RetentionPeriod));
        }
        if (qcSSCD) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcSSCD));
        }
        x509v3CertificateBuilder.addExtension(Extension.qCStatements, true, new DERSequence(vec));

    }

    if (tsa) {
        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (ocspResponder) {
        x509v3CertificateBuilder.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false,
                DERNull.INSTANCE);

        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}

From source file:be.neutrinet.ispng.vpn.api.VPNClientCertificate.java

@Get
public Representation getCertificate() {
    // TODO: decide if returning an entire list of certificates needs to be implemented
    if (!getRequestAttributes().containsKey("client")) {
        return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
    }//www  .ja v a 2 s .  c  o  m

    String clientId = getAttribute("client").toString();
    try {
        List<Certificate> certs = Certificates.dao.queryForEq("client_id", clientId);

        if (getQueryValue("active") != null && Boolean.parseBoolean(getQueryValue("active"))) {
            certs = certs.stream().filter(Certificate::valid).collect(Collectors.toList());
        }

        if (getQueryValue("raw") != null) {
            if (getRequestAttributes().containsKey("cert") && !getAttribute("cert").equals("all")) {
                String certId = getAttribute("cert").toString();

                Certificate cert = certs.stream().filter(c -> c.id == Integer.parseInt(certId)).iterator()
                        .next();

                X509CertificateHolder c = null;
                if (cert.signedDate == null) {
                    c = sign(cert);
                } else {
                    c = cert.get();
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(baos);
                PemObject po = new PemObject("CERTIFICATE", c.getEncoded());
                PEMWriter pw = new PEMWriter(osw);
                pw.writeObject(po);
                pw.close();

                return new ByteArrayRepresentation(baos.toByteArray(), PEM_MIME);
            } else {
                return clientError("MAX_ONE_RAW_CERT", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }
        } else {
            if (getRequestAttributes().containsKey("cert") && !getAttribute("cert").equals("all")) {
                String certId = getAttribute("cert").toString();

                Certificate cert = certs.stream().filter(c -> c.id == Integer.parseInt(certId)).iterator()
                        .next();

                return new JacksonRepresentation(cert);
            } else {
                return new JacksonRepresentation(certs);
            }
        }
    } catch (Exception ex) {
        Logger.getLogger(VPNClientCertificate.class).error("Failed to get certificate", ex);
    }

    return DEFAULT_ERROR;
}

From source file:bft.BFTNode.java

private byte[] getSerializedCertificate(X509CertificateHolder certificate) throws IOException {

    PemObject pemObj = (new PemObject("", certificate.getEncoded()));

    StringWriter strWriter = new StringWriter();
    PemWriter writer = new PemWriter(strWriter);
    writer.writeObject(pemObj);//ww w  .ja v a 2  s . c  o m

    writer.close();
    strWriter.close();

    return strWriter.toString().getBytes();

}

From source file:bft.TestSignatures.java

private static void parseCertificate(String filename) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(filename));
    PEMParser pp = new PEMParser(br);
    X509CertificateHolder certificate = (X509CertificateHolder) pp.readObject();

    PemObject pemObj = (new PemObject("", certificate.getEncoded()));

    StringWriter strWriter = new StringWriter();
    PemWriter writer = new PemWriter(strWriter);
    writer.writeObject(pemObj);/*  ww w.  jav  a  2  s .  c om*/

    writer.close();
    strWriter.close();

    TestSignatures.serializedCert = strWriter.toString().getBytes();

}

From source file:bft.TestSignaturesZMQ.java

private static void parseCertificate(String filename) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(filename));
    PEMParser pp = new PEMParser(br);
    X509CertificateHolder certificate = (X509CertificateHolder) pp.readObject();

    PemObject pemObj = (new PemObject("", certificate.getEncoded()));

    StringWriter strWriter = new StringWriter();
    PemWriter writer = new PemWriter(strWriter);
    writer.writeObject(pemObj);//from  w  w w.  j a v a2 s .  c  o m

    writer.close();
    strWriter.close();

    TestSignaturesZMQ.serializedCert = strWriter.toString().getBytes();

}