Java Code Examples for java.util.Base64#getEncoder()

The following examples show how to use java.util.Base64#getEncoder() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: consultant   File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static StringEntity toJson(Map<String, String> entries) {
	Encoder encoder = Base64.getEncoder();
	try {
		return new StringEntity("[" + entries.entrySet().stream()
				.map(entry -> {
					String value = Optional.ofNullable(entry.getValue())
							.map(entryValue -> "\"" + encoder.encodeToString(entryValue.getBytes()) + "\"")
							.orElse("null");

					return "{\"Key\":\"" + entry.getKey() + "\",\"Value\":" + value + "}";
				})
				.collect(Collectors.joining(",")) + "]");
	}
	catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 2
@Override
@Timed(name = "dw.remoteDatawaveUserService.reload", absolute = true)
public Collection<DatawaveUser> reload(Collection<SubjectIssuerDNPair> dns) throws AuthorizationException {
    Base64.Encoder encoder = Base64.getEncoder();
    // @formatter:off
    return executeGetMethodWithAuthorizationException("admin/reloadUsers",
            // We need to base64 encode each parameter as a work-around since DNs contain
            // commas, which are used as a separator for a multi-valued parameter.
            uriBuilder -> dns.stream()
                            .map(SubjectIssuerDNPair::toString)
                            .map(s -> encoder.encodeToString(s.getBytes()))
                            .forEach(s -> uriBuilder.addParameter("dns", s)),
            httpGet -> {},
            entity -> datawaveUserListReader.readValue(entity.getContent()),
            () -> "reload " + dns);
    // @formatter:on
}
 
Example 3
Source Project: keywhiz   File: SecretTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void decodedLengthCalculates() {
  Base64.Encoder encoder = Base64.getEncoder();
  String base64 = encoder.encodeToString("31337".getBytes(UTF_8));
  assertThat(decodedLength(base64)).isEqualTo(5);

  base64 = encoder.withoutPadding().encodeToString("31337".getBytes(UTF_8));
  assertThat(decodedLength(base64)).isEqualTo(5);

  String longerBase64 = encoder.encodeToString("313373133731337".getBytes(UTF_8));
  assertThat(decodedLength(longerBase64)).isEqualTo(15);

  longerBase64 = encoder.withoutPadding().encodeToString("313373133731337".getBytes(UTF_8));
  assertThat(decodedLength(longerBase64)).isEqualTo(15);

  assertThat(decodedLength("")).isZero();
}
 
Example 4
Source Project: botbuilder-java   File: JwtTokenExtractorTests.java    License: MIT License 5 votes vote down vote up
private static String encodeCertificate(Certificate certificate) {
    try {
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] rawCrtText = certificate.getEncoded();
        return new String(encoder.encode(rawCrtText));
    } catch(CertificateEncodingException e) {
        return null;
    }
}
 
Example 5
public static String generate(String data, int height, int width) throws Exception {
    BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height);
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        MatrixToImageWriter.writeToStream(matrix, "png", out);
        Base64.Encoder encoder = Base64.getEncoder();
        String base64Image = encoder.encodeToString(out.toByteArray());
        return "data:image/png;base64," + base64Image;
    }
}
 
Example 6
Source Project: LiMe   File: LiMeMessageDigester.java    License: MIT License 5 votes vote down vote up
public static String md5(String content) {
    try {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(md5(content.getBytes()));
    } catch (Exception e) {
        return null;
    }
}
 
Example 7
private static void testDecodeIgnoredAfterPadding() throws Throwable {
    for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
        byte[][] src = new byte[][] {
            "A".getBytes("ascii"),
            "AB".getBytes("ascii"),
            "ABC".getBytes("ascii"),
            "ABCD".getBytes("ascii"),
            "ABCDE".getBytes("ascii")
        };
        Base64.Encoder encM = Base64.getMimeEncoder();
        Base64.Decoder decM = Base64.getMimeDecoder();
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        for (int i = 0; i < src.length; i++) {
            // decode(byte[])
            byte[] encoded = encM.encode(src[i]);
            encoded = Arrays.copyOf(encoded, encoded.length + 1);
            encoded[encoded.length - 1] = nonBase64;
            checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
            byte[] decoded = new byte[src[i].length];
            decM.decode(encoded, decoded);
            checkEqual(decoded, src[i], "Non-base64 char is not ignored");

            try {
                dec.decode(encoded);
                throw new RuntimeException("No IAE for non-base64 char");
            } catch (IllegalArgumentException iae) {}
        }
    }
}
 
