java.util.Base64.Encoder Java Examples

The following examples show how to use java.util.Base64.Encoder. 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 File: HttpUtils.java    From consultant with 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
Source File: Base64Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testEncoder_encodeByteBuffer() {
    Encoder encoder = Base64.getEncoder();

    byte[] emptyByteArray = new byte[0];
    ByteBuffer emptyByteBuffer = ByteBuffer.wrap(emptyByteArray);
    ByteBuffer emptyEncodedBuffer = encoder.encode(emptyByteBuffer);
    assertEquals(emptyByteBuffer, emptyEncodedBuffer);
    assertNotSame(emptyByteArray, emptyEncodedBuffer);

    // Test the two types of byte buffer.
    byte[] input = "abcefghi".getBytes(US_ASCII);
    String expectedString = "YWJjZWZnaGk=";
    byte[] expectedBytes = expectedString.getBytes(US_ASCII);

    ByteBuffer inputBuffer = ByteBuffer.allocate(input.length);
    inputBuffer.put(input);
    inputBuffer.position(0);
    testEncoder_encodeByteBuffer(encoder, inputBuffer, expectedBytes);

    inputBuffer = ByteBuffer.allocateDirect(input.length);
    inputBuffer.put(input);
    inputBuffer.position(0);
    testEncoder_encodeByteBuffer(encoder, inputBuffer, expectedBytes);
}
 
Example #3
Source File: TestBase64Golden.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #4
Source File: TestBase64Golden.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #5
Source File: TestBase64Golden.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #6
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static void checkWrapOutputStreamConsistentWithEncode(Encoder encoder)
        throws Exception {
    final Random random = new Random(32176L);

    // one large write(byte[]) of the whole input
    WriteStrategy allAtOnce = (bytes, out) -> out.write(bytes);
    checkWrapOutputStreamConsistentWithEncode(encoder, allAtOnce);

    // many calls to write(int)
    WriteStrategy byteWise = (bytes, out) -> {
        for (byte b : bytes) {
            out.write(b);
        }
    };
    checkWrapOutputStreamConsistentWithEncode(encoder, byteWise);

    // intermixed sequences of write(int) with
    // write(byte[],int,int) of various lengths.
    WriteStrategy mixed = (bytes, out) -> {
        int[] writeLengths = { -10, -5, -1, 0, 1, 1, 2, 2, 3, 10, 100 };
        int p = 0;
        while (p < bytes.length) {
            int l = writeLengths[random.nextInt(writeLengths.length)];
            l = Math.min(l, bytes.length - p);
            if (l >= 0) {
                out.write(bytes, p, l);
                p += l;
            } else {
                l = Math.min(-l, bytes.length - p);
                for (int i = 0; i < l; ++i) {
                    out.write(bytes[p + i]);
                }
                p += l;
            }
        }
    };
    checkWrapOutputStreamConsistentWithEncode(encoder, mixed);
}
 
