下面列出了怎么用java.util.Base64.Decoder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
/**
* 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;
}
@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));
}
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);
}
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);
}
/**
* 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);
}
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();
}
private List<Certificate> getCertificatesFromJsonArray(JsonArray x5c) throws CertificateException, NoSuchProviderException{
List<Certificate> result = new ArrayList<>();
if(x5c == null){
return result;
}
Decoder decoder = Base64.getDecoder();
for(int i = 0; i < x5c.size(); i++){
byte[] certBytes = decoder.decode(x5c.getString(i));
result.add(cryptoCommon.generateX509FromBytes(certBytes));
}
return result;
}
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]);
}
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();
}
}
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();
}
}
/**
* Returns signature of a JWT as a String.
*
* @param jwt REQUIRED: valid JSON Web Token as String.
* @return signature as a String.
*/
public static String getSignature(String jwt) {
try {
validateJWT(jwt);
Base64.Decoder dec= Base64.getDecoder();
final byte[] sectionDecoded = dec.decode(jwt.split("\\.")[SIGNATURE]);
return new String(sectionDecoded, "UTF-8");
} catch (final Exception e) {
throw new InvalidParameterException("error in parsing JSON");
}
}
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();
}
}
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();
}
}
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();
}
}
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);
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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);
}
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();
}
}
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();
}
}
/**
* 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;
}
/**
* 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();
}
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();
}
}
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();
}
}
/**
* 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_");
}
/**
* 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/");
}