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.syncany.plugins.webdav.WebdavTransferManager.java

private String formatCertificate(X509Certificate cert) {
    try {//from w w  w. jav  a2 s. c  o  m
        CipherUtil.enableUnlimitedStrength(); // Dirty!

        String checksumMd5 = formatChecksum(createChecksum(cert.getEncoded(), "MD5"));
        String checksumSha1 = formatChecksum(createChecksum(cert.getEncoded(), "SHA1"));
        String checksumSha256 = formatChecksum(createChecksum(cert.getEncoded(), "SHA256"));

        StringBuilder sb = new StringBuilder();

        sb.append(String.format("Owner: %s\n", cert.getSubjectDN().getName()));
        sb.append(String.format("Issuer: %s\n", cert.getIssuerDN().getName()));
        sb.append(String.format("Serial number: %d\n", cert.getSerialNumber()));
        sb.append(String.format("Valid from %s until: %s\n", cert.getNotBefore().toString(),
                cert.getNotAfter().toString()));
        sb.append("Certificate fingerprints:\n");
        sb.append(String.format(" MD5:  %s\n", checksumMd5));
        sb.append(String.format(" SHA1: %s\n", checksumSha1));
        sb.append(String.format(" SHA256: %s", checksumSha256));

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

private String getCertFingerPrint(X509Certificate cert) {
    try {//w  ww.j  a  va 2 s.c om
        String mdAlg;
        if (cert.getSigAlgName().toUpperCase().startsWith("SHA")) {
            mdAlg = "SHA";
        } else {
            mdAlg = "MD5";
        }
        byte[] encCertInfo = cert.getEncoded();
        MessageDigest md = MessageDigest.getInstance(mdAlg);
        byte[] digest = md.digest(encCertInfo);
        return toHexString(digest);
    } catch (Exception e) {
        return e.toString();
    }
}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.impl.EnrollmentServiceImpl.java

/**
 * This method prepares the wap-provisioning file by including relevant certificates etc.
 *
 * @param binarySecurityToken     - CSR from device
 * @param wapProvisioningFilePath - File path of wap-provisioning file
 * @return - base64 encoded final wap-provisioning file as a String
 * @throws CertificateGenerationException
 * @throws org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WAPProvisioningException
 *//*from  w  w  w  .  j  a  v a  2 s.  com*/
private String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
        String headerBst)
        throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException {
    String rootCertEncodedString;
    String signedCertEncodedString;
    X509Certificate signedCertificate;
    String provisioningXmlString;
    CertificateManagementServiceImpl certMgtServiceImpl = CertificateManagementServiceImpl.getInstance();
    Base64 base64Encoder = new Base64();
    try {
        X509Certificate rootCACertificate = (X509Certificate) certMgtServiceImpl.getCACertificate();
        rootCertEncodedString = base64Encoder.encodeAsString(rootCACertificate.getEncoded());

        signedCertificate = certMgtServiceImpl.getSignedCertificateFromCSR(binarySecurityToken);
        signedCertEncodedString = base64Encoder.encodeAsString(signedCertificate.getEncoded());

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        domFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        DocumentBuilder builder;

        builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(wapProvisioningFilePath);
        NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM);
        Node caCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment.CA_CERTIFICATE_POSITION);

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        caCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase());
        //Adding encoded CA certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes();
        Node rootCertNode = rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
        rootCertNode.setTextContent(rootCertEncodedString);

        if (log.isDebugEnabled()) {
            log.debug("Root certificate: " + rootCertEncodedString);
        }

        Node signedCertificatePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase());

        //Adding encoded signed certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
        Node clientEncodedNode = clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");

        clientEncodedNode.setTextContent(signedCertEncodedString);
        if (log.isDebugEnabled()) {
            log.debug("Signed certificate: " + signedCertEncodedString);
        }

        //Adding domainName to wap-provisioning xml.
        Node domainPosition = wapParm.item(PluginConstants.CertificateEnrolment.DOMAIN_POSITION);
        NamedNodeMap domainAttribute = domainPosition.getAttributes();
        Node domainNode = domainAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        domainNode.setTextContent(domain);

        //Adding Next provisioning service URL to wap-provisioning xml.
        Node syncmlServicePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_ADDR_POSITION);
        NamedNodeMap syncmlServiceAttribute = syncmlServicePosition.getAttributes();
        Node syncmlServiceNode = syncmlServiceAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        syncmlServiceNode.setTextContent(provisioningURL);

        // Adding user name auth token to wap-provisioning xml.
        Node userNameAuthPosition = wapParm
                .item(PluginConstants.CertificateEnrolment.APPAUTH_USERNAME_POSITION);
        NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes();
        Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        String userName = getRequestedUser(headerBst);
        //CacheEntry cacheEntry = (CacheEntry) DeviceUtil.getCacheEntry(headerBst);
        // String userName = cacheEntry.getUsername();
        authNameNode.setTextContent(userName);
        DeviceUtil.removeTokenEntry(headerBst);
        String password = DeviceUtil.generateRandomToken();
        Node passwordAuthPosition = wapParm
                .item(PluginConstants.CertificateEnrolment.APPAUTH_PASSWORD_POSITION);
        NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes();
        Node authPasswordNode = appSrvPasswordAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        authPasswordNode.setTextContent(password);
        String requestSecurityTokenResponse = SyncmlCredentialUtil.generateRST(userName, password);
        DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName);

        // Get device polling frequency from the tenant Configurations.
        Node numberOfFirstRetries = wapParm
                .item(PluginConstants.CertificateEnrolment.POLLING_FREQUENCY_POSITION);
        NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
        Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        pollValue.setTextContent(pollingFrequency);
        provisioningXmlString = convertDocumentToString(document);
    } catch (ParserConfigurationException e) {
        throw new WAPProvisioningException("Problem occurred while creating configuration request", e);
    } catch (CertificateEncodingException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while encoding certificates.", e);
    } catch (SAXException e) {
        throw new WAPProvisioningException("Error occurred while parsing wap-provisioning.xml file.", e);
    } catch (TransformerException e) {
        throw new WAPProvisioningException("Error occurred while transforming wap-provisioning.xml file.", e);
    } catch (IOException e) {
        throw new WAPProvisioningException("Error occurred while getting wap-provisioning.xml file.", e);
    } catch (SyncmlMessageFormatException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while generating password hash value.", e);
    } catch (KeystoreException e) {
        throw new CertificateGenerationException("CA certificate cannot be generated.", e);
    }
    return base64Encoder.encodeAsString(provisioningXmlString.getBytes());
}

