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:eu.openanalytics.shinyproxy.controllers.BaseController.java

protected String resolveImageURI(String resourceURI) {
    if (resourceURI == null || resourceURI.isEmpty())
        return resourceURI;
    if (imageCache.containsKey(resourceURI))
        return imageCache.get(resourceURI);

    String resolvedValue = resourceURI;
    if (resourceURI.toLowerCase().startsWith("file://")) {
        String mimetype = URLConnection.guessContentTypeFromName(resourceURI);
        if (mimetype == null) {
            logger.warn("Cannot determine mimetype for resource: " + resourceURI);
        } else {/*w w w  . j a va  2 s  . c o  m*/
            try (InputStream input = new URL(resourceURI).openConnection().getInputStream()) {
                byte[] data = StreamUtils.copyToByteArray(input);
                String encoded = Base64.getEncoder().encodeToString(data);
                resolvedValue = String.format("data:%s;base64,%s", mimetype, encoded);
            } catch (IOException e) {
                logger.warn("Failed to convert file URI to data URI: " + resourceURI, e);
            }
        }
    }
    imageCache.put(resourceURI, resolvedValue);
    return resolvedValue;
}

From source file:io.kodokojo.brick.nexus.NexusConfigurer.java

private String encodeBasicAuth(String login, String password) {
    return "Basic " + Base64.getEncoder().encodeToString(String.format("%s:%s", login, password).getBytes());
}

From source file:org.codice.ddf.security.handler.api.BSTAuthenticationToken.java

public String getEncodedCredentials() {
    StringBuilder builder = new StringBuilder();
    builder.append(BST_PRINCIPAL);//  ww w .  ja v a 2  s . co  m
    builder.append(getPrincipal());
    builder.append(NEWLINE);
    builder.append(BST_CREDENTIALS);
    builder.append(getCredentials());
    builder.append(NEWLINE);
    builder.append(BST_REALM);
    builder.append(getRealm());
    String retVal = builder.toString();
    if (LOGGER.isTraceEnabled()) {
        String[] lines = retVal.split(NEWLINE);
        if (lines.length >= 3) {
            LOGGER.trace("Credentials String: {}\n{}\n{}", lines[0], BST_CREDENTIALS + "******", lines[2]);
        }
    }
    LOGGER.trace("Credential String: {}", retVal);
    String encodedCreds = Base64.getEncoder()
            .encodeToString(builder.toString().getBytes(StandardCharsets.UTF_8));
    LOGGER.trace("BST: {}", encodedCreds);
    return encodedCreds;
}

From source file:keywhiz.client.KeywhizClient.java

public SecretDetailResponse createSecret(String name, String description, byte[] content,
        ImmutableMap<String, String> metadata, long expiry) throws IOException {
    checkArgument(!name.isEmpty());/*w w  w. j  ava2  s  .com*/
    checkArgument(content.length > 0, "Content must not be empty");

    String b64Content = Base64.getEncoder().encodeToString(content);
    CreateSecretRequest request = new CreateSecretRequest(name, description, b64Content, metadata, expiry);
    String response = httpPost(baseUrl.resolve("/admin/secrets"), request);
    return mapper.readValue(response, SecretDetailResponse.class);
}

From source file:org.springframework.integration.samples.rest.RestHttpClientTest.java

private HttpHeaders getHttpHeadersWithUserCredentials(HttpHeaders headers) {

    String username = "SPRING";
    String password = "spring";

    String combinedUsernamePassword = username + ":" + password;
    byte[] base64Token = Base64.getEncoder().encode(combinedUsernamePassword.getBytes());
    String base64EncodedToken = new String(base64Token);
    //adding Authorization header for HTTP Basic authentication
    headers.add("Authorization", "Basic  " + base64EncodedToken);

    return headers;
}

From source file:waffle.spring.ImpersonateTests.java

