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.jboss.as.test.integration.security.common.Utils.java

public static String hash(String target, String algorithm, Coding coding) {
    MessageDigest md = null;/* w w  w.j a  v a  2s .co  m*/
    try {
        md = MessageDigest.getInstance(algorithm);
    } catch (Exception e) {
        e.printStackTrace();
    }
    byte[] bytes = target.getBytes();
    byte[] byteHash = md.digest(bytes);

    String encodedHash = null;

    switch (coding) {
    case BASE_64:
        encodedHash = Base64.getEncoder().encodeToString(byteHash);
        break;
    case HEX:
        encodedHash = toHex(byteHash);
        break;
    default:
        throw new IllegalArgumentException("Unsuported coding:" + coding.name());
    }

    return encodedHash;
}

From source file:org.apache.syncope.core.spring.security.Encryptor.java

public String encode(final String value, final CipherAlgorithm cipherAlgorithm)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    String encodedValue = null;/*from   ww w .  j a  v a 2  s  .  c om*/

    if (value != null) {
        if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
            final byte[] cleartext = value.getBytes(StandardCharsets.UTF_8);

            final Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            encodedValue = new String(Base64.getEncoder().encode(cipher.doFinal(cleartext)));
        } else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
            encodedValue = BCrypt.hashpw(value, BCrypt.gensalt());
        } else {
            encodedValue = getDigester(cipherAlgorithm).digest(value);
        }
    }

    return encodedValue;
}

From source file:software.coolstuff.springframework.owncloud.service.impl.AbstractOwncloudServiceTest.java

private ResponseActions prepareRestRequest(RestRequest request) throws MalformedURLException {
    MockRestServiceServer server = this.server;
    if (request.getServer() != null) {
        server = request.getServer();//from  w w  w.ja  v  a 2  s . com
    }
    ResponseActions responseActions = server.expect(requestToWithPrefix(request.getUrl()))
            .andExpect(method(request.getMethod()));
    if (StringUtils.isNotBlank(request.getBasicAuthentication())) {
        responseActions.andExpect(header(HttpHeaders.AUTHORIZATION, request.getBasicAuthentication()));
    } else {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        responseActions
                .andExpect(header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(
                        (authentication.getName() + ":" + authentication.getCredentials()).getBytes())));
    }
    return responseActions;
}

From source file:org.pentaho.di.pan.PanIT.java

@Test
public void testTransExecutionFromWithinProvidedZip() throws Exception {

    long now = System.currentTimeMillis();

    String testZipRelativePath = "test-ktr.zip";
    String testZipFullPath = getRelativePathKTR(testZipRelativePath);

    String testKTRWithinZip = "Pan.ktr";

    String logFileRelativePath = testZipRelativePath + "." + now + ".log";
    String logFileFullPath = testZipFullPath + "." + now + ".log";

    File zipFile = null;//  ww  w.j av a  2 s.  c  o  m

    try {
        zipFile = new File(getClass().getResource(testZipRelativePath).toURI());
        String base64Zip = Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(zipFile));

        Pan.main(new String[] { "/file:" + testKTRWithinZip, "/level:Basic", "/logfile:" + logFileFullPath,
                "/zip:" + base64Zip });

    } catch (SecurityException e) {
        // All OK / expected: SecurityException is purposely thrown when Pan triggers System.exitJVM()

        // get log file contents
        String logFileContent = getFileContentAsString(logFileRelativePath);

        // use FINISHED_PROCESSING_ERROR_COUNT_REGEX to get execution error count
        int errorCount = parseErrorCount(logFileContent);

        assertTrue(!logFileContent.contains(FAILED_TO_INITIALIZE_ERROR_PATTERN) && errorCount == 0);

        Result result = Pan.getCommandExecutor().getResult();
        assertNotNull(result);
        assertEquals(CommandExecutorCodes.Pan.SUCCESS.getCode(), result.getExitStatus());

    } finally {
        zipFile = null;

        // sanitize
        File f = new File(logFileFullPath);
        if (f != null && f.exists()) {
            f.deleteOnExit();
        }
    }
}

From source file:io.kodokojo.bdd.stage.HttpUserSupport.java

public String generateHelloWebSocketMessage(UserInfo user) {
    String aggregateCredentials = String.format("%s:%s", user.getUsername(), user.getPassword());
    String encodedCredentials = Base64.getEncoder().encodeToString(aggregateCredentials.getBytes());
    return "{\n" + "  \"entity\": \"user\",\n" + "  \"action\": \"authentication\",\n" + "  \"data\": {\n"
            + "    \"authorization\": \"Basic " + encodedCredentials + "\"\n" + "  }\n" + "}";
}

From source file:ddf.security.samlp.SimpleSign.java

public void signUriString(String queryParams, UriBuilder uriBuilder) throws SignatureException {
    X509Certificate[] certificates = getSignatureCertificates();
    String sigAlgo = getSignatureAlgorithmURI(certificates[0]);
    PrivateKey privateKey = getSignaturePrivateKey();
    java.security.Signature signature = initSign(certificates[0], privateKey);

    String requestToSign;/*from w  w  w  .  ja  v  a2 s  .c  o m*/
    try {
        requestToSign = queryParams + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }

    try {
        signature.update(requestToSign.getBytes(UTF_8));
    } catch (java.security.SignatureException | UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }

    byte[] signatureBytes;
    try {
        signatureBytes = signature.sign();
    } catch (java.security.SignatureException e) {
        throw new SignatureException(e);
    }

    try {
        uriBuilder.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, UTF_8));
        uriBuilder.queryParam(SSOConstants.SIGNATURE,
                URLEncoder.encode(Base64.getEncoder().encodeToString(signatureBytes), UTF_8));
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }
}

