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

private void addCertChain(KeystoreEditor keystoreEditor)
        throws KeystoreEditor.KeystoreEditorException, IOException {
    FileInputStream fileInputStream = new FileInputStream(chainFile);
    byte[] crtBytes = IOUtils.toByteArray(fileInputStream);
    IOUtils.closeQuietly(fileInputStream);
    keystoreEditor.addPrivateKey("asdf", password, "", Base64.getEncoder().encodeToString(crtBytes),
            KeystoreEditor.PEM_TYPE, chainFile.toString());
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public String requestASToken(Registration registration, String[] adds) throws IOException {
    String asToken = null;/*from   w  w  w.  j  av  a  2 s .c  o  m*/

    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    //
    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    // Request
    // POST /iam-services/0.1/oidc/am/token HTTP/1.1
    URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION);

    HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection();
    httpConTokenAcquisition.setDoOutput(true);
    httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConTokenAcquisition.setRequestProperty("Accept", "application/json");
    // httpConTokenAcquisition.setRequestProperty("Authorization",
    // "Basic Base64(<c_id>:<c_secret>");
    String auth = registration.c_id + ":" + registration.c_secret;
    String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes()));
    httpConTokenAcquisition.setRequestProperty("Authorization", authb);
    httpConTokenAcquisition.setRequestMethod("POST");

    String requestBodyTokenAcquisition = "grant_type=client_credentials";
    if (adds == null || adds.length == 0) {
        // no additions
    } else {
        if (adds.length % 2 == 0) {
            for (int i = 0; i < (adds.length - 1); i += 2) {
                requestBodyTokenAcquisition += "&";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8");
                requestBodyTokenAcquisition += "=";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8");
            }
        } else {
            log.warn(
                    "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds));
        }
    }

    OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream();
    outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes());
    outTokenAcquisition.close();

    int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode();
    log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": "
            + responseCodeoutTokenAcquisition);

    if (responseCodeoutTokenAcquisition == 200) {
        // everything ok
        InputStream isTA = httpConTokenAcquisition.getInputStream();
        byte[] bisTA = getBytesFromInputStream(isTA);
        String jsonResponseTA = new String(bisTA);
        log.info(jsonResponseTA);

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisTA);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode access_token = actualObj.get("access_token");
        if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) {
            log.error("access_token: " + access_token);
        } else {
            // ok so far
            // access_token provides a JWT structure
            // see Understanding JWT
            // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html

            log.info("access_token: " + access_token);
            // http://jwt.io/

            // TODO verify signature (e.g., use Jose4J)

            // Note: currently we assume signature is fine.. we just fetch
            // "as_token"
            String[] decAT = access_token.textValue().split("\\.");
            if (decAT == null || decAT.length != 3) {
                log.error("Cannot build JWT tripple structure for " + access_token);
            } else {
                assert (decAT.length == 3);
                // JWT structure
                // decAT[0]; // header
                // decAT[1]; // payload
                // decAT[2]; // signature
                String decAT1 = new String(Base64.getDecoder().decode(decAT[1]));
                JsonParser jpas = factory.createParser(decAT1);
                JsonNode payload = mapper.readTree(jpas);
                JsonNode as_token = payload.get("as_token");
                if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) {
                    log.error("as_token: " + as_token);
                } else {
                    log.info("as_token: " + as_token);
                    asToken = as_token.textValue();
                }
            }
        }

    } else {
        // error
        InputStream error = httpConTokenAcquisition.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }

    httpConTokenAcquisition.disconnect();

    return asToken;
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdminTest.java

@Test
public void testCreateLocalEntryString() throws Exception {
    String encodeThisString = "aPretendXmlRegistryPackage";
    String metacardId = "createdMetacardId";
    String base64EncodedString = Base64.getEncoder().encodeToString(encodeThisString.getBytes());

    Metacard metacard = getTestMetacard();

    when(registryTransformer.transform(any(InputStream.class))).thenReturn(metacard);
    when(federationAdminService.addRegistryEntry(metacard)).thenReturn(metacardId);

    String createdMetacardId = federationAdmin.createLocalEntry(base64EncodedString);

    assertThat(createdMetacardId, is(equalTo(metacardId)));
    verify(registryTransformer).transform(any(InputStream.class));
    verify(federationAdminService).addRegistryEntry(metacard);
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Base64 encodes a given string/*  w  w w.  j  av  a2 s .co  m*/
 *
 * @param text - The text to base64 encode
 * @return The base64-encoded string
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String base64Encode(final String text) throws SecurityException {
    final String methodName = PasswordUtils.CNAME + "#base64Encode(final String text) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", text);
    }

    return Base64.getEncoder().encodeToString(text.getBytes());
}

