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:marshalsec.Jackson.java

@Override
@Args(minArgs = 1, args = { "cmd", "args..." }, defaultArgs = {
        MarshallerBase.defaultExecutable }, noTest = true) // this should only work with < JDK 8u45 OR if upstream xalan is present (set upstreamXalan=true)
// this is likely the original gadget reported for Jackson bug #1599
// also described by https://adamcaudill.com/2017/10/04/exploiting-jackson-rce-cve-2017-7525/
public Object makeTemplates(UtilFactory uf, String... args) throws Exception {
    Object tpl = TemplatesUtil.createTemplatesImpl(args);
    byte[][] bytecodes = (byte[][]) Reflections.getFieldValue(tpl, "_bytecodes");
    Map<String, String> values = new LinkedHashMap<>();
    String base64 = Base64.getEncoder().encodeToString(bytecodes[0]);
    values.put("transletBytecodes", writeArray(quoteString(base64)));
    values.put("transletName", quoteString("foo"));
    values.put("outputProperties", "{}");
    if (Boolean.parseBoolean(System.getProperty("upstreamXalan", "false"))) {
        return writeObject("org.apache.xalan.xsltc.trax.TemplatesImpl", values);
    }/*from  ww  w .  j  av  a2s.c o  m*/
    return writeObject("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl", values);
}

From source file:org.onehippo.forge.content.pojo.model.BinaryValue.java

/**
 * Converts the {@code data} in {@code mediaType} and {@code charset} to a <code>data:</code> URL string.
 * @param data binary data in byte array
 * @param mediaType media type//from   w w w .j  a v  a  2  s. c  o m
 * @param charset character set
 * @return a <code>data:</code> URL string converted from the given {@code data}.
 */
public static String toDataURI(byte[] data, final String mediaType, final String charset) {
    int size = (data == null ? 0 : data.length);
    StringBuilder sbTemp = new StringBuilder(size + 20);

    sbTemp.append("data:");

    if (StringUtils.isNotBlank(mediaType)) {
        sbTemp.append(mediaType);
    }

    if (StringUtils.isNotBlank(charset)) {
        sbTemp.append(';').append(charset);
    }

    sbTemp.append(";base64");
    sbTemp.append(',');
    sbTemp.append(Base64.getEncoder().encodeToString(data));

    return sbTemp.toString();
}

From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticatorTest.java

@Test(description = "This method tests the behaviour of the authenticate method in BasicAuthenticator with "
        + "in-valid credentials", dependsOnMethods = { "testAuthenticateWithValidCredentials" })
