Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {//from  www .  j a  va 2s  .c o m
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:test.integ.be.fedict.trust.Foreigner201305Test.java

@Test
public void testForeigner201305() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCert = (X509Certificate) certificateFactory
            .generateCertificate(Foreigner201305Test.class.getResourceAsStream("/belgiumrca2.crt"));
    X509Certificate foreigner201304Cert = (X509Certificate) certificateFactory
            .generateCertificate(Foreigner201305Test.class.getResourceAsStream("/foreigner201304.crt"));

    foreigner201304Cert.verify(rootCert.getPublicKey());

    X509Certificate foreigner201305Cert = (X509Certificate) certificateFactory
            .generateCertificate(Foreigner201305Test.class.getResourceAsStream("/foreigner201305.crt"));

    foreigner201305Cert.verify(rootCert.getPublicKey());

    byte[] foreigner201304SignatureValue = foreigner201304Cert.getSignature();
    byte[] foreigner201305SignatureValue = foreigner201305Cert.getSignature();
    LOG.debug("201304 signature size: " + foreigner201304SignatureValue.length);
    LOG.debug("201305 signature size: " + foreigner201305SignatureValue.length);

    RSAPublicKey rootPublicKey = (RSAPublicKey) rootCert.getPublicKey();

    BigInteger foreigner201304Signature = new BigInteger(foreigner201304SignatureValue);
    BigInteger foreigner201305Signature = new BigInteger(foreigner201305SignatureValue);

    LOG.debug("201305 signature size: " + foreigner201305Signature.toByteArray().length);

    BigInteger foreigner201304PaddedMessage = foreigner201304Signature.modPow(rootPublicKey.getPublicExponent(),
            rootPublicKey.getModulus());
    BigInteger foreigner201305PaddedMessage = foreigner201305Signature.modPow(rootPublicKey.getPublicExponent(),
            rootPublicKey.getModulus());

    LOG.debug(// w  ww . j  a  v a2  s.  c o  m
            "201304 padded message: " + new String(Hex.encodeHex(foreigner201304PaddedMessage.toByteArray())));
    LOG.debug(
            "201305 padded message: " + new String(Hex.encodeHex(foreigner201305PaddedMessage.toByteArray())));

    LOG.debug("201304 modulus size: "
            + ((RSAPublicKey) foreigner201304Cert.getPublicKey()).getModulus().toByteArray().length);
    LOG.debug("201305 modulus size: "
            + ((RSAPublicKey) foreigner201305Cert.getPublicKey()).getModulus().toByteArray().length);
    LOG.debug("201304 modulus: " + new String(
            Hex.encodeHex(((RSAPublicKey) foreigner201304Cert.getPublicKey()).getModulus().toByteArray())));
    LOG.debug("201305 modulus: " + new String(
            Hex.encodeHex(((RSAPublicKey) foreigner201305Cert.getPublicKey()).getModulus().toByteArray())));
}

From source file:test.unit.be.fedict.trust.constraints.QCStatementsCertificateConstraintTest.java

@Test
public void testQcSSCD() throws Exception {
    InputStream certInputStream = QCStatementsCertificateConstraintTest.class
            .getResourceAsStream("/qcstatements.der");
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(certInputStream);
    LOG.debug("certificate: " + certificate);

    QCStatementsCertificateConstraint testedInstance = new QCStatementsCertificateConstraint(true, true);

    testedInstance.check(certificate);//from w  w w .  j  av a 2  s  . c  o m
}

From source file:org.kuali.rice.ksb.security.SignatureVerifyingRequestWrapper.java