From source file:cloudlens.engine.CL.java

public Object post(String urlString, String jsonData) throws IOException {
    final URL url = new URL(urlString);

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*w w  w.  j  a v  a 2s  .  c  om*/
    conn.setDoInput(true);
    final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString);
    if (matcher.find()) {
        final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + encoding);
    }
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestMethod("POST");

    try (final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
        wr.write(jsonData);
        wr.flush();
    }
    try (final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        String line;
        final StringBuilder sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        final String s = StringEscapeUtils.escapeEcmaScript(sb.toString());
        final Object log = engine.eval(
                "CL.log=JSON.parse(\"" + s + "\").hits.hits.map(function (entry) { return entry._source})");
        return log;
    }
}

From source file:org.wso2.carbon.analytics.data.commons.utils.AnalyticsCommonUtils.java

/**
 * This method is used to generate an UUID from the target table name to make sure that it is a compact
 * name that can be fitted in all the supported RDBMSs. For example, Oracle has a table name
 * length of 30. So we must translate source table names to hashed strings, which here will have
 * a very low probability of clashing.//from  w  w  w .j ava 2s  . co  m
 */
public static String generateTableUUID(String tableName) {
    try {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(byteOut);
        /* we've to limit it to 64 bits */
        dout.writeInt(tableName.hashCode());
        dout.close();
        byteOut.close();
        String result = Base64.getEncoder().encodeToString(byteOut.toByteArray());
        result = result.replace('=', '_');
        result = result.replace('+', '_');
        result = result.replace('/', '_');
        /* a table name must start with a letter */
        return ANALYTICS_USER_TABLE_PREFIX + result;
    } catch (IOException e) {
        /* this will never happen */
        throw new RuntimeException(e);
    }
}

From source file:org.elasticsearch.upgrades.FullClusterRestartIT.java

public void testSearch() throws Exception {
    int count;/*from w ww .  j  av  a2  s .  c o  m*/
    if (runningAgainstOldCluster) {
        XContentBuilder mappingsAndSettings = jsonBuilder();
        mappingsAndSettings.startObject();
        {
            mappingsAndSettings.startObject("settings");
            mappingsAndSettings.field("number_of_shards", 1);
            mappingsAndSettings.field("number_of_replicas", 0);
            mappingsAndSettings.endObject();
        }
        {
            mappingsAndSettings.startObject("mappings");
            mappingsAndSettings.startObject("doc");
            mappingsAndSettings.startObject("properties");
            {
                mappingsAndSettings.startObject("string");
                mappingsAndSettings.field("type", "text");
                mappingsAndSettings.endObject();
            }
            {
                mappingsAndSettings.startObject("dots_in_field_names");
                mappingsAndSettings.field("type", "text");
                mappingsAndSettings.endObject();
            }
            {
                mappingsAndSettings.startObject("binary");
                mappingsAndSettings.field("type", "binary");
                mappingsAndSettings.field("store", "true");
                mappingsAndSettings.endObject();
            }
            mappingsAndSettings.endObject();
            mappingsAndSettings.endObject();
            mappingsAndSettings.endObject();
        }
        mappingsAndSettings.endObject();
        client().performRequest("PUT", "/" + index, Collections.emptyMap(),
                new StringEntity(Strings.toString(mappingsAndSettings), ContentType.APPLICATION_JSON));

        count = randomIntBetween(2000, 3000);
        byte[] randomByteArray = new byte[16];
        random().nextBytes(randomByteArray);
        indexRandomDocuments(count, true, true, i -> {
            return JsonXContent.contentBuilder().startObject().field("string", randomAlphaOfLength(10))
                    .field("int", randomInt(100)).field("float", randomFloat())
                    // be sure to create a "proper" boolean (True, False) for the first document so that automapping is correct
                    .field("bool", i > 0 && supportsLenientBooleans ? randomLenientBoolean() : randomBoolean())
                    .field("field.with.dots", randomAlphaOfLength(10))
                    .field("binary", Base64.getEncoder().encodeToString(randomByteArray)).endObject();
        });
        refresh();
    } else {
        count = countOfIndexedRandomDocuments();
    }

    Map<String, String> params = new HashMap<>();
    params.put("timeout", "2m");
    params.put("wait_for_status", "green");
    params.put("wait_for_no_relocating_shards", "true");
    params.put("wait_for_events", "languid");
    Map<String, Object> healthRsp = toMap(client().performRequest("GET", "/_cluster/health/" + index, params));
    logger.info("health api response: {}", healthRsp);
    assertEquals("green", healthRsp.get("status"));
    assertFalse((Boolean) healthRsp.get("timed_out"));

    assertBasicSearchWorks(count);
    assertAllSearchWorks(count);
    assertBasicAggregationWorks();
    assertRealtimeGetWorks();
    assertStoredBinaryFields(count);
}

From source file:ostepu.file.fileUtils.java

/**
 * kodiert einen String als Base64//  w  w w  . j  a va  2 s  .  c om
 *
 * @param content der zu kodierende Text
 * @return der Base64 kodierte Text
 */
public static String encodeBase64(String content) {
    Encoder enc = Base64.getEncoder();
    return new String(enc.encode(content.getBytes()));
}