Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

In this page you can find the example usage for java.util Base64 getEncoder.

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java

License:asdf

@Test
public void testEncryptedData() throws KeystoreEditor.KeystoreEditorException, IOException {
    KeystoreEditor keystoreEditor = new KeystoreEditor();
    FileInputStream fileInputStream = new FileInputStream(p7bFile);
    byte[] crtBytes = IOUtils.toByteArray(fileInputStream);
    IOUtils.closeQuietly(fileInputStream);
    keystoreEditor.addTrustedCertificate("asdf", password, "", new String(Base64.getEncoder().encode(crtBytes)),
            KeystoreEditor.PEM_TYPE, p7bFile.toString());
    List<Map<String, Object>> truststore = keystoreEditor.getTruststore();
    Assert.assertThat(truststore.size(), Is.is(1));
    Assert.assertThat(truststore.get(0).get("alias"), Is.is("asdf"));

    List<Map<String, Object>> keystore = keystoreEditor.getKeystore();
    Assert.assertThat(keystore.size(), Is.is(0));
}

From source file:org.codice.ddf.catalog.ui.util.EndpointUtil.java

private boolean handleThumbnail(Metacard metacard, Map<String, Object> result, AttributeDescriptor descriptor) {
    if (Core.THUMBNAIL.equals(descriptor.getName())) {
        if (metacard.getThumbnail() != null) {
            result.put(descriptor.getName(), Base64.getEncoder().encodeToString(metacard.getThumbnail()));
        } else {/*from w  ww .  ja va  2s.  c  o m*/
            result.put(descriptor.getName(), null);
        }
        return true;
    }
    return false;
}

From source file:com.joyent.manta.config.ConfigContext.java

/**
 * Finds a configuration value based on a key name.
 *
 * @param attribute key name to search for
 * @param config configuration context to search within
 * @return null if not found, otherwise the configuration value
 *///  ww  w  . j  a v  a2 s .  c o m