From source file:com.jrestless.aws.gateway.handler.GatewayRequestObjectHandlerIntTest.java

private void testBase64Encoding(String resoruce) {
    DefaultGatewayRequest request = new DefaultGatewayRequestBuilder().httpMethod("GET").resource(resoruce)
            .build();/*from   ww  w. j a va 2 s. com*/
    GatewayResponse response = handler.handleRequest(request, context);
    assertTrue(response.isIsBase64Encoded());
    assertEquals(Base64.getEncoder().encodeToString("test".getBytes()), response.getBody());
    assertFalse(response.getHeaders().containsKey(GatewayBinaryResponseFilter.HEADER_BINARY_RESPONSE));
}

From source file:com.serphacker.serposcope.scraper.google.scraper.GoogleScraper.java

protected String buildUule(String location) {
    if (location == null || location.isEmpty()) {
        return null;
    }/*from   w ww.j ava2  s  .  com*/

    byte[] locationArray = location.getBytes();
    if (locationArray.length + 1 > UULE_LENGTH.length()) {
        LOG.warn("unencodable uule location, length is too long {}", location);
        return null;
    }

    return "w+CAIQICI" + UULE_LENGTH.charAt(locationArray.length)
            + Base64.getEncoder().encodeToString(locationArray);
}

From source file:net.e2.bw.idreg.db2ldif.Db2Ldif.java

/**
 * Generate LDIF for all groups//from   w  w w.j  a va  2  s.  c  o  m
 * @param db the database
 * @param ldif the LDIF file to append to
 */
@SuppressWarnings("all")
private void importGroups(TeamworkDB db, StringBuilder ldif, Map<String, String> userNames) {
    long t0 = System.currentTimeMillis();
    String sql = loadResourceText("/groups.sql");

    Map<String, StringBuilder> groups = new LinkedHashMap<>();

    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = db.getConnection();

        stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();
        int index = 0;
        while (rs.next()) {
            String userId = TeamworkDB.getString(rs, "userId");
            String companyName = TeamworkDB.getString(rs, "companyName");
            String entryUUID = TeamworkDB.getString(rs, "companyId");

            String companyId = companyId(companyName);

            StringBuilder g = groups.get(companyName);
            if (!groups.containsKey(companyName)) {
                g = new StringBuilder();
                groups.put(companyName, g);

                Company company = companyData.get(companyId);

                g.append("dn: cn=").append(companyName).append(",").append(groupsDN).append(NL);
                g.append("objectClass: top").append(NL);
                g.append("objectClass: groupOfUniqueNames").append(NL);
                g.append("objectclass: maritimeResource").append(NL);
                g.append("objectclass: maritimeOrganization").append(NL);
                g.append("cn: ").append(companyName).append(NL);
                g.append("uid: ").append(companyId).append(NL);
                g.append("mrn: ").append("urn:mrn:mc:org:").append(companyId.toLowerCase().replace(' ', '_'))
                        .append(NL);
                g.append("entryUUID: ").append(new UUID(Long.parseLong(entryUUID), 0L).toString()).append(NL);

                if (company != null) {
                    if (company.country.length() == 2) {
                        g.append("c: ").append(company.country).append(NL);
                    }
                    g.append("labeledURI: ").append(company.www).append(NL);
                    g.append("description: ").append(company.description).append(NL);
                    if (includePhotos && company.logo != null) {
                        byte[] img = fetchPhoto(getClass().getResourceAsStream(company.logo), null);
                        if (img != null) {
                            wrapLine(g, "photo:: ", Base64.getEncoder().encodeToString(img));
                        }
                    }
                }
            }

            String userName = userNames.get(userId);
            g.append("uniqueMember: uid=").append(userName).append(",").append(peopleDN).append(NL);

            index++;
        }
        rs.close();

        groups.values().stream().forEach(g -> ldif.append(g).append(NL));

        System.out.println(
                String.format("Fetched %d groups in %d ms", groups.size(), System.currentTimeMillis() - t0));

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception ex) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ex) {
        }
    }

}

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