/**
 * Test impersonate disabled./* w w w. j  a  v  a 2 s  .  c  o m*/
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Test
public void testImpersonateDisabled() throws IOException, ServletException {

    Assertions.assertNotEquals("Current user shouldn't be the test user prior to the test",
            MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName());
    final SimpleHttpRequest request = new SimpleHttpRequest();
    request.setMethod("GET");
    final String userHeaderValue = MockWindowsAccount.TEST_USER_NAME + ":" + MockWindowsAccount.TEST_PASSWORD;
    final String basicAuthHeader = "Basic "
            + Base64.getEncoder().encodeToString(userHeaderValue.getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", basicAuthHeader);
    final SimpleHttpResponse response = new SimpleHttpResponse();
    final RecordUserNameFilterChain filterChain = new RecordUserNameFilterChain();

    this.filter.setImpersonate(false);
    this.filter.doFilter(request, response, filterChain);

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Assertions.assertTrue(authentication.isAuthenticated(), "Test user should be authenticated");

    final Principal principal = (Principal) authentication.getPrincipal();
    assertThat(principal).isInstanceOf(WindowsPrincipal.class);
    final WindowsPrincipal windowsPrincipal = (WindowsPrincipal) principal;
    try {
        Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, filterChain.getUserName(),
                "Test user should not be impersonated");
        Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName(),
                "Impersonation context should have been reverted");
    } finally {
        windowsPrincipal.getIdentity().dispose();
    }
}

From source file:com.github.horrorho.inflatabledonkey.requests.EscrowProxyRequestFactory.java

public HttpUriRequest recover(byte[] m1, byte[] uid, byte[] tag) throws IOException {
    String uri = escrowProxyUrl + "/escrowproxy/api/recover";
    String authorization = AccessTokens.MOBILEMEAUTHTOKEN.token(dsPrsID, mmeAuthToken);

    BlobA5 blob = new BlobA5(tag, uid, m1);
    byte[] data = blob.export().array();
    String encodedMessage = Base64.getEncoder().encodeToString(data);

    String post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
            + "<plist version=\"1.0\">\n" + "<dict>\n" + "   <key>blob</key>\n" + "   <string>" + encodedMessage
            + "</string>\n" + "   <key>command</key>\n" + "   <string>RECOVER</string>\n"
            + "   <key>label</key>\n" + "   <string>com.apple.protectedcloudstorage.record</string>\n"
            + "   <key>version</key>\n" + "   <integer>1</integer>\n" + "</dict>\n" + "</plist>";
    logger.trace("-- recover() - post: {}", post);

    HttpUriRequest request = RequestBuilder.post(uri)
            .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-apple-plist")
            .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
            .addHeader(HttpHeaders.AUTHORIZATION, authorization).addHeader(headers.get(Headers.USERAGENT))
            .addHeader(headers.get(Headers.XMMECLIENTINFO))
            .setEntity(new StringEntity(post, StandardCharsets.UTF_8)).build();

    return request;
}

From source file:org.onosproject.openstacknetworkingui.OpenstackNetworkingUiMessageHandler.java

public void setRestAuthInfo(String id, String password) {
    restAuthInfo = Base64.getEncoder().encodeToString(id.concat(":").concat(password).getBytes());
}

From source file:com.joyent.manta.client.multipart.EncryptedMultipartManagerTest.java

