java.util.Base64.Decoder Java Examples

The following examples show how to use java.util.Base64.Decoder. 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: PPGaussian.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void decode(String string64, StereoMolecule mol)  {
	Decoder decoder = Base64.getDecoder();
	String[] strings = string64.split(" ");
	if(strings.length==1) { // no pharmacophore information encoded
		return;
	}
	atomicNo = Integer.decode(strings[0]);
	weight = EncodeFunctions.byteArrayToDouble(decoder.decode(strings[1].getBytes()));
	StringBuilder sb = new StringBuilder();
	for(int i=2;i<strings.length;i++) {
		sb.append(strings[i]);
		sb.append(" ");
	}
	pp = PharmacophorePointFactory.fromString(sb.toString(), mol);
	center = pp.getCenter();
	alpha = calculateWidth(); //the width of the Gaussian depends on the atomic radius of the atom
	volume = calculateVolume();
	coeff = calculateHeight();
	this.atomId = pp.getCenterID();
}
 
Example #2
Source File: KeyCloakRsaKeyFetcher.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This method will accept keycloak base URL and realm name. Based on provided values it will
 * fetch public key from keycloak.
 *
 * @param url A string value having keycloak base URL
 * @param realm Keycloak realm name
 * @return Public key used to verify user access token.
 */
public PublicKey getPublicKeyFromKeyCloak(String url, String realm) {
  try {
    Map<String, String> valueMap = null;
    Decoder urlDecoder = Base64.getUrlDecoder();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    String publicKeyString = requestKeyFromKeycloak(url, realm);
    if (publicKeyString != null) {
      valueMap = getValuesFromJson(publicKeyString);
      if (valueMap != null) {
        BigInteger modulus = new BigInteger(1, urlDecoder.decode(valueMap.get(MODULUS)));
        BigInteger publicExponent = new BigInteger(1, urlDecoder.decode(valueMap.get(EXPONENT)));
        PublicKey key = keyFactory.generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
        saveToCache(key);
        return key;
      }
    }
  } catch (Exception e) {
    ProjectLogger.log(
        "KeyCloakRsaKeyFetcher:getPublicKeyFromKeyCloak: Exception occurred with message = "
            + e.getMessage(),
        LoggerEnum.ERROR);
  }
  return null;
}
 
Example #3
Source File: Base64Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testDecoder_decodeByteBuffer() {
    Decoder decoder = Base64.getDecoder();

    byte[] emptyByteArray = new byte[0];
    ByteBuffer emptyByteBuffer = ByteBuffer.wrap(emptyByteArray);
    ByteBuffer emptyDecodedBuffer = decoder.decode(emptyByteBuffer);
    assertEquals(emptyByteBuffer, emptyDecodedBuffer);
    assertNotSame(emptyByteArray, emptyDecodedBuffer);

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

    ByteBuffer inputBuffer = ByteBuffer.allocate(input.length);
    inputBuffer.put(input);
    inputBuffer.position(0);
    checkDecoder_decodeByteBuffer(decoder, inputBuffer, expectedBytes);

    inputBuffer = ByteBuffer.allocateDirect(input.length);
    inputBuffer.put(input);
    inputBuffer.position(0);
    checkDecoder_decodeByteBuffer(decoder, inputBuffer, expectedBytes);
}
 
Example #4
Source File: Base64Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testDecoder_decodeByteBuffer_invalidData() {
    Decoder decoder = Base64.getDecoder();

    // Test the two types of byte buffer.
    String inputString = "AAAA AAAA";
    byte[] input = inputString.getBytes(US_ASCII);

    ByteBuffer inputBuffer = ByteBuffer.allocate(input.length);
    inputBuffer.put(input);
    inputBuffer.position(0);
    checkDecoder_decodeByteBuffer_invalidData(decoder, inputBuffer);

    inputBuffer = ByteBuffer.allocateDirect(input.length);
    inputBuffer.put(input);
    inputBuffer.position(0);
    checkDecoder_decodeByteBuffer_invalidData(decoder, inputBuffer);
}
 
Example #5
Source File: TFRecordIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testTFRecordCodec() throws IOException {
  Decoder b64 = Base64.getDecoder();
  TFRecordCodec codec = new TFRecordCodec();

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PickyWriteChannel outChan = new PickyWriteChannel(baos);

  codec.write(outChan, "foo".getBytes(StandardCharsets.UTF_8));
  assertArrayEquals(b64.decode(FOO_RECORD_BASE64), baos.toByteArray());
  codec.write(outChan, "bar".getBytes(StandardCharsets.UTF_8));
  assertArrayEquals(b64.decode(FOO_BAR_RECORD_BASE64), baos.toByteArray());

  PickyReadChannel inChan = new PickyReadChannel(new ByteArrayInputStream(baos.toByteArray()));
  byte[] foo = codec.read(inChan);
  byte[] bar = codec.read(inChan);
  assertNull(codec.read(inChan));

  assertEquals("foo", new String(foo, StandardCharsets.UTF_8));
  assertEquals("bar", new String(bar, StandardCharsets.UTF_8));
}
 