static Object getAttributeFromContext(final String attribute, final ConfigContext config) {
    switch (attribute) {
    case MapConfigContext.MANTA_URL_KEY:
    case EnvVarConfigContext.MANTA_URL_ENV_KEY:
        return config.getMantaURL();
    case MapConfigContext.MANTA_USER_KEY:
    case EnvVarConfigContext.MANTA_ACCOUNT_ENV_KEY:
        return config.getMantaUser();
    case MapConfigContext.MANTA_KEY_ID_KEY:
    case EnvVarConfigContext.MANTA_KEY_ID_ENV_KEY:
        return config.getMantaKeyId();
    case MapConfigContext.MANTA_KEY_PATH_KEY:
    case EnvVarConfigContext.MANTA_KEY_PATH_ENV_KEY:
        return config.getMantaKeyPath();
    case MapConfigContext.MANTA_TIMEOUT_KEY:
    case EnvVarConfigContext.MANTA_TIMEOUT_ENV_KEY:
        return config.getTimeout();
    case MapConfigContext.MANTA_RETRIES_KEY:
    case EnvVarConfigContext.MANTA_RETRIES_ENV_KEY:
        return config.getRetries();
    case MapConfigContext.MANTA_MAX_CONNS_KEY:
    case EnvVarConfigContext.MANTA_MAX_CONNS_ENV_KEY:
        return config.getMaximumConnections();
    case MapConfigContext.MANTA_PRIVATE_KEY_CONTENT_KEY:
    case EnvVarConfigContext.MANTA_PRIVATE_KEY_CONTENT_ENV_KEY:
        return config.getPrivateKeyContent();
    case MapConfigContext.MANTA_PASSWORD_KEY:
    case EnvVarConfigContext.MANTA_PASSWORD_ENV_KEY:
        return config.getPassword();
    case MapConfigContext.MANTA_HTTP_BUFFER_SIZE_KEY:
    case EnvVarConfigContext.MANTA_HTTP_BUFFER_SIZE_ENV_KEY:
        return config.getHttpBufferSize();
    case MapConfigContext.MANTA_HTTPS_PROTOCOLS_KEY:
    case EnvVarConfigContext.MANTA_HTTPS_PROTOCOLS_ENV_KEY:
        return config.getHttpsProtocols();
    case MapConfigContext.MANTA_HTTPS_CIPHERS_KEY:
    case EnvVarConfigContext.MANTA_HTTPS_CIPHERS_ENV_KEY:
        return config.getHttpsCipherSuites();
    case MapConfigContext.MANTA_NO_AUTH_KEY:
    case EnvVarConfigContext.MANTA_NO_AUTH_ENV_KEY:
        return config.noAuth();
    case MapConfigContext.MANTA_NO_NATIVE_SIGS_KEY:
    case EnvVarConfigContext.MANTA_NO_NATIVE_SIGS_ENV_KEY:
        return config.disableNativeSignatures();
    case MapConfigContext.MANTA_TCP_SOCKET_TIMEOUT_KEY:
    case EnvVarConfigContext.MANTA_TCP_SOCKET_TIMEOUT_ENV_KEY:
        return config.getTcpSocketTimeout();
    case MapConfigContext.MANTA_CONNECTION_REQUEST_TIMEOUT_KEY:
    case EnvVarConfigContext.MANTA_CONNECTION_REQUEST_TIMEOUT_ENV_KEY:
        return config.getConnectionRequestTimeout();
    case MapConfigContext.MANTA_EXPECT_CONTINUE_TIMEOUT_KEY:
    case EnvVarConfigContext.MANTA_EXPECT_CONTINUE_TIMEOUT_ENV_KEY:
        return config.getExpectContinueTimeout();
    case MapConfigContext.MANTA_CLIENT_ENCRYPTION_ENABLED_KEY:
    case EnvVarConfigContext.MANTA_CLIENT_ENCRYPTION_ENABLED_ENV_KEY:
        return config.isClientEncryptionEnabled();
    case MapConfigContext.MANTA_VERIFY_UPLOADS_KEY:
    case EnvVarConfigContext.MANTA_VERIFY_UPLOADS_ENV_KEY:
        return config.verifyUploads();
    case MapConfigContext.MANTA_UPLOAD_BUFFER_SIZE_KEY:
    case EnvVarConfigContext.MANTA_UPLOAD_BUFFER_SIZE_ENV_KEY:
        return config.getUploadBufferSize();
    case MapConfigContext.MANTA_SKIP_DIRECTORY_DEPTH_KEY:
    case EnvVarConfigContext.MANTA_SKIP_DIRECTORY_DEPTH_ENV_KEY:
        return config.getSkipDirectoryDepth();
    case MapConfigContext.MANTA_DOWNLOAD_CONTINUATIONS_KEY:
    case EnvVarConfigContext.MANTA_DOWNLOAD_CONTINUATIONS_ENV_KEY:
        return config.downloadContinuations();
    case MapConfigContext.MANTA_PERMIT_UNENCRYPTED_DOWNLOADS_KEY:
    case EnvVarConfigContext.MANTA_PERMIT_UNENCRYPTED_DOWNLOADS_ENV_KEY:
        return config.permitUnencryptedDownloads();
    case MapConfigContext.MANTA_ENCRYPTION_KEY_ID_KEY:
    case EnvVarConfigContext.MANTA_ENCRYPTION_KEY_ID_ENV_KEY:
        return config.getEncryptionKeyId();
    case MapConfigContext.MANTA_ENCRYPTION_ALGORITHM_KEY:
    case EnvVarConfigContext.MANTA_ENCRYPTION_ALGORITHM_ENV_KEY:
        return config.getEncryptionAlgorithm();
    case MapConfigContext.MANTA_ENCRYPTION_AUTHENTICATION_MODE_KEY:
    case EnvVarConfigContext.MANTA_ENCRYPTION_AUTHENTICATION_MODE_ENV_KEY:
        return config.getEncryptionAuthenticationMode();
    case MapConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_PATH_KEY:
    case EnvVarConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_PATH_ENV_KEY:
        return config.getEncryptionPrivateKeyPath();
    case MapConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_BYTES_KEY:
        return config.getEncryptionPrivateKeyBytes();
    case MapConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_BYTES_BASE64_KEY:
    case EnvVarConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_BYTES_BASE64_ENV_KEY:
        return Base64.getEncoder().encode(config.getEncryptionPrivateKeyBytes());
    default:
        return null;
    }
}

