Example usage for java.security.cert X509Certificate getEncoded

List of usage examples for java.security.cert X509Certificate getEncoded

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getEncoded.

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:org.josso.gateway.identity.service.store.db.IdentityDAO.java

public String loadUID(CredentialKey key) throws SSOIdentityException {
    PreparedStatement stmt = null;
    ResultSet result = null;/*  ww  w .java 2  s  . co  m*/
    String uid = null;

    try {

        if (key instanceof CertificateUserKey) {
            X509Certificate certificate = ((CertificateUserKey) key).getCertificate();
            if (certificate != null) {
                stmt = createPreparedStatement(_uidQueryString);
                stmt.setBytes(1, certificate.getEncoded());
                // Use key id to narrow search scope?
                //stmt.setString(2, ((CertificateUserKey)key).getId());
                result = stmt.executeQuery();
                while (result.next()) {
                    uid = result.getString(1);
                    break;
                }
            }
        } else if (key instanceof SimpleUserKey) {
            uid = ((SimpleUserKey) key).getId();
        }

    } catch (SQLException sqlE) {
        logger.error("SQLException while finding UID", sqlE);
        throw new SSOIdentityException("During UID lookup: " + sqlE.getMessage());

    } catch (Exception e) {
        logger.error("Exception while finding UID", e);
        throw new SSOIdentityException("During UID lookup: " + e.getMessage());

    } finally {
        closeResultSet(result);
        closeStatement(stmt);
    }

    return uid;
}

From source file:com.vmware.certificate.VMCAClient.java

/**
 * returns a PEM Encoded String from a X509Certificate
 *
 * @param certificate//from   ww w . jav a2s . c  om
 * @return
 * @throws Exception
 */
private String getEncodedStringFromCertificate(X509Certificate certificate) throws Exception {
    if (certificate == null) {
        throw new IllegalStateException("Invalid Certificate, certificate cannot be null");
    }

    String encoded = new String(Base64.encodeBase64(certificate.getEncoded()));
    StringBuffer pemencode = new StringBuffer();
    for (int x = 0; x < encoded.length(); x++) {

        if ((x > 0) && (x % 64 == 0)) {
            pemencode.append("\n");
            pemencode.append(encoded.charAt(x));
        } else {
            pemencode.append(encoded.charAt(x));

        }
    }

    return BEGIN_CERT + pemencode.toString() + END_CERT;
}

From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * @see com.otterca.persistence.dao.X509CertificateDao#put(java.security.cert
 *      .X509Certificate)/* w  w w . j  a  va  2  s. com*/
 */
public void put(X509Certificate cert) throws IOException, CertificateEncodingException {

    // TODO: we want cert's issuer to be its parent. For now certs don't
    // have parents.
    Key key = generateKey(cert);
    Entity e = new Entity(key);

    // also set parent...

    e.setProperty(CERTIFICATE, new Blob(cert.getEncoded()));
    // up to 20 octets - 40 characters
    e.setProperty(SERIAL_NUMBER, cert.getSerialNumber().toString(16));
    // up to 500 unicode characters
    e.setProperty(SUBJECT_DN, cert.getSubjectDN().getName());
    // up to 500 unicode characters
    e.setProperty(ISSUER_DN, cert.getIssuerDN().getName());
    e.setProperty(NOT_BEFORE, cert.getNotBefore());
    e.setProperty(NOT_AFTER, cert.getNotAfter());

    // RFC search criteria
    e.setProperty(COMMON_NAME, x509CertUtil.getName(cert));
    e.setProperty(FINGERPRINT, x509CertUtil.getFingerprint(cert));
    e.setProperty(CERT_HASH, x509CertUtil.getCertificateHash(cert));
    e.setProperty(ISSUER_HASH, x509CertUtil.getIHash(cert));
    e.setProperty(SUBJECT_HASH, x509CertUtil.getSHash(cert));
    // e.setProperty(AKID_HASH, x509CertUtil.getAkidHash(cert));
    e.setProperty(SKID_HASH, x509CertUtil.getSkidHash(cert));
    // e.setProperty(IANDS_HASH, x509CertUtil.getIandSHash(cert));

    // e.setProperty(EMAIL) ?...

    e.setUnindexedProperty(TRUSTED, false);
    e.setUnindexedProperty(STATUS, UNKNOWN);

    datastore.put(e);
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Generates a canonicalized JSON format of the given object, and put the signature in it. Because it mutates the
 * signed object itself, validating the signature needs a bit of work, but this enables a signature to be added
 * transparently.//from w  w  w  .  ja va 2 s .c  om
 */
protected void sign(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject sign = new JSONObject();

    List<X509Certificate> certs = getCertificateChain();
    X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA.

    PEMReader pemReader = new PEMReader(new FileReader(privateKey));
    PrivateKey key;
    try {
        key = ((KeyPair) pemReader.readObject()).getPrivate();
    } finally {
        pemReader.close();
    }

    // first, backward compatible signature for <1.433 Jenkins that forgets to flush the stream.
    // we generate this in the original names that those Jenkins understands.
    SignatureGenerator sg = new SignatureGenerator(signer, key);
    o.writeCanonical(new OutputStreamWriter(sg.getOut(), "UTF-8"));
    sg.addRecord(sign, "");

    // then the correct signature, into names that don't collide.
    OutputStream raw = new NullOutputStream();
    if (canonical != null) {
        raw = new FileOutputStream(canonical);
    }
    try {
        sg = new SignatureGenerator(signer, key);
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(sg.getOut(), raw), "UTF-8")).close();
    } finally {
        IOUtils.closeQuietly(raw);
    }
    sg.addRecord(sign, "correct_");

    // and certificate chain
    JSONArray a = new JSONArray();
    for (X509Certificate cert : certs) {
        a.add(new String(Base64.encodeBase64(cert.getEncoded())));
    }
    sign.put("certificates", a);

    o.put("signature", sign);
}