public SignatureVerifyingRequestWrapper(HttpServletRequest request) {
    super(request);
    String encodedSignature = request.getHeader(KSBConstants.DIGITAL_SIGNATURE_HEADER);
    if (StringUtils.isEmpty(encodedSignature)) {
        throw new RuntimeException("A digital signature was required on the request but none was found.");
    }// www .j a  va  2  s  .  c o m
    String verificationAlias = request.getHeader(KSBConstants.KEYSTORE_ALIAS_HEADER);
    String encodedCertificate = request.getHeader(KSBConstants.KEYSTORE_CERTIFICATE_HEADER);
    if ((StringUtils.isEmpty(verificationAlias)) && (StringUtils.isEmpty(encodedCertificate))) {
        throw new RuntimeException(
                "A verification alias or certificate was required on the request but neither was found.");
    }
    try {
        this.digitalSignature = Base64.decodeBase64(encodedSignature.getBytes("UTF-8"));
        if (StringUtils.isNotBlank(encodedCertificate)) {
            byte[] certificate = Base64.decodeBase64(encodedCertificate.getBytes("UTF-8"));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            this.signature = KSBServiceLocator.getDigitalSignatureService()
                    .getSignatureForVerification(cf.generateCertificate(new ByteArrayInputStream(certificate)));
        } else if (StringUtils.isNotBlank(verificationAlias)) {
            this.signature = KSBServiceLocator.getDigitalSignatureService()
                    .getSignatureForVerification(verificationAlias);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize digital signature verification.", e);
    }
}

From source file:org.bibsonomy.webapp.validation.opensocial.BibSonomyOAuthValidator.java

private PublicKey getPublicKeyFromDerCert(byte[] certObject) throws GeneralSecurityException {
    CertificateFactory fac = CertificateFactory.getInstance("X509");
    ByteArrayInputStream in = new ByteArrayInputStream(certObject);
    X509Certificate cert = (X509Certificate) fac.generateCertificate(in);
    return cert.getPublicKey();
}

From source file:org.projectforge.business.ldap.MyTrustManager.java

public void addCertificate(final String alias, final InputStream is) {
    CertificateFactory factory;
    try {//from   w  w  w. j  av  a  2 s . c o  m
        factory = CertificateFactory.getInstance("X.509");
        certificate = factory.generateCertificate(is);
        // keyStore.setCertificateEntry(alias, certificate);
    } catch (final CertificateException ex) {
        log.error("Exception encountered " + ex + " while adding certificate '" + alias + "'", ex);
        // } catch (final KeyStoreException ex) {
        // log.error("Exception encountered " + ex + " while adding certificate '" + alias + "'", ex);
    }
}

From source file:pl.psnc.synat.wrdz.ru.registries.RemoteRegistryManagerBean.java

/**
 * Loads the object representation of the certificate from it's byte representation.
 * //from  www  . jav a  2s. com
 * @param certificate
 *            PEM representation of the certificate.
 * @return loaded x509 certificate object.
 */
private X509Certificate loadCertificate(String certificate) {
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(certificate)));
    } catch (CertificateException e) {
        logger.error("Wrong certificate format or data corrupt.", e);
        throw new UserCertificateException("Wrong certificate format or data corrupt.", e);
    }
}

From source file:no.digipost.api.client.filters.response.ResponseSignatureFilter.java

public X509Certificate lastSertifikat() {
    try {/*  www  .j  a  va 2  s .  com*/
        InputStream certStream = new ByteArrayInputStream(
                apiService.getEntryPoint().getCertificate().getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        X509Certificate sertifikat = (X509Certificate) cf.generateCertificate(certStream);
        if (sertifikat == null) {
            throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                    "Kunne ikke laste Digipost's public key - server-signatur kunne ikke sjekkes");
        }
        return sertifikat;
    } catch (GeneralSecurityException e) {
        throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                "Kunne ikke laste Digiposts public key - server-signatur kunne ikke sjekkes");
    }
}

From source file:test.integ.be.e_contract.mycarenet.etee.SealTest.java

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();
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);
    if (false == certificateCollection.isEmpty()) {
        X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

        SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                .build(certificate);//from   w ww .j av a 2 s.c  o  m
        boolean signatureResult = signer.verify(signerInformationVerifier);
        assertTrue(signatureResult);

        LOG.debug("signer certificate: " + certificate);
    } else {
        LOG.warn("no signer matched");
    }

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

From source file:eu.europa.ec.markt.dss.ws.impl.SignatureServiceImpl.java

private SignatureParameters createParameters(SignatureFormat signatureInfoLevel,
        SignedPropertiesContainer container) throws IOException {
    SignatureParameters params = new SignatureParameters();
    params.setSignatureFormat(signatureInfoLevel);
    if (container != null) {
        params.setClaimedSignerRole(container.getClaimedSignerRole());
        params.setSignaturePackaging(SignaturePackaging.valueOf(container.getSignaturePackaging()));
        params.setSigningDate(container.getSigningDate());

        try {/*from ww w .j  av  a2s. com*/
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            params.setSigningCertificate((X509Certificate) factory
                    .generateCertificate(new ByteArrayInputStream(container.getSigningCertificate())));
            List<X509Certificate> chain = new ArrayList<X509Certificate>();
            for (byte[] cert : container.getCertificateChain()) {
                chain.add((X509Certificate) factory.generateCertificate(new ByteArrayInputStream(cert)));
            }
            params.setCertificateChain(chain);
        } catch (CertificateException ex) {
            throw new IOException("Cannot read certficate");
        }
    }

    return params;
}