From source file:org.mycore.common.MCRUtils.java

/**
 * @deprecated use {@link Base64} instead
 *///from  w  w w .  j  av  a 2s .  c  o  m
@Deprecated
public static String toBase64String(byte[] data) {
    return Base64.getEncoder().encodeToString(data);
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private String getPEMCertificateFromServer(String host) {
    HttpsURLConnection connection = null;
    try {//from w  w w. j a  v  a2 s  .c  om
        URL url = new URL(host);

        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(hostnameVerifier);
        connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats());
        connection.connect();

        java.security.cert.Certificate[] cert = connection.getServerCertificates();
        connection.disconnect();

        byte[] by = ((X509Certificate) cert[0]).getEncoded();
        if (by.length != 0) {
            return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT;
        }
    } catch (MalformedURLException e) {
        if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) {
            logger.error("A MalformedURLException occurred: ", e);
        }
    } catch (IOException e) {
        short code = ConnectionManager.GENERAL_EXCEPTION;
        if (e instanceof java.net.ConnectException) {
            code = ConnectionManager.CONNECTION_EXCEPTION;
        } else if (e instanceof java.net.UnknownHostException) {
            code = ConnectionManager.UNKNOWN_HOST_EXCEPTION;
        }
        if (!informConnectionManager(code) || code == -1) {
            logger.error("An IOException occurred: ", e);
        }
    } catch (CertificateEncodingException e) {
        logger.error("A CertificateEncodingException occurred: ", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:alfio.util.TemplateResource.java

public static ImageData fillWithImageData(FileBlobMetadata m, byte[] image) {

    Map<String, String> attributes = m.getAttributes();
    if (attributes.containsKey(FileBlobMetadata.ATTR_IMG_WIDTH)
            && attributes.containsKey(FileBlobMetadata.ATTR_IMG_HEIGHT)) {
        final int width = Integer.parseInt(attributes.get(FileBlobMetadata.ATTR_IMG_WIDTH));
        final int height = Integer.parseInt(attributes.get(FileBlobMetadata.ATTR_IMG_HEIGHT));
        //in the PDF the image can be maximum 300x150
        int resizedWidth = width;
        int resizedHeight = height;
        if (resizedHeight > 150) {
            resizedHeight = 150;/*from ww  w  .  ja va2 s  .co m*/
            resizedWidth = width * resizedHeight / height;
        }
        if (resizedWidth > 300) {
            resizedWidth = 300;
            resizedHeight = height * resizedWidth / width;
        }
        return new ImageData(
                "data:" + m.getContentType() + ";base64," + Base64.getEncoder().encodeToString(image),
                resizedWidth, resizedHeight);
    }
    return new ImageData(null, null, null);
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void getAccessTokenWrongClientIdHeaderTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();//from  w  w w  . ja va  2 s  . co  m

    ExternalApplication externalApp = new ExternalApplication();
    externalApp.setAuthor(user1);
    externalApp.setName("Test External Application");
    externalApp.setDescription("This is a test external application");
    externalApp.setRedirectUrl("http://test.url/callback");

    ApplicationUserSession applicationUserSession = new ApplicationUserSession();
    applicationUserSession.setCode("fenixedu");

    ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1,
            externalApp);
    applicationUserAuthorization.addSession(applicationUserSession);
    externalApp.addApplicationUserAuthorization(applicationUserAuthorization);

    String clientSecret = "fenixedu:fenixedu";
    req.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8)));
    req.addParameter(REDIRECT_URI, externalApp.getRedirectUrl());
    req.addParameter(CODE, applicationUserSession.getCode());
    req.addParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);
        Assert.assertEquals("must return status BAD_REQUEST", 400, res.getStatus());
    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:SdkUnitTests.java