Example 8
/**
 * Encodes string.
 * @param txt string to encode
 * @return encoded string or <code>null</code> if error encoding string
 */
public static String encode(String txt) {
  txt = StringUtils.defaultIfEmpty(txt, "");
  try {
    CRC32 crC32 = new CRC32();
    crC32.update(txt.getBytes("UTF-8"));
    long crc = crC32.getValue();
    String crctxt = String.format("%10d%s", crc, txt);
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(crctxt.getBytes("UTF-8"));
  } catch (UnsupportedEncodingException ex) {
    return null;
  }
}
 
Example 9
Source Project: fabric-sdk-java   File: HFCAClient.java    License: Apache License 2.0 5 votes vote down vote up
String getHTTPAuthCertificate(Enrollment enrollment, String method, String url, String body) throws Exception {
    Base64.Encoder b64 = Base64.getEncoder();
    String cert = b64.encodeToString(enrollment.getCert().getBytes(UTF_8));
    body = b64.encodeToString(body.getBytes(UTF_8));
    String signString;
    // Cache the version, so don't need to make info call everytime the same client is used
    if (newPayloadType == null) {
        newPayloadType = true;

        // If CA version is less than 1.4.0, use old payload
        String caVersion = info().getVersion();
        logger.info(format("CA Version: %s", caVersion));

        if (Utils.isNullOrEmpty(caVersion)) {
            newPayloadType = false;
        }

        String version = caVersion + ".";
        if (version.startsWith("1.1.") || version.startsWith("1.2.") || version.startsWith("1.3.")) {
            newPayloadType = false;
        }
    }

    if (newPayloadType) {
        url = addCAToURL(url);
        String file = b64.encodeToString(new URL(url).getFile().getBytes(UTF_8));
        signString = method + "." + file + "." + body + "." + cert;
    } else {
        signString = body + "." + cert;
    }

    byte[] signature = cryptoSuite.sign(enrollment.getKey(), signString.getBytes(UTF_8));
    return cert + "." + b64.encodeToString(signature);
}
 
Example 10
private static void testDecodeIgnoredAfterPadding() throws Throwable {
    for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
        byte[][] src = new byte[][] {
            "A".getBytes("ascii"),
            "AB".getBytes("ascii"),
            "ABC".getBytes("ascii"),
            "ABCD".getBytes("ascii"),
            "ABCDE".getBytes("ascii")
        };
        Base64.Encoder encM = Base64.getMimeEncoder();
        Base64.Decoder decM = Base64.getMimeDecoder();
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        for (int i = 0; i < src.length; i++) {
            // decode(byte[])
            byte[] encoded = encM.encode(src[i]);
            encoded = Arrays.copyOf(encoded, encoded.length + 1);
            encoded[encoded.length - 1] = nonBase64;
            checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
            byte[] decoded = new byte[src[i].length];
            decM.decode(encoded, decoded);
            checkEqual(decoded, src[i], "Non-base64 char is not ignored");

            try {
                dec.decode(encoded);
                throw new RuntimeException("No IAE for non-base64 char");
            } catch (IllegalArgumentException iae) {}
        }
    }
}
 