@Test
public void testTokenTypeWrongAccessTokenInHeader() {

    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();/*  w  w w.  j ava 2  s.  c  om*/

    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");
    externalApp.addScopes(externalApplicationScope);

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

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

    String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret();
    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 OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();
        final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject();

        Assert.assertTrue("response must be a valid json and have" + ACCESS_TOKEN + " field",
                token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0);

        Assert.assertTrue("response must be a valid json and have " + TOKEN_TYPE + " field",
                token.has(TOKEN_TYPE) && token.get(TOKEN_TYPE).getAsString().length() > 0);

        String accessToken = token.get(ACCESS_TOKEN).getAsString() + "fenixedu";
        String tokenType = token.get(TOKEN_TYPE).getAsString();

        Response result = target("bennu-oauth").path("test").path("test-scope").request()
                .header(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken).get(Response.class);

        Assert.assertEquals("request must fail", 401, result.getStatus());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:com.simiacryptus.util.io.HtmlNotebookOutput.java

@javax.annotation.Nonnull
@Override//ww  w . ja  v a 2s  . c o m
public String image(@Nullable final BufferedImage rawImage, final String caption) throws IOException {
    if (null == rawImage)
        return "";
    new ByteArrayOutputStream();
    @javax.annotation.Nonnull
    final String thisImage = UUID.randomUUID().toString().substring(0, 8);
    @javax.annotation.Nonnull
    final File file = new File(getResourceDir(), "img" + thisImage + ".png");
    @javax.annotation.Nonnull
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ImageIO.write(rawImage, "png", buffer);
    final String pngSrc = Base64.getEncoder().encodeToString(buffer.toByteArray());
    if (pngSrc.length() < 4 * 1024) {
        return "<img src='data:image/png;base64," + pngSrc + "' alt='" + caption + "'/>";
    } else {
        @Nullable
        final BufferedImage stdImage = Util.resize(rawImage);
        if (stdImage != rawImage) {
            ImageIO.write(rawImage, "png", new File(getResourceDir(), "raw" + thisImage + ".png"));
        }
        ImageIO.write(stdImage, "png", file);
        return "<img src='etc/" + file.getName() + "' alt='" + caption + "'/>";
    }
}

From source file:org.codice.ddf.security.idp.client.AssertionConsumerService.java

@GET
@Path("/metadata")
@Produces("application/xml")
public Response retrieveMetadata() throws WSSecurityException, CertificateEncodingException {
    X509Certificate issuerCert = findCertificate(systemCrypto.getSignatureAlias(),
            systemCrypto.getSignatureCrypto());
    X509Certificate encryptionCert = findCertificate(systemCrypto.getEncryptionAlias(),
            systemCrypto.getEncryptionCrypto());

    String hostname = SystemBaseUrl.getHost();
    String port = SystemBaseUrl.getPort();
    String rootContext = SystemBaseUrl.getRootContext();

    String entityId = String.format("https://%s:%s%s/saml", hostname, port, rootContext);

    String logoutLocation = String.format("https://%s:%s%s/saml/logout", hostname, port, rootContext);
    String assertionConsumerServiceLocation = String.format("https://%s:%s%s/saml/sso", hostname, port,
            rootContext);/*w  ww.  ja v a2 s  .  c  om*/

    EntityDescriptor entityDescriptor = SamlProtocol.createSpMetadata(entityId,
            Base64.getEncoder().encodeToString(issuerCert.getEncoded()),
            Base64.getEncoder().encodeToString(encryptionCert.getEncoded()), logoutLocation,
            assertionConsumerServiceLocation, assertionConsumerServiceLocation);

    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    return Response.ok(DOM2Writer.nodeToString(OpenSAMLUtil.toDom(entityDescriptor, doc, false))).build();
}