public void canDoMultipartUpload() throws Exception {
    MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-my-key", "my value");
    metadata.put("e-my-key-1", "my value 1");
    metadata.put("e-my-key-2", "my value 2");

    MantaHttpHeaders headers = new MantaHttpHeaders();

    String path = "/user/stor/testobject";

    EncryptedMultipartUpload<TestMultipartUpload> upload = manager.initiateUpload(path, 35L, metadata, headers);

    ArrayList<String> lines = new ArrayList<>();
    lines.add("01234567890ABCDEF|}{");
    lines.add("ZYXWVUTSRQPONMLKJIHG");
    lines.add("!@#$%^&*()_+-=[]/,.<");
    lines.add(">~`?abcdefghijklmnop");
    lines.add("qrstuvxyz");

    String expected = StringUtils.join(lines, "");

    MantaMultipartUploadPart[] parts = new MantaMultipartUploadPart[5];

    for (int i = 0; i < lines.size(); i++) {
        parts[i] = manager.uploadPart(upload, i + 1, lines.get(i));
    }//from   ww w.j  a  v a  2  s. co  m

    Stream<MantaMultipartUploadTuple> partsStream = Stream.of(parts);

    manager.complete(upload, partsStream);

    TestMultipartUpload actualUpload = upload.getWrapped();

    MantaMetadata actualMetadata = MantaObjectMapper.INSTANCE.readValue(actualUpload.getMetadata(),
            MantaMetadata.class);

    Assert.assertEquals(actualMetadata, metadata, "Metadata wasn't stored correctly");

    MantaHttpHeaders actualHeaders = MantaObjectMapper.INSTANCE.readValue(actualUpload.getHeaders(),
            MantaHttpHeaders.class);

    Assert.assertEquals(actualHeaders, headers, "Headers were stored correctly");

    {
        Cipher cipher = cipherDetails.getCipher();
        byte[] iv = upload.getEncryptionState().getEncryptionContext().getCipher().getIV();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

        byte[] assumedCiphertext = cipher.doFinal(expected.getBytes(StandardCharsets.US_ASCII));
        byte[] contents = FileUtils.readFileToByteArray(upload.getWrapped().getContents());
        byte[] actualCiphertext = Arrays.copyOf(contents,
                contents.length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes());

        try {
            AssertJUnit.assertEquals(assumedCiphertext, actualCiphertext);
        } catch (AssertionError e) {
            System.err.println("expected: " + Hex.encodeHexString(assumedCiphertext));
            System.err.println("actual  : " + Hex.encodeHexString(actualCiphertext));
            throw e;
        }
    }

    EncryptionContext encryptionContext = upload.getEncryptionState().getEncryptionContext();

    MantaHttpHeaders responseHttpHeaders = new MantaHttpHeaders();
    responseHttpHeaders.setContentLength(actualUpload.getContents().length());

    final String hmacName = SupportedHmacsLookupMap
            .hmacNameFromInstance(encryptionContext.getCipherDetails().getAuthenticationHmac());

    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName);
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_IV,
            Base64.getEncoder().encodeToString(encryptionContext.getCipher().getIV()));
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, cipherDetails.getCipherId());

    MantaObjectResponse response = new MantaObjectResponse(path, responseHttpHeaders, metadata);

    CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);

    try (InputStream fin = new FileInputStream(actualUpload.getContents());
            EofSensorInputStream eofIn = new EofSensorInputStream(fin, null);
            MantaObjectInputStream objIn = new MantaObjectInputStream(response, httpResponse, eofIn);
            InputStream in = new MantaEncryptedObjectInputStream(objIn, cipherDetails, secretKey, true)) {
        String actual = IOUtils.toString(in, StandardCharsets.UTF_8);

        Assert.assertEquals(actual, expected);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.OAuthAction.java

/** ACTIONS **/
// http://localhost:8080/ciapl/external/oauth/userdialog&client_id=123123&redirect_uri=http://www.google.com

public ActionForward getUserPermission(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String clientId = request.getParameter("client_id");
    String redirectUrl = request.getParameter("redirect_uri");
    Person person = getLoggedPerson(request);

    if (!StringUtils.isEmpty(clientId) && !StringUtils.isEmpty(redirectUrl)) {
        if (person == null) {
            //redirect person to this action with client id in session

            final String cookieValue = clientId + "|" + redirectUrl;
            response.addCookie(//from  ww w  .ja v  a 2 s.c o m
                    new Cookie(OAUTH_SESSION_KEY, Base64.getEncoder().encodeToString(cookieValue.getBytes())));
            if (CoreConfiguration.casConfig().isCasEnabled()) {
                response.sendRedirect(CoreConfiguration.casConfig().getCasLoginUrl(
                        CoreConfiguration.getConfiguration().applicationUrl() + "/oauth/userdialog"));
            } else {
                response.sendRedirect(request.getContextPath() + "/oauth/userdialog");
            }
            return null;
        } else {
            return redirectToRedirectUrl(mapping, request, response, person, clientId, redirectUrl);
        }
    } else {
        if (person != null) {
            // this is the request that will recover client id from session
            final Cookie cookie = CookieReaderUtils.getCookieForName(OAUTH_SESSION_KEY, request);
            if (cookie == null) {
                logger.debug("Cookie can't be null because this a direct request from this action with cookie");
                return mapping.findForward("oauthErrorPage");
            }
            final String sessionClientId = cookie.getValue();
            if (!StringUtils.isEmpty(sessionClientId)) {
                return redirectToRedirectUrl(mapping, request, response, person, cookie);
            }
        } else {
            logger.debug("Person should not be null since this a redirect from this action with cookie");
        }
    }

    return mapping.findForward("oauthErrorPage");

}