public void testAuthenticateWithWrongCredentials() throws IllegalAccessException {
    String encodedString = new String(
            Base64.getEncoder().encode((ADMIN_USER + ":test" + ADMIN_USER).getBytes()));
    mimeHeaders = new MimeHeaders();
    bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(BASIC_HEADER + encodedString);
    coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    AuthenticationInfo authenticationInfo = basicAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
            "For a wrong credentials authentication succeeded.");

    encodedString = new String(Base64.getEncoder().encode((ADMIN_USER).getBytes()));
    mimeHeaders = new MimeHeaders();
    bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(BASIC_HEADER + encodedString);
    coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    authenticationInfo = basicAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
            "For a request with missing password authentication succeeded.");
}

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

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

    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 userName = TeamworkDB.getString(rs, "userName");
            String entryUUID = TeamworkDB.getString(rs, "userId");
            String userFirstName = TeamworkDB.getString(rs, "userFirstName");
            String userLastName = TeamworkDB.getString(rs, "userLastName");
            String userEmail = TeamworkDB.getString(rs, "userEmail");
            String companyId = TeamworkDB.getString(rs, "companyName");
            String userImage = TeamworkDB.getString(rs, "userImage");

            // Normalize user and company names
            userName = userName.replace('.', '_');
            companyId = companyId(companyId);

            // Make sure the name is unique
            if (userNames.containsValue(userName)) {
                int suffix = 2;
                while (userNames.containsValue(userName + suffix)) {
                    suffix++;
                }
                userName = userName + suffix;
            }
            userNames.put(entryUUID, userName);

            ldif.append("dn: uid=").append(userName).append(",").append(peopleDN).append(NL);
            ldif.append("objectclass: top").append(NL);
            ldif.append("objectclass: organizationalPerson").append(NL);
            ldif.append("objectclass: inetOrgPerson").append(NL);
            ldif.append("objectclass: maritimeResource").append(NL);
            ldif.append("ou: people").append(NL);
            ldif.append("mrn: ").append("urn:mrn:mc:user:").append(companyId).append(":").append(userName)
                    .append(NL);
            ldif.append("uid: ").append(userName).append(NL);
            ldif.append("cn: ").append(userFirstName).append(" ").append(userLastName).append(NL);
            ldif.append("givenName: ").append(userFirstName).append(NL);
            ldif.append("sn: ").append(userLastName).append(NL);
            ldif.append("mail: ").append(userEmail).append(NL);
            ldif.append("userpassword:: ").append("e1NTSEF9QTM3TkF4K0l1Z25UZS8vTHJPbWFOczdZeGVNSk4xeVQ=")
                    .append(NL);
            ldif.append("entryUUID: ").append(new UUID(Long.parseLong(entryUUID), 0L).toString()).append(NL);

            if (includePhotos) {
                byte[] jpg = fetchJPEG(userImage);
                if (jpg != null) {
                    wrapLine(ldif, "jpegPhoto:: ", Base64.getEncoder().encodeToString(jpg));
                }
            }

            ldif.append(NL);

            index++;
        }
        rs.close();
        System.out.println(String.format("Fetched %d users in %d ms", index, 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:no.kantega.useradmin.controls.CreateInitialUserController.java

private synchronized void createInitialUserToken() {
    if (!this.tokenFile.exists()) {
        byte[] bytes = new byte[16];
        random.nextBytes(bytes);/*  www .  java  2s  .c  om*/

        try (FileOutputStream out = new FileOutputStream(tokenFile)) {
            tokenFile.getParentFile().mkdirs();
            IOUtils.write(Base64.getEncoder().encode(bytes), out);
        } catch (IOException e) {
            throw new RuntimeException("Error writing token to file", e);
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.gep.a3es.A3ESDegreeProcess.java

public void initialize() {
    base64Hash = new String(Base64.getEncoder().encode((user + ":" + password).getBytes()));
    JSONArray processes = invoke(webResource().path(API_PROCESS));
    JSONObject json = (JSONObject) processes.iterator().next();
    id = (String) json.get("id");
    String name = (String) json.get("name");
    if (acefIndex.containsKey(name)) {
        degree = Degree.readBySigla(acefIndex.get(name));
        JSONArray forms = invoke(webResource().path(API_FORM).queryParam("processId", id));
        for (Object object : forms) {
            JSONObject form = (JSONObject) object;
            if ("Guio para a auto-avaliao".equals(form.get("name"))) {
                formId = (String) form.get("id");
            }//from   www. jav  a2s.  c  o m
        }
        if (formId == null) {
            throw new DomainException("Process " + name + " has no auto-evaluation form.");
        }
    } else {
        throw new DomainException("Not recognized ACEF code: " + name);
    }
}

From source file:org.springframework.security.crypto.scrypt.SCryptPasswordEncoder.java

private String encodePart(byte[] part) {
    return Utf8.decode(Base64.getEncoder().encode(part));
}

From source file:keywhiz.client.KeywhizClient.java

public SecretDetailResponse updateSecret(String name, boolean descriptionPresent, String description,
        boolean contentPresent, byte[] content, boolean metadataPresent, ImmutableMap<String, String> metadata,
        boolean expiryPresent, long expiry) throws IOException {
    checkArgument(!name.isEmpty());/*  w ww.j  a v a2  s .  c  o  m*/

    String b64Content = Base64.getEncoder().encodeToString(content);
    PartialUpdateSecretRequestV2 request = PartialUpdateSecretRequestV2.builder()
            .descriptionPresent(descriptionPresent).description(description).contentPresent(contentPresent)
            .content(b64Content).metadataPresent(metadataPresent).metadata(metadata)
            .expiryPresent(expiryPresent).expiry(expiry).build();
    String response = httpPost(baseUrl.resolve(format("/admin/secrets/%s/partialupdate", name)), request);
    return mapper.readValue(response, SecretDetailResponse.class);
}

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

/**
 * Provides one-way (irreversible) encryption of a provided string.
 *
 * @param plainText - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param instance - The security instance to utilize
 * @param iterations - The number of times the value should be re-encrypted
 * @param encoding - The text encoding/* w  ww.j  a  va  2  s  . co  m*/
 * @return The encrypted string
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String encryptText(final String plainText, final String salt, final String instance,
        final int iterations, final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String plainText, final String salt, final String algorithm, final String instance, final int iterations, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", plainText);
        DEBUGGER.debug("Value: {}", salt);
        DEBUGGER.debug("Value: {}", instance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String response = null;

    try {
        MessageDigest md = MessageDigest.getInstance(instance);
        md.reset();
        md.update(salt.getBytes(encoding));
        byte[] input = md.digest(plainText.getBytes(encoding));

        for (int x = 0; x < iterations; x++) {
            md.reset();
            input = md.digest(input);
        }

        response = Base64.getEncoder().encodeToString(input);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    }

    return response;
}