From source file:pl.psnc.synat.wrdz.realm.db.WrdzUserDatabaseHandler.java

/**
 * Fetches the username of user using the specified certificate.
 * //from ww w .j  av a  2 s  .c  o  m
 * @param x509Certificate
 *            certificate of the user who is to be authenticated.
 * @return name of the user possessing the certificate.
 */
public String findUsername(X509Certificate x509Certificate) {
    String username = null;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        String certificate = StringUtils.newStringUtf8(Base64.encodeBase64(x509Certificate.getEncoded()));
        connection = getConnection();
        statement = connection.prepareStatement(usernameCertQuery);
        statement.setString(1, certificate);
        rs = statement.executeQuery();
        if (rs.next()) {
            username = rs.getString(1);
        }
    } catch (SQLException e) {
        logger.log(Level.SEVERE, "Cannot validate user " + username + ", exception: " + e.toString());
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Cannot validate user", e);
        }
    } catch (CertificateEncodingException e) {
        logger.log(Level.SEVERE, "Invalid certificate data retrieved.");
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Cannot encode certificate data properly", e);
        }
    } catch (LoginException e) {
        logger.log(Level.SEVERE, "Invalid user " + username);
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Cannot validate user", e);
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected error " + e.getMessage());
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Unexpected error", e);
        }
    } finally {
        close(connection, statement, rs);
    }
    return username;
}

From source file:test.unit.be.fedict.trust.MemoryCertificateRepositoryTest.java

@Test
public void trustPointFoundByDifferentCryptoProvider() throws Exception {

    // setup/*from www  .jav a2  s  .  co  m*/
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    KeyPair keyPair = TrustTestUtils.generateKeyPair();
    X509Certificate trustPoint = TrustTestUtils.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
            notAfter);
    LOG.debug("trust point certificate impl class: " + trustPoint.getClass().getName());

    MemoryCertificateRepository testedInstance = new MemoryCertificateRepository();
    testedInstance.addTrustPoint(trustPoint);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(trustPoint.getEncoded()));
    LOG.debug("certificate impl class: " + certificate.getClass().getName());

    // operate
    assertFalse(certificate.getClass().equals(trustPoint.getClass()));
    assertTrue(testedInstance.isTrustPoint(certificate));
}

From source file:com.microsoft.azure.batch.CertificateOperations.java

/**
 * Creates a new {@link Certificate} from .cer format data in stream.
 *
 * @param certStream The certificate data in .cer format.
 * @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
 * @throws BatchErrorException Exception thrown from REST call
 * @throws IOException Exception thrown from serialization/deserialization
 * @throws CertificateException Exception thrown on parsing errors
 * @throws NoSuchAlgorithmException Exception thrown if the X509 provider is not registered in the security provider list.
 *///from w  w w.  j av a 2s  . c  om