From source file:be.fedict.eid.tsl.TrustService.java

private DigitalIdentityListType createDigitalIdentityList(X509Certificate... certificates) {
    DigitalIdentityListType digitalIdentityList = this.objectFactory.createDigitalIdentityListType();
    List<DigitalIdentityType> digitalIdentities = digitalIdentityList.getDigitalId();

    for (X509Certificate certificate : certificates) {
        DigitalIdentityType digitalIdentity = this.objectFactory.createDigitalIdentityType();
        try {/*from   ww  w. j av  a  2  s . co  m*/
            digitalIdentity.setX509Certificate(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("X509 encoding error: " + e.getMessage(), e);
        }
        digitalIdentities.add(digitalIdentity);
    }

    DigitalIdentityType digitalIdentity = this.objectFactory.createDigitalIdentityType();
    digitalIdentity.setX509SubjectName(certificates[0].getSubjectX500Principal().getName());
    digitalIdentities.add(digitalIdentity);

    digitalIdentity = this.objectFactory.createDigitalIdentityType();
    byte[] skiValue = certificates[0].getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
    try {
        subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(skiValue);
    } catch (IOException e) {
        throw new RuntimeException("X509 SKI decoding error: " + e.getMessage(), e);
    }
    digitalIdentity.setX509SKI(subjectKeyIdentifierStructure.getKeyIdentifier());
    digitalIdentities.add(digitalIdentity);

    return digitalIdentityList;
}

From source file:ee.ria.xroad.common.conf.globalconf.GlobalConfImpl.java

@Override
public X509Certificate getCaCert(String instanceIdentifier, X509Certificate memberCert) throws Exception {
    if (memberCert == null) {
        throw new IllegalArgumentException("Member certificate must be present to find CA cert!");
    }/*from w  w  w. j  a va  2  s  . c o m*/

    X509CertificateHolder ch = new X509CertificateHolder(memberCert.getEncoded());

    String[] instances = instanceIdentifier != null ? new String[] { instanceIdentifier } : new String[] {};

    return getSharedParameters(instances).stream().map(p -> p.getSubjectsAndCaCerts().get(ch.getIssuer()))
            .filter(Objects::nonNull).findFirst().orElseThrow(() -> new CodedException(X_INTERNAL_ERROR,
                    "Certificate is not issued by approved " + "certification service provider."));
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Judge the Convergence's observation period of a certificate. There are four possible outcomes:
 * - The period is not yet over//  www.j av  a 2 s  . c  om
 * - The period ended sometime in the past
 * - The certificate has never been observed by Convergence
 * - The Convergence Notary didn't reply (e.g. because of a timeout or because the Notary was not able to get the server's certificate)
 * 
 * @param cert The certificate for which the period should be determined
 * @param hostPort The Hostname and port of the server from which it has been observed by the client e.g. encrypted.google.com:443 
 * @return A CertificateJudgment stating during which time interval Convergence observed "cert" for "hostPort"
 * @throws SQLException
 * @throws CertificateEncodingException
 * @throws NoSuchAlgorithmException
 */
public CertJudgment getJudgmentOfObservationPeriod(X509Certificate cert, String hostPort)
        throws SQLException, CertificateEncodingException, NoSuchAlgorithmException {

    // Calculate the certificate's SHA1-hash. It will be used as the certificate's identifier in all Convergence-related functions and SQL-tables
    String certSHA1 = Message.byteArrayToHexString(CertificateManager.SHA1(cert.getEncoded()));

    // Try to get the information about when Convergence observed "cert" for "hostPort" from the local cache (i.e. the ConvergenceCertObservations-table)
    ConvergenceCertObservation cco = getCCOFromCache(hostPort, certSHA1);

    // If that was not possible ...
    if (cco == null) {

        // ... contact a ConvergenceNotary for all ConvergenceCertObservations it made for "hostPort".
        HashSet<ConvergenceCertObservation> hostCcos = getCCOsForHostPort(hostPort);

        // If that failed also: Report that it was not possible to get a Judgment from Convergence.
        if (hostCcos == null) {
            return new CertJudgment("<crit>CONVERGENCE: NO REPLY</crit>", 0);
        }

        // In case it was possible: See if convergence has ever observed "cert"
        cco = getCCOFromList(certSHA1, hostCcos);

        // If not ...
        if (cco == null) {
            // .. create a dummy-observation for the "hostPort"/"cert"-combination. This is necessary in order to store the fact that Convergence has never observed "cert" for "hostPort" in the local cache.
            cco = new ConvergenceCertObservation(hostPort, certSHA1, new Timestamp(0), new Timestamp(0),
                    new Timestamp(System.currentTimeMillis()));

            // Add the dummy-observation in "hostCcos" so it will be added to the cache
            hostCcos.add(cco);
        }

        // Add all ConvergenceCertObservations that the server made for "hostPort" in the local cache
        storeCCOsInCache(hostCcos);

    }

    // Finally get a Judgment for the ConvergenceCertObservations made for the "hostPort"/"cert"-combination and return it
    return getJudgmentForCCO(cco);
}

From source file:be.fedict.trust.client.XKMS2Client.java

protected void validate(String trustDomain, List<X509Certificate> certificateChain,
        boolean returnRevocationData, Date validationDate, List<byte[]> ocspResponses, List<byte[]> crls,
        RevocationValuesType revocationValues, TimeStampToken timeStampToken,
        CertifiedRolesListType attributeCertificates) throws CertificateEncodingException,
        TrustDomainNotFoundException, RevocationDataNotFoundException, ValidationFailedException {
    LOG.debug("validate");
    be.fedict.trust.client.jaxb.xkms.ObjectFactory objectFactory = new be.fedict.trust.client.jaxb.xkms.ObjectFactory();
    be.fedict.trust.client.jaxb.xmldsig.ObjectFactory xmldsigObjectFactory = new be.fedict.trust.client.jaxb.xmldsig.ObjectFactory();

    ValidateRequestType validateRequest = objectFactory.createValidateRequestType();
    QueryKeyBindingType queryKeyBinding = objectFactory.createQueryKeyBindingType();
    KeyInfoType keyInfo = xmldsigObjectFactory.createKeyInfoType();
    queryKeyBinding.setKeyInfo(keyInfo);
    X509DataType x509Data = xmldsigObjectFactory.createX509DataType();
    for (X509Certificate certificate : certificateChain) {
        byte[] encodedCertificate = certificate.getEncoded();
        x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName()
                .add(xmldsigObjectFactory.createX509DataTypeX509Certificate(encodedCertificate));
    }/*from  w  w  w  .ja v  a 2  s .  c o m*/
    keyInfo.getContent().add(xmldsigObjectFactory.createX509Data(x509Data));
    validateRequest.setQueryKeyBinding(queryKeyBinding);

    /*
     * Set optional trust domain
     */
    if (null != trustDomain) {
        UseKeyWithType useKeyWith = objectFactory.createUseKeyWithType();
        useKeyWith.setApplication(XKMSConstants.TRUST_DOMAIN_APPLICATION_URI);
        useKeyWith.setIdentifier(trustDomain);
        queryKeyBinding.getUseKeyWith().add(useKeyWith);
    }

    /*
     * Add timestamp token for TSA validation
     */

    if (null != timeStampToken) {
        addTimeStampToken(validateRequest, timeStampToken);
    }

    /*
     * Add attribute certificates
     */
    if (null != attributeCertificates) {
        addAttributeCertificates(validateRequest, attributeCertificates);
    }

    /*
     * Set if used revocation data should be returned or not
     */
    if (returnRevocationData) {
        validateRequest.getRespondWith().add(XKMSConstants.RETURN_REVOCATION_DATA_URI);
    }

    /*
     * Historical validation, add the revocation data to the request
     */
    if (null != validationDate) {
        TimeInstantType timeInstant = objectFactory.createTimeInstantType();
        timeInstant.setTime(getXmlGregorianCalendar(validationDate));
        queryKeyBinding.setTimeInstant(timeInstant);

        addRevocationData(validateRequest, ocspResponses, crls, revocationValues);
    }

    ValidateResultType validateResult = this.port.validate(validateRequest);

    if (null == validateResult) {
        throw new RuntimeException("missing ValidateResult element");
    }

    checkResponse(validateResult);

    // set the optionally requested revocation data
    if (returnRevocationData) {
        for (MessageExtensionAbstractType messageExtension : validateResult.getMessageExtension()) {
            if (messageExtension instanceof RevocationDataMessageExtensionType) {
                this.revocationValues = ((RevocationDataMessageExtensionType) messageExtension)
                        .getRevocationValues();
            }
        }
        if (null == this.revocationValues) {
            LOG.error("no revocation data found");
            throw new RevocationDataNotFoundException();
        }
    }

    // store reason URIs
    this.invalidReasonURIs.clear();
    List<KeyBindingType> keyBindings = validateResult.getKeyBinding();
    for (KeyBindingType keyBinding : keyBindings) {
        StatusType status = keyBinding.getStatus();
        String statusValue = status.getStatusValue();
        LOG.debug("status: " + statusValue);
        if (XKMSConstants.KEY_BINDING_STATUS_VALID_URI.equals(statusValue)) {
            return;
        }
        for (String invalidReason : status.getInvalidReason()) {
            this.invalidReasonURIs.add(invalidReason);
        }
        throw new ValidationFailedException(invalidReasonURIs);
    }
}

From source file:org.wso2.identity.integration.test.oauth2.OAuth2ServiceAbstractIntegrationTest.java

/**
 * Convert a x509 certificate to pem format.
 *
 * @param x509Certificate Certificate in x509 format.
 * @return Certificate in pem format./*  w  ww  .j  a v a2 s  .co  m*/
 * @throws CertificateEncodingException
 */
public String convertToPem(X509Certificate x509Certificate) throws CertificateEncodingException {

    String certBegin = X509Factory.BEGIN_CERT;
    String endCert = X509Factory.END_CERT;
    String pemCert = new String(java.util.Base64.getEncoder().encode(x509Certificate.getEncoded()));
    return certBegin + pemCert + endCert;
}

From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/**
 * Generate a new key pair and request a new certificate for this key pair using EJBCA WS.
 * /* w  ww  .j  a  v  a 2 s  .  c o m*/
 * @param ejbcaWS a reference to the remote EJBCA WS
 * @param ocspSigningCacheEntry the cached OCSP signing entry backed by an OcspKeyBinding
 * @throws InvalidKeyException if the new public key can not be used to verify a string signed by the private key, because the key is wrong or 
 * the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist.
 * @throws KeyRenewalFailedException if any error occurs during signing
 */
private void renewKeyStore(EjbcaWS ejbcaWS, OcspSigningCacheEntry ocspSigningCacheEntry)
        throws InvalidKeyException, CryptoTokenOfflineException, KeyRenewalFailedException {
    //Generate the new key pair
    final int internalKeyBindingId = ocspSigningCacheEntry.getOcspKeyBinding().getId();
    try {
        internalKeyBindingMgmtSession.generateNextKeyPair(authenticationToken, internalKeyBindingId);
    } catch (InvalidAlgorithmParameterException e) {
        throw new KeyRenewalFailedException(e);
    } catch (AuthorizationDeniedException e) {
        throw new KeyRenewalFailedException(e);
    }
    //Sign the new keypair
    final X509Certificate signedCertificate = signCertificateByCa(ejbcaWS, ocspSigningCacheEntry);
    try {
        internalKeyBindingMgmtSession.importCertificateForInternalKeyBinding(authenticationToken,
                internalKeyBindingId, signedCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new KeyRenewalFailedException(e);
    } catch (CertificateImportException e) {
        throw new KeyRenewalFailedException(e);
    } catch (AuthorizationDeniedException e) {
        throw new KeyRenewalFailedException(e);
    }
    /*
     * Replace the alias and the chain at this step. If anything bad happened prior to this step the old alias and 
     * chain are still active, and no harm done. 
     */
    ocspResponseGeneratorSession.reloadOcspSigningCache();
}