Example #7
Source File: TestBase64Golden.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #8
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that writing to a wrap()ping OutputStream produces the same
 * output on the wrapped stream as {@link Encoder#encode(byte[])}.
 */
private static void checkWrapOutputStreamConsistentWithEncode(Encoder encoder,
        WriteStrategy writeStrategy) throws IOException {
    Random random = new Random(32176L);
    // Test input needs to be at least 1024 bytes to test filling
    // up the write(int) buffer of Base64OutputStream.
    byte[] plain = new byte[1234];
    random.nextBytes(plain);
    byte[] encodeResult = encoder.encode(plain);
    ByteArrayOutputStream wrappedOutputStream = new ByteArrayOutputStream();
    try (OutputStream plainOutputStream = encoder.wrap(wrappedOutputStream)) {
        writeStrategy.write(plain, plainOutputStream);
    }
    assertArrayEquals(encodeResult, wrappedOutputStream.toByteArray());
}
 
Example #9
Source File: JavaImgConverter.java    From easyCV with Apache License 2.0 5 votes vote down vote up
/**
	 * bufferedImage转base64
	 * @param format -格式(jpg,png等等)
	 * @return
	 * @throws IOException
	 */
	public static String bufferedImage2Base64(BufferedImage image, String format) throws IOException {
		Encoder encoder = Base64.getEncoder();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();// 字节流
//		baos.reset();
		ImageIO.write(image, format, baos);// 写出到字节流
		byte[] bytes=baos.toByteArray();
		// 编码成base64
		String jpg_base64 = encoder.encodeToString(bytes);
		return jpg_base64;
	}
 
Example #10
Source File: TestBase64Golden.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #11
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks round-trip encoding/decoding of {@code plain}.
 *
 * @param plain an ASCII String
 * @return the Base64-encoded value of the ASCII codepoints from {@code plain}
 */
private static String encodeFromAscii(Encoder encoder, Decoder decoder, String plain)
        throws Exception {
    String encoded = encoder.encodeToString(plain.getBytes(US_ASCII));
    String decoded = decodeToAscii(decoder, encoded);
    assertEquals(plain, decoded);
    return encoded;
}
 
Example #12
Source File: TestBase64Golden.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #13
Source File: TestBase64Golden.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #14
Source File: TestBase64Golden.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #15
Source File: TestBase64Golden.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #16
Source File: AESCipher.java    From AESCipher-Java with 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);
	Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(encryptedBytes);
}
 
Example #17
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static void testEncoder_encodeByteBuffer(
        Encoder encoder, ByteBuffer inputBuffer, byte[] expectedBytes) {
    assertEquals(0, inputBuffer.position());
    assertEquals(inputBuffer.remaining(), inputBuffer.limit());
    int inputLength = inputBuffer.remaining();

    ByteBuffer encodedBuffer = encoder.encode(inputBuffer);

    assertEquals(inputLength, inputBuffer.position());
    assertEquals(0, inputBuffer.remaining());
    assertEquals(inputLength, inputBuffer.limit());
    assertEquals(0, encodedBuffer.position());
    assertEquals(expectedBytes.length, encodedBuffer.remaining());
    assertEquals(expectedBytes.length, encodedBuffer.limit());
}
 
Example #18
Source File: CommonUtil.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a random 32 byte value encoded as a Base64 string (44 characters).
 *
 * @return
 */
public static String getRandomKey() {
    byte[] buffer = new byte[32];
    random.nextBytes(buffer);
    Encoder enc = Base64.getEncoder();
    return enc.encodeToString(buffer);
}
 
Example #19
Source File: JwtManager.java    From onlyoffice-confluence with GNU Affero General Public License v3.0 5 votes vote down vote up
public String createToken(JSONObject payload) throws Exception {
    JSONObject header = new JSONObject();
    header.put("alg", "HS256");
    header.put("typ", "JWT");

    Encoder enc = Base64.getUrlEncoder();

    String encHeader = enc.encodeToString(header.toString().getBytes("UTF-8")).replace("=", "");
    String encPayload = enc.encodeToString(payload.toString().getBytes("UTF-8")).replace("=", "");
    String hash = calculateHash(encHeader, encPayload);

    return encHeader + "." + encPayload + "." + hash;
}
 
Example #20
Source File: TestBase64Golden.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #21
Source File: Base64Test.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * Test a variety of different input lengths and check that our calculated length
 * matches the actual length (which includes padding).
 */
@Test
public void testLen() {
    Encoder enc = Base64.getEncoder();
    
    for (int l=1; l<=256; l++) {
        byte[] src   = new byte[l];
        for (int i=0; i<src.length; i++) {
            src[i] = (byte)i; // doesn't really matter
        }

        // check that our calculated length equals the actual encoded length
        assertEquals(calcCharLength(src.length), enc.encodeToString(src).length());
    }
}
 
Example #22
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Decoder#decode(byte[], byte[])} for correctness.
 */