Example #6
Source File: Base64Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that if the lineSeparator is empty or the line length is {@code <= 3}
 * or larger than the data to be encoded, a single line is returned.
 */
public void testRoundTrip_allBytes_mime_singleLine() {
    Decoder decoder = Base64.getMimeDecoder();
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(76, new byte[0]), decoder);

    // Line lengths <= 3 mean no wrapping; the separator is ignored in that case.
    byte[] separator = new byte[] { '*' };
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(Integer.MIN_VALUE, separator),
            decoder);
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(-1, separator), decoder);
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(0, separator), decoder);
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(1, separator), decoder);
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(2, separator), decoder);
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(3, separator), decoder);

    // output fits into the permitted line length
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(
            ALL_BYTE_VALUES_ENCODED.length(), separator), decoder);
    checkRoundTrip_allBytes_singleLine(Base64.getMimeEncoder(Integer.MAX_VALUE, separator),
            decoder);
}
 
Example #7
Source File: JobParameter.java    From FHIR with Apache License 2.0 6 votes vote down vote up
/**
 * converts back from input string to objects
 * 
 * @param input
 * @return
 * @throws IOException
 */
public static List<Input> parseInputsFromString(String input) throws IOException {
    List<Input> inputs = new ArrayList<>();
    Decoder decoder = Base64.getDecoder();
    byte[] bytes = decoder.decode(input);

    try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
        try (JsonReader jsonReader = JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) {
            JsonArray jsonArray = jsonReader.readArray();
            /*
             * the input is intentionally base64 to capture the JSON Array and maintain integrity as part of a
             * name:value pair when submitted to the Batch framework.
             */
            ListIterator<JsonValue> iter = jsonArray.listIterator();
            while (iter.hasNext()) {
                JsonObject obj = iter.next().asJsonObject();
                inputs.add(new Input(obj.getString("type"), obj.getString("url")));
            }
        }
    }
    return inputs;
}
 
Example #8
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 #9
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 #10
Source File: AESCipher.java    From AESCipher-Java with MIT License 5 votes vote down vote up
public static String aesDecryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
	Decoder decoder = Base64.getDecoder();
    byte[] encryptedBytes = decoder.decode(content);
    byte[] keyBytes = key.getBytes(charset);
	byte[] decryptedBytes = aesDecryptBytes(encryptedBytes, keyBytes);
    return new String(decryptedBytes, charset);		
}
 
Example #11
Source File: StaticEdition.java    From syndesis with Apache License 2.0 5 votes vote down vote up
static byte[] decode(final String given) {
    final Decoder decoder = Base64.getDecoder();

    try {
        return decoder.decode(given);
    } catch (final IllegalArgumentException ignored) {
        // given is not a base64 string
        return given.getBytes(StandardCharsets.US_ASCII);
    }
}
 
Example #12
Source File: Encryption.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Decrypt an array of integers from a String.
 * 
 * @param encrypted
 * @param context
 * @return
 * @throws ServletException
 */