public void createCertificate(InputStream certStream, Iterable<BatchClientBehavior> additionalBehaviors)
        throws BatchErrorException, IOException, CertificateException, NoSuchAlgorithmException {
    CertificateFactory x509CertFact = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) x509CertFact.generateCertificate(certStream);

    CertificateAddParameter addParam = new CertificateAddParameter();
    addParam.withCertificateFormat(CertificateFormat.CER);
    addParam.withThumbprintAlgorithm(SHA1_CERTIFICATE_ALGORITHM);
    addParam.withThumbprint(getThumbPrint(cert));
    addParam.withData(Base64.encodeBase64String(cert.getEncoded()));

    createCertificate(addParam, additionalBehaviors);
}

From source file:io.hops.hopsworks.common.security.OpensslOperations.java

@Lock(LockType.WRITE)
public void validateCertificate(X509Certificate certificate, PKI.CAType caType) throws IOException {
    File tmpCertFile = File.createTempFile("cert-", ".pem");
    try (FileWriter fw = new FileWriter(tmpCertFile, false)) {
        fw.write(X509Factory.BEGIN_CERT);
        fw.write("\n");
        fw.write(b64encoder.encodeToString(certificate.getEncoded()));
        fw.write("\n");
        fw.write(X509Factory.END_CERT);/*from  w ww.j av  a  2 s.com*/
        fw.flush();

        List<String> commands = new ArrayList<>();
        commands.add(OPENSSL);
        commands.add("verify");
        commands.add("-CAfile");
        commands.add(pki.getChainOfTrustFilePath(caType).toString());
        commands.add("-crl_check");
        commands.add("-CRLfile");
        commands.add(pki.getCACRLPath(caType).toString());
        commands.add(tmpCertFile.getAbsolutePath());
        executeCommand(commands, false);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex);
    } finally {
        tmpCertFile.delete();
    }
}

From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java

@Nullable
private String getAppSignature() {
    // Cache this so we don't need to calculate the signature on every request
    if (mAppSignature != null) {
        return mAppSignature;
    }//from   w ww.j ava 2 s. c om

    try {
        // Get signatures for the package
        Signature[] sigs = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_SIGNATURES).signatures;

        // There should only be one signature, anything else is suspicious
        if (sigs == null || sigs.length > 1 || sigs.length == 0) {
            Log.w(TAG, "Either 0 or >1 signatures, returning null");
            return null;
        }

        byte[] certBytes = sigs[0].toByteArray();

        InputStream input = new ByteArrayInputStream(certBytes);
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(input);

        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(cert.getEncoded());

        // Build a hex string of the SHA1 Digest
        StringBuilder hexString = new StringBuilder();
        for (byte aPublicKey : publicKey) {
            // Convert each byte to hex
            String appendString = Integer.toHexString(0xFF & aPublicKey);
            if (appendString.length() == 1) {
                hexString.append("0");
            }

            // Convert to upper case and add ":" separators so it matches keytool output
            appendString = appendString.toUpperCase() + ":";

            hexString.append(appendString);
        }

        // Convert to string, chop off trailing colon
        String signature = hexString.toString();
        if (signature.endsWith(":")) {
            signature = signature.substring(0, signature.length() - 1);
        }

        // Set and return
        mAppSignature = signature;
        return mAppSignature;
    } catch (Exception e) {
        Log.e(TAG, "getSignature", e);
    }

    return null;
}

From source file:org.wso2.carbon.certificate.mgt.jaxrs.api.impl.CertificateMgtServiceImpl.java

@POST
@Path("/sign-csr")
@Produces(MediaType.TEXT_PLAIN)/*from   w w  w . j a v a  2 s . c o m*/
@Consumes(MediaType.TEXT_PLAIN)
public Response getSignedCertFromCSR(@HeaderParam("If-Modified-Since") String ifModifiedSince,
        String binarySecurityToken) {
    Message message = new Message();
    X509Certificate signedCert;
    String singedCertificate;
    Base64 base64 = new Base64();
    CertificateGenerator certificateGenerator = new CertificateGenerator();
    try {
        if (certificateGenerator.getSignedCertificateFromCSR(binarySecurityToken) == null) {
            message.setErrorMessage("Error occurred while signing the CSR.");
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message).build();
        } else {
            signedCert = certificateGenerator.getSignedCertificateFromCSR(binarySecurityToken);
            singedCertificate = base64.encodeToString(signedCert.getEncoded());
            return Response.status(Response.Status.OK).entity(singedCertificate).build();
        }
    } catch (KeystoreException e) {
        String msg = "Error occurred while fetching certificate.";
        log.error(msg, e);
        throw new UnexpectedServerErrorException(
                new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
    } catch (CertificateEncodingException e) {
        String msg = "Error occurred while encoding the certificate.";
        log.error(msg, e);
        throw new UnexpectedServerErrorException(
                new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
    }
}