public void testEncoder_encodeArrayToArray() {
    Encoder encoder = Base64.getEncoder();

    // Empty input
    assertEquals(0, encoder.encode(new byte[0], new byte[0]));

    // Test data for non-empty input
    byte[] input = "abcefghi".getBytes(US_ASCII);
    String expectedString = "YWJjZWZnaGk=";
    byte[] encodedBytes = expectedString.getBytes(US_ASCII);

    // Non-empty input: output array too short
    byte[] tooShort = new byte[encodedBytes.length - 1];
    try {
        encoder.encode(input, tooShort);
        fail();
    } catch (IllegalArgumentException expected) {
    }

    // Non-empty input: output array longer than required
    byte[] tooLong = new byte[encodedBytes.length + 1];
    int tooLongBytesEncoded = encoder.encode(input, tooLong);
    assertEquals(encodedBytes.length, tooLongBytesEncoded);
    assertEquals(0, tooLong[tooLong.length - 1]);
    assertArrayPrefixEquals(tooLong, encodedBytes.length, encodedBytes);

    // Non-empty input: output array has exact minimum required size
    byte[] justRight = new byte[encodedBytes.length];
    int justRightBytesEncoded = encoder.encode(input, justRight);
    assertEquals(encodedBytes.length, justRightBytesEncoded);
    assertArrayEquals(encodedBytes, justRight);
}
 
Example #23
Source File: Encryption.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Encrypt an array of integers to a String.
 * 
 * @param integers
 * @param context
 * @return
 * @throws ServletException
 */