public static int[] decryptIntegers(String encrypted, String password) throws ServletException {
	String encryptedParts[] = encrypted.split("\\|");
	if (encryptedParts.length != 3) {
		throw new ServletException("Invalid encrypted string.");
	}

	/* Extract the encrypted data, initialisation vector, and salt from the cookie. */
	Decoder decoder = Base64.getDecoder();
	byte ciphertext[] = decoder.decode(encryptedParts[0]);
	byte iv[] = decoder.decode(encryptedParts[1]);
	byte salt[] = decoder.decode(encryptedParts[2]);
	byte plainbytes[];
	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");

		/* Decrypt the message, given derived key and initialization vector. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
		plainbytes = cipher.doFinal(ciphertext);
	} catch (Exception ex) {
		throw new ServletException(ex);
	}
	IntBuffer buff = ByteBuffer.wrap(plainbytes).asIntBuffer();
	int integers[] = new int[buff.remaining()];
	for (int i = 0; i < integers.length; ++i) {
		integers[i] = buff.get();
	}
	return integers;
}
 
Example #13
Source File: Base64DecodeMultipartFile.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
public static MultipartFile base64Convert(String base64) {

        String[] baseStrs = base64.split(",");
        Decoder decoder = Base64.getDecoder();
        byte[] b = decoder.decode(baseStrs[1]);

        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        return new Base64DecodeMultipartFile(b, baseStrs[0]);
    }
 
Example #14
Source File: SampleIDs.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Decrypt an integer from a String.
 * 
 * @param encrypted
 * @param context
 * @return
 * @throws ServletException
 */
private static Integer decryptInteger(String encrypted, ServletContext context) throws ServletException {
	String encryptedParts[] = encrypted.split("\\|");
	if (encryptedParts.length != 3) {
		throw new ServletException("Invalid encrypted string.");
	}
	/* Get password. */
	String password = context.getInitParameter("SampleSetIDEncryptionPassword");

	/* Extract the encrypted data, initialisation vector, and salt from the cookie. */
	Decoder decoder = Base64.getDecoder();
	byte ciphertext[] = decoder.decode(encryptedParts[0]);
	byte iv[] = decoder.decode(encryptedParts[1]);
	byte salt[] = decoder.decode(encryptedParts[2]);
	byte plainbytes[];
	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");

		/* Decrypt the message, given derived key and initialization vector. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
		plainbytes = cipher.doFinal(ciphertext);
	} catch (Exception ex) {
		throw new ServletException(ex);
	}
	return ByteBuffer.wrap(plainbytes).asIntBuffer().get();
}
 
Example #15
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 #16
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 #17
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 #18
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks decoding of bytes containing a value outside of the allowed
 * {@link #TABLE_1 "basic" alphabet}.
 */
public void testDecoder_extraChars_basic() throws Exception {
    Decoder basicDecoder = Base64.getDecoder(); // uses Table 1
    // Check failure cases common to both RFC4648 Table 1 and Table 2 decoding.
    checkDecoder_extraChars_common(basicDecoder);

    // Tests characters that are part of RFC4848 Table 2 but not Table 1.
    assertDecodeThrowsIAe(basicDecoder, "_aGVsbG8sIHdvcmx");
    assertDecodeThrowsIAe(basicDecoder, "aGV_sbG8sIHdvcmx");
    assertDecodeThrowsIAe(basicDecoder, "aGVsbG8sIHdvcmx_");
}
 
Example #19
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks decoding of bytes containing a value outside of the allowed
 * {@link #TABLE_2 url alphabet}.
 */
public void testDecoder_extraChars_url() throws Exception {
    Decoder urlDecoder = Base64.getUrlDecoder(); // uses Table 2
    // Check failure cases common to both RFC4648 table 1 and table 2 decoding.
    checkDecoder_extraChars_common(urlDecoder);

    // Tests characters that are part of RFC4848 Table 1 but not Table 2.
    assertDecodeThrowsIAe(urlDecoder, "/aGVsbG8sIHdvcmx");
    assertDecodeThrowsIAe(urlDecoder, "aGV/sbG8sIHdvcmx");
    assertDecodeThrowsIAe(urlDecoder, "aGVsbG8sIHdvcmx/");
}
 
Example #20
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Check decoding sample non-ASCII byte[] values from a {@link #TABLE_1}
 * encoded String.
 */
private static void checkDecoder_nonPrintableBytes_table1(Decoder decoder) throws Exception {
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 0, decoder.decode(""));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 1, decoder.decode("/w=="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 2, decoder.decode("/+4="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 3, decoder.decode("/+7d"));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 4, decoder.decode("/+7dzA=="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 5, decoder.decode("/+7dzLs="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 6, decoder.decode("/+7dzLuq"));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 7, decoder.decode("/+7dzLuqmQ=="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 8, decoder.decode("/+7dzLuqmYg="));
}
 
Example #21
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Check decoding sample non-ASCII byte[] values from a {@link #TABLE_2}
 * (url safe) encoded String.
 */
public void testDecoder_nonPrintableBytes_url() throws Exception {
    Decoder decoder = Base64.getUrlDecoder();
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 0, decoder.decode(""));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 1, decoder.decode("_w=="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 2, decoder.decode("_-4="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 3, decoder.decode("_-7d"));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 4, decoder.decode("_-7dzA=="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 5, decoder.decode("_-7dzLs="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 6, decoder.decode("_-7dzLuq"));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 7, decoder.decode("_-7dzLuqmQ=="));
    assertArrayPrefixEquals(SAMPLE_NON_ASCII_BYTES, 8, decoder.decode("_-7dzLuqmYg="));
}
 
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 as well as
 * for consistency with other methods tested elsewhere.
 */
public void testDecoder_decodeArrayToArray() {
    Decoder decoder = Base64.getDecoder();

    // Empty input
    assertEquals(0, decoder.decode(new byte[0], new byte[0]));

    // Test data for non-empty input
    String inputString = "YWJjZWZnaGk=";
    byte[] input = inputString.getBytes(US_ASCII);
    String expectedString = "abcefghi";
    byte[] decodedBytes = expectedString.getBytes(US_ASCII);
    // check test data consistency with other methods that are tested elsewhere
    assertRoundTrip(Base64.getEncoder(), decoder, inputString, decodedBytes);

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

    // Non-empty input: output array longer than required
    byte[] tooLong = new byte[decodedBytes.length + 1];
    int tooLongBytesDecoded = decoder.decode(input, tooLong);
    assertEquals(decodedBytes.length, tooLongBytesDecoded);
    assertEquals(0, tooLong[tooLong.length - 1]);
    assertArrayPrefixEquals(tooLong, decodedBytes.length, decodedBytes);

    // Non-empty input: output array has exact minimum required size
    byte[] justRight = new byte[decodedBytes.length];
    int justRightBytesDecoded = decoder.decode(input, justRight);
    assertEquals(decodedBytes.length, justRightBytesDecoded);
    assertArrayEquals(decodedBytes, justRight);

}
 
Example #23
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static void checkDecoder_decodeByteBuffer(
        Decoder decoder, ByteBuffer inputBuffer, byte[] expectedBytes) {
    assertEquals(0, inputBuffer.position());
    assertEquals(inputBuffer.remaining(), inputBuffer.limit());
    int inputLength = inputBuffer.remaining();

    ByteBuffer decodedBuffer = decoder.decode(inputBuffer);

    assertEquals(inputLength, inputBuffer.position());
    assertEquals(0, inputBuffer.remaining());
    assertEquals(inputLength, inputBuffer.limit());
    assertEquals(0, decodedBuffer.position());
    assertEquals(expectedBytes.length, decodedBuffer.remaining());
    assertEquals(expectedBytes.length, decodedBuffer.limit());
}
 
Example #24
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static void checkDecoder_nullArgs(Decoder decoder) {
    assertThrowsNpe(() -> decoder.decode((byte[]) null));
    assertThrowsNpe(() -> decoder.decode((String) null));
    assertThrowsNpe(() -> decoder.decode(null, null));
    assertThrowsNpe(() -> decoder.decode((ByteBuffer) null));
    assertThrowsNpe(() -> decoder.wrap(null));
}
 
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: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/** check a range of possible line lengths */
public void testRoundTrip_allBytes_mime_lineLength() {
    Decoder decoder = Base64.getMimeDecoder();
    byte[] separator = new byte[] { '*' };
    checkRoundTrip_allBytes(Base64.getMimeEncoder(4, separator), decoder,
            wrapLines("*", ALL_BYTE_VALUES_ENCODED, 4));
    checkRoundTrip_allBytes(Base64.getMimeEncoder(8, separator), decoder,
            wrapLines("*", ALL_BYTE_VALUES_ENCODED, 8));
    checkRoundTrip_allBytes(Base64.getMimeEncoder(20, separator), decoder,
            wrapLines("*", ALL_BYTE_VALUES_ENCODED, 20));
    checkRoundTrip_allBytes(Base64.getMimeEncoder(100, separator), decoder,
            wrapLines("*", ALL_BYTE_VALUES_ENCODED, 100));
    checkRoundTrip_allBytes(Base64.getMimeEncoder(Integer.MAX_VALUE & ~3, separator), decoder,
            wrapLines("*", ALL_BYTE_VALUES_ENCODED, Integer.MAX_VALUE & ~3));
}
 
Example #27
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * checks that the specified line length is rounded down to the nearest multiple of 4.
 */
public void testRoundTrip_allBytes_mime_lineLength_isRoundedDown() {
    Decoder decoder = Base64.getMimeDecoder();
    byte[] separator = new byte[] { '\r', '\n' };
    checkRoundTrip_allBytes(Base64.getMimeEncoder(60, separator), decoder,
            wrapLines("\r\n", ALL_BYTE_VALUES_ENCODED, 60));
    checkRoundTrip_allBytes(Base64.getMimeEncoder(63, separator), decoder,
            wrapLines("\r\n", ALL_BYTE_VALUES_ENCODED, 60));
    checkRoundTrip_allBytes(Base64.getMimeEncoder(10, separator), decoder,
            wrapLines("\r\n", ALL_BYTE_VALUES_ENCODED, 8));
}
 
Example #28
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that various-sized inputs survive a round trip.
 */
private static void checkRoundTrip_variousSizes(Encoder encoder, Decoder decoder) {
    Random random = new Random(7654321);
    for (int numBytes : new int [] { 0, 1, 2, 75, 76, 77, 80, 100, 1234 }) {
        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        byte[] result = decoder.decode(encoder.encode(bytes));
        assertArrayEquals(bytes, result);
    }
}
 
Example #29
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 #30
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/** Assert that decoding the specific String throws IllegalArgumentException. */
private static void assertDecodeThrowsIAe(Decoder decoder, String invalidEncoded)
        throws Exception {
    try {
        decoder.decode(invalidEncoded);
        fail("should have failed to decode");
    } catch (IllegalArgumentException e) {
    }
}