@Test
public void GetDiagnosticLogsTest() {

    byte[] fileBytes = null;
    try {//from  w w w  .ja  v  a  2  s .  c o m
        //  String currentDir = new java.io.File(".").getCononicalPath();

        String currentDir = System.getProperty("user.dir");

        Path path = Paths.get(currentDir + SignTest1File);
        fileBytes = Files.readAllBytes(path);
    } catch (IOException ioExcp) {
        Assert.assertEquals(null, ioExcp);
    }

    // create an envelope to be signed
    EnvelopeDefinition envDef = new EnvelopeDefinition();
    envDef.setEmailSubject("DownLoadEnvelopeDocumentsTest");
    envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    doc.setName("TestFile.pdf");
    doc.setDocumentId("1");

    List<Document> docs = new ArrayList<Document>();
    docs.add(doc);
    envDef.setDocuments(docs);

    // Add a recipient to sign the document
    Signer signer = new Signer();
    signer.setEmail(UserName);
    String name = "Pat Developer";
    signer.setName(name);
    signer.setRecipientId("1");

    // this value represents the client's unique identifier for the signer
    String clientUserId = "2939";
    signer.setClientUserId(clientUserId);

    // Create a SignHere tab somewhere on the document for the signer to sign
    SignHere signHere = new SignHere();
    signHere.setDocumentId("1");
    signHere.setPageNumber("1");
    signHere.setRecipientId("1");
    signHere.setXPosition("100");
    signHere.setYPosition("100");

    List<SignHere> signHereTabs = new ArrayList<SignHere>();
    signHereTabs.add(signHere);
    Tabs tabs = new Tabs();
    tabs.setSignHereTabs(signHereTabs);
    signer.setTabs(tabs);

    // Above causes issue
    envDef.setRecipients(new Recipients());
    envDef.getRecipients().setSigners(new ArrayList<Signer>());
    envDef.getRecipients().getSigners().add(signer);

    // send the envelope (otherwise it will be "created" in the Draft folder
    envDef.setStatus("sent");

    try {

        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(BaseUrl);

        String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey);
        apiClient.addDefaultHeader("X-DocuSign-Authentication", creds);
        Configuration.setDefaultApiClient(apiClient);

        AuthenticationApi authApi = new AuthenticationApi();
        LoginInformation loginInfo = authApi.login();

        Assert.assertNotSame(null, loginInfo);
        Assert.assertNotNull(loginInfo.getLoginAccounts());
        Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0);
        List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
        Assert.assertNotNull(loginAccounts.get(0).getAccountId());

        String accountId = loginInfo.getLoginAccounts().get(0).getAccountId();

        DiagnosticsApi diagApi = new DiagnosticsApi();

        DiagnosticsSettingsInformation diagSettings = new DiagnosticsSettingsInformation();
        diagSettings.setApiRequestLogging("true");
        diagApi.updateRequestLogSettings(diagSettings);

        EnvelopesApi envelopesApi = new EnvelopesApi();
        EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);

        Assert.assertNotNull(envelopeSummary);
        Assert.assertNotNull(envelopeSummary.getEnvelopeId());

        System.out.println("EnvelopeSummary: " + envelopeSummary);

        byte[] pdfBytes = envelopesApi.getDocument(accountId, envelopeSummary.getEnvelopeId(), "combined");

        try {

            File pdfFile = File.createTempFile("ds_", "pdf", null);
            FileOutputStream fos = new FileOutputStream(pdfFile);
            fos.write(pdfBytes);

            // show the PDF
            Desktop.getDesktop().open(pdfFile);

        } catch (Exception ex) {
            Assert.fail("Could not create pdf File");

        }

        ApiRequestLogsResult logsList = diagApi.listRequestLogs();
        String requestLogId = logsList.getApiRequestLogs().get(0).getRequestLogId();
        byte[] diagBytes = diagApi.getRequestLog(requestLogId);
        try {

            File diagFile = File.createTempFile("ds_", "txt", null);
            FileOutputStream fos = new FileOutputStream(diagFile);
            fos.write(diagBytes);

            // show the PDF
            Desktop.getDesktop().open(diagFile);

        } catch (Exception ex) {
            Assert.fail("Could not create diag log File");

        }

    } catch (ApiException ex) {
        System.out.println("Exception: " + ex);
        Assert.assertEquals(null, ex);
    }

}

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.SPNEGOLoginModuleTestCase.java