Example 11
Source Project: riptide   File: BasicAuthorizationProvider.java    License: MIT License 5 votes vote down vote up
public BasicAuthorizationProvider(final String username, final String password) {
    checkArgument(!username.contains(":"), "Username must not contain a colon");
    final CharsetEncoder encoder = ISO_8859_1.newEncoder();
    checkArgument(encoder.canEncode(username), "Username must be encoded in ISO-8859-1");
    checkArgument(encoder.canEncode(password), "Password must be encoded in ISO-8859-1");
    final String credentials = username + ":" + password;
    final Base64.Encoder base64 = Base64.getEncoder();
    final byte[] bytes = credentials.getBytes(ISO_8859_1);
    this.authorization = "Basic " + base64.encodeToString(bytes);
}
 
Example 12
Source Project: LiMe   File: LiMeAesCipher.java    License: MIT License 5 votes vote down vote up
public static String aesEncryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    byte[] contentBytes = content.getBytes(CHARSET);
    byte[] keyBytes = key.getBytes(CHARSET);
    byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(encryptedBytes);
}
 
Example 13
Source Project: netbeans   File: AdminKeyFile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update password hash using supplied password <code>String</code>.
 * <p/>
 * @param password New password to be set.
 */
public boolean setPassword(final String password) {
    boolean success = true;
    byte[] passwordBytes = null;
    MessageDigest md = null;
    try {
        passwordBytes = password.getBytes(PASSWORD_ENCODING);
        md = MessageDigest.getInstance(HASH_ALGORITHM);
    } catch (UnsupportedEncodingException uee) {
        success = false;
        LOGGER.log(Level.INFO,
                "Cannot convert password to bytes array: {0}",
                uee.getMessage());
    } catch (NoSuchAlgorithmException nae) {
        success = false;
        LOGGER.log(Level.INFO,
                "Cannot initialize message digest to produce {0}: {1}",
                new Object[] {HASH_ALGORITHM, nae.getMessage()});
    }
    if (success && passwordBytes != null && md != null) {
        Base64.Encoder b64Enc = Base64.getEncoder();
        md.reset();
        md.update(passwordBytes);
        String b64Hash = b64Enc.encodeToString(md.digest());
        if (b64Hash != null) {
            StringBuilder sb = new StringBuilder(
                    1 + HASH_ALGORITHM_GALSSFISH.length()
                    + 1 + b64Hash.length());
            sb.append(HASH_ALGORITHM_PREFIX);
            sb.append(HASH_ALGORITHM_GALSSFISH);
            sb.append(HASH_ALGORITHM_SUFFIX);
            sb.append(b64Hash);
            passwordHash = sb.toString();
        } else {
            success = false;
        }
    }
    return success;
}
 
Example 14
Source Project: TAC   File: EncryptionTool.java    License: MIT License 5 votes vote down vote up
/**
 * BASE64加密
 *
 * @param key
 * @return
 * @throws Exception
 */
public static String encryptBASE64(String key) {
    byte[] textByte = new byte[0];
    try {
        textByte = key.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    Base64.Encoder encoder = Base64.getEncoder();
    String encodedText = encoder.encodeToString(textByte);
    return new String(encodedText);

}
 
Example 15
private static String buildCredentials(String user, String password) {
    Base64.Encoder x = Base64.getEncoder();
    String credentials = String.join(":", user, password);
    return new String(x.encode(credentials.getBytes()));
}
 
Example 16
Source Project: j2objc   File: Base64Test.java    License: Apache License 2.0 4 votes vote down vote up
public void testRoundtrip_wrap_basic() throws Exception {
    Encoder encoder = Base64.getEncoder();
    Decoder decoder = Base64.getDecoder();
    checkRoundTrip_wrapInputStream(encoder, decoder);
}
 
Example 17
Source Project: thorntail   File: MavenSettings.java    License: Apache License 2.0 4 votes vote down vote up
public String getCredentialsBase64() {
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString((this.username + ":" + this.password).getBytes());
}
 
Example 18
private String encode(byte[] data) {
    Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(data);
}
 
Example 19
@Override
public byte[] modifyBytes(byte[] input) {
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encode(input);
}
 
Example 20
Source Project: AsciidocFX   File: SpringAppConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public Base64.Encoder base64Encoder() {
    return Base64.getEncoder();
}