public static String encryptIntegers(int integers[], String password) throws ServletException {
	/* Generate salt. */
	SecureRandom rand = new SecureRandom();
	byte salt[] = new byte[8];
	rand.nextBytes(salt);

	byte[] iv;
	byte[] ciphertext;
	try {
		/* Derive the key, given password and salt. */
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
		KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
		SecretKey tmp = factory.generateSecret(spec);
		SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		/* Encrypt the SampleSetID. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		iv = params.getParameterSpec(IvParameterSpec.class).getIV();

		ByteBuffer buff = ByteBuffer.allocate(integers.length * 4);
		for (int i = 0; i < integers.length; ++i) {
			buff.putInt(integers[i]);
		}
		ciphertext = cipher.doFinal(buff.array());
	} catch (Exception ex) {
		throw new ServletException(ex);
	}

	/* Store the encrypted SampleSetID in a cookie */

	Encoder encoder = Base64.getEncoder();
	String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
	return encryptedStr;
}
 
Example #24
Source File: SampleIDs.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Encrypt an integer to a String.
 * 
 * @param integer
 * @param context
 * @return
 * @throws ServletException
 */
private static String encryptInteger(Integer integer, ServletContext context) throws ServletException {
	/* Get password. */
	String password = context.getInitParameter("SampleSetIDEncryptionPassword");

	/* Generate salt. */
	SecureRandom rand = new SecureRandom();
	byte salt[] = new byte[8];
	rand.nextBytes(salt);

	byte[] iv;
	byte[] ciphertext;
	try {
		/* Derive the key, given password and salt. */
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
		KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
		SecretKey tmp = factory.generateSecret(spec);
		SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		/* Encrypt the SampleSetID. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		iv = params.getParameterSpec(IvParameterSpec.class).getIV();
		ciphertext = cipher.doFinal(ByteBuffer.allocate(4).putInt(integer).array());
	} catch (Exception ex) {
		throw new ServletException(ex);
	}

	/* Store the encrypted SampleSetID in a cookie */

	Encoder encoder = Base64.getEncoder();
	String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
	return encryptedStr;
}
 
Example #25
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testEncoder_lineLength() throws Exception {
    String in_56 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd";
    String in_57 = in_56 + "e";
    String in_58 = in_56 + "ef";
    String in_59 = in_56 + "efg";
    String in_60 = in_56 + "efgh";
    String in_61 = in_56 + "efghi";

    String prefix = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5emFi";
    String out_56 = prefix + "Y2Q=";
    String out_57 = prefix + "Y2Rl";
    String out_58 = prefix + "Y2Rl\r\nZg==";
    String out_59 = prefix + "Y2Rl\r\nZmc=";
    String out_60 = prefix + "Y2Rl\r\nZmdo";
    String out_61 = prefix + "Y2Rl\r\nZmdoaQ==";

    Encoder encoder = Base64.getMimeEncoder();
    Decoder decoder = Base64.getMimeDecoder();
    assertEquals("", encodeFromAscii(encoder, decoder, ""));
    assertEquals(out_56, encodeFromAscii(encoder, decoder, in_56));
    assertEquals(out_57, encodeFromAscii(encoder, decoder, in_57));
    assertEquals(out_58, encodeFromAscii(encoder, decoder, in_58));
    assertEquals(out_59, encodeFromAscii(encoder, decoder, in_59));
    assertEquals(out_60, encodeFromAscii(encoder, decoder, in_60));
    assertEquals(out_61, encodeFromAscii(encoder, decoder, in_61));

    encoder = Base64.getUrlEncoder();
    decoder = Base64.getUrlDecoder();
    assertEquals(out_56.replaceAll("\r\n", ""), encodeFromAscii(encoder, decoder, in_56));
    assertEquals(out_57.replaceAll("\r\n", ""), encodeFromAscii(encoder, decoder, in_57));
    assertEquals(out_58.replaceAll("\r\n", ""), encodeFromAscii(encoder, decoder, in_58));
    assertEquals(out_59.replaceAll("\r\n", ""), encodeFromAscii(encoder, decoder, in_59));
    assertEquals(out_60.replaceAll("\r\n", ""), encodeFromAscii(encoder, decoder, in_60));
    assertEquals(out_61.replaceAll("\r\n", ""), encodeFromAscii(encoder, decoder, in_61));
}
 
Example #26
Source File: TestBase64Golden.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #27
Source File: JwtBasedSamlRequestIdManager.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static String getUniquifierPrefix() {
    // To make a request ID globally unique, we will add MAC-based machine ID and a random number.
    // The random number tries to make this instance unique in the same machine and process.
    final byte[] r = TemporaryThreadLocals.get().byteArray(6);
    ThreadLocalRandom.current().nextBytes(r);
    final Encoder encoder = Base64.getEncoder();
    return new StringBuilder().append(encoder.encodeToString(defaultMachineId()))
                              .append(encoder.encodeToString(r))
                              .toString();
}
 
Example #28
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testEncoder_nonPrintableBytes() throws Exception {
    Encoder encoder = Base64.getUrlEncoder();
    assertEquals("", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 0)));
    assertEquals("_w==", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 1)));
    assertEquals("_-4=", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 2)));
    assertEquals("_-7d", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 3)));
    assertEquals("_-7dzA==", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 4)));
    assertEquals("_-7dzLs=", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 5)));
    assertEquals("_-7dzLuq", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 6)));
    assertEquals("_-7dzLuqmQ==", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 7)));
    assertEquals("_-7dzLuqmYg=", encoder.encodeToString(copyOfRange(SAMPLE_NON_ASCII_BYTES, 0, 8)));
}
 
Example #29
Source File: TestBase64Golden.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test1() throws Exception {
    byte[] src = new byte[] {
        46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67,
        40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30,
        -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 };
    Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e });
    byte[] encoded = encoder.encode(src);
    Decoder decoder = Base64.getMimeDecoder();
    byte[] decoded = decoder.decode(encoded);
    if (!Objects.deepEquals(src, decoded)) {
        throw new RuntimeException();
    }
}
 
Example #30
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static void checkEncoder_nullArgs(Encoder encoder) {
    assertThrowsNpe(() -> encoder.encode((byte[]) null));
    assertThrowsNpe(() -> encoder.encodeToString(null));
    assertThrowsNpe(() -> encoder.encode(null, null));
    assertThrowsNpe(() -> encoder.encode((ByteBuffer) null));
    assertThrowsNpe(() -> encoder.wrap(null));
}