/**
 * Implements testing of SPNEGO authentication workflow with configurable parameters such supported mechanisms, tokens,
 * expected continuation and checking responses.
 *
 * @param uri                  test URI which is protected by SPNEGO/Kerberos authentication.
 * @param mechTypesOids        array of supported mechanisms by the client in decreasing preference order (favorite choice first)
 * @param initMechToken        initial token (optimistic mechanism token) - token for the first of supported mechanisms
 * @param responseToken        token which is used in the second round when the server requests using Kerberos as a mechanism for
 *                             authentication
 * @param continuationExpected flag which says that we expect server to require the second round of authentication (i.e.
 *                             server asks to send Kerberos token)
 * @param successExpected      flag which says that we expect the authentication finishes with success (in the first or second
 *                             round - which depends on the continuationExpected param)
 *//* ww  w .  j av  a  2  s .  c o  m*/
private void assertSpnegoWorkflow(URI uri, final String[] mechTypesOids, final byte[] initMechToken,
        final byte[] responseToken, boolean continuationExpected, boolean successExpected) throws IOException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        final HttpGet httpGet = new HttpGet(uri);
        HttpResponse response = httpClient.execute(httpGet);
        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        assertHttpHeader(response, HEADER_WWW_AUTHENTICATE, "Negotiate");
        EntityUtils.consume(response.getEntity());

        byte[] spnegoInitToken = KerberosTestUtils.generateSpnegoTokenInit(initMechToken, mechTypesOids);
        httpGet.setHeader(HEADER_AUTHORIZATION,
                "Negotiate " + Base64.getEncoder().encodeToString(spnegoInitToken));

        response = httpClient.execute(httpGet);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(
                    "Negotiate response in HTTP header:\n" + KerberosTestUtils.dumpNegotiateHeader(response));
        }

        if (continuationExpected) {
            assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
            // Assume that the server selects Kerberos v5 mechanism - OID: '1 2 840 113554 1 2 2'
            assertHttpHeader(response, HEADER_WWW_AUTHENTICATE, HEADER_VAL_SELECT_KERBEROS_MECH);
            EntityUtils.consume(response.getEntity());

            byte[] spnegoRespToken = KerberosTestUtils.generateSpnegoTokenResp(responseToken);
            httpGet.setHeader(HEADER_AUTHORIZATION,
                    "Negotiate " + Base64.getEncoder().encodeToString(spnegoRespToken));
            response = httpClient.execute(httpGet);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Negotiate response in HTTP header:\n"
                        + KerberosTestUtils.dumpNegotiateHeader(response));
            }
        }
        if (successExpected) {
            assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            assertEquals("Unexpected response body", SimpleSecuredServlet.RESPONSE_BODY,
                    EntityUtils.toString(response.getEntity()));
        } else {
            assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
            assertHttpHeader(response, HEADER_WWW_AUTHENTICATE,
                    // if this is the first round we expect the REJECTED response.
                    "Negotiate" + (continuationExpected ? "" : " oQcwBaADCgEC"));
        }
    }
}

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Generate random chars string of given <code>length</code>.
 * /*from  ww  w . j ava 2  s  . c om*/
 * @param length
 * @return a random string of given <code>length</code>.
 */
public static String generateRandomString(int length) {
    int blen = ((length + 3) / 4) * 3; // base 64: 3 bytes = 4 chars
    byte[] bval = new byte[blen];
    rnd.nextBytes(bval);
    // change '/' and '\' with '$' in case the string is used as file name
    return new String(Base64.getEncoder().encode(bval), 0, length).replace('/', '$');
}