Java Code Examples for java.util.Base64#Decoder

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: JwtUtil.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public static String getUserRoles(HttpServletRequest httpServletRequest) {
    String authorization = httpServletRequest.getHeader("authorization");
    if (null == authorization) {
        // 请求头中没有携带JWT,表示非登录用户
        return null;
    }

    String jwt = authorization.substring(7); // 去除前缀“bearer ”
    String payloadBase64 = jwt.substring(jwt.indexOf(".") + 1, jwt.lastIndexOf(".")); // 取出JWT中第二部分
    Base64.Decoder decoder = Base64.getDecoder();
    String payloadString;
    try {
        payloadString = new String(decoder.decode(payloadBase64), "UTF-8");
    } catch (Exception e) {
        return null;
    }
    JSONObject payloadJson = JSONObject.parseObject(payloadString);

    return payloadJson.getString("authorities");
}
 
Example 2
Source File: ContentCryptographer.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts content under a derived key.
 *
 * @param plaintextBase64 plaintext content to encrypt, which is expected to be base64-encoded
 * @return serialized JSON containing ciphertext and parameters necessary for decryption
 */
public String encrypt(String plaintextBase64) {
  Base64.Decoder decoder = getDecoder();
  final byte[] plaintext = decoder.decode(plaintextBase64);

  byte[] nonce = new byte[NONCE_BYTES];
  random.nextBytes(nonce);

  byte[] ciphertext = gcm(Mode.ENCRYPT, derivationInfo, nonce, plaintext);
  Crypted crypted = Crypted.of(derivationInfo, ciphertext, nonce);
  String encryptedJson;
  try {
    encryptedJson = MAPPER.writeValueAsString(crypted);
  } catch (JsonProcessingException e) {
    throw Throwables.propagate(e);
  }

  if (!Subtles.secureCompare(decoder.decode(decrypt(encryptedJson)), plaintext)) {
    logger.warn("Decryption of (just encrypted) data does not match original! [name={}]",
        derivationInfo);
  }

  return encryptedJson;
}
 
Example 3
Source File: TestBase64.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void  testDecodeUnpadded() throws Throwable {
    byte[] srcA = new byte[] { 'Q', 'Q' };
    byte[] srcAA = new byte[] { 'Q', 'Q', 'E'};
    Base64.Decoder dec = Base64.getDecoder();
    byte[] ret = dec.decode(srcA);
    if (ret[0] != 'A')
        throw new RuntimeException("Decoding unpadding input A failed");
    ret = dec.decode(srcAA);
    if (ret[0] != 'A' && ret[1] != 'A')
        throw new RuntimeException("Decoding unpadding input AA failed");
    ret = new byte[10];
    if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 1 &&
        ret[0] != 'A')
        throw new RuntimeException("Decoding unpadding input A from stream failed");
    if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 2 &&
        ret[0] != 'A' && ret[1] != 'A')
        throw new RuntimeException("Decoding unpadding input AA from stream failed");
}
 
Example 4
Source File: TestBase64.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 5
Source File: TestBase64.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void testNull(Base64.Decoder dec) {
    checkNull(() -> dec.decode(ba_null));
    checkNull(() -> dec.decode(str_null));
    checkNull(() -> dec.decode(ba_null, new byte[10]));
    checkNull(() -> dec.decode(new byte[10], ba_null));
    checkNull(() -> dec.decode(bb_null));
    checkNull(() -> dec.wrap((InputStream)null));
}
 
Example 6
Source File: LiMeStaticFactory.java    From LiMe with MIT License 5 votes vote down vote up
public static String decrypt(String content, String key) {
    try {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedBytes = decoder.decode(content);
        byte[] digestedKeyBytes = LiMeMessageDigester.md5(key.getBytes(CHARSET));
        byte[] decryptedBytes = LiMeAesCipher.aesDecryptBytes(encryptedBytes, digestedKeyBytes);
        return new String(decryptedBytes, CHARSET);
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 7
Source File: TestBase64.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)
    throws Throwable {

    ByteBuffer bout = dec.decode(bin);
    byte[] buf = new byte[bout.remaining()];
    bout.get(buf);
    checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");
}
 
Example 8
Source File: TestBase64.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {
    ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
    InputStream is = dec.wrap(bais);
    is.read(new byte[10]);
    is.close();
    checkIOE(() -> is.read());
    checkIOE(() -> is.read(new byte[] {10}));
    checkIOE(() -> is.read(new byte[] {10}, 1, 4));
    checkIOE(() -> is.available());
    checkIOE(() -> is.skip(20));
}
 
Example 9
Source File: TestBase64.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testNull(final Base64.Decoder dec) {
    checkNull(new Runnable() { public void run() { dec.decode(ba_null); }});
    checkNull(new Runnable() { public void run() { dec.decode(str_null); }});
    checkNull(new Runnable() { public void run() { dec.decode(ba_null, new byte[10]); }});
    checkNull(new Runnable() { public void run() { dec.decode(new byte[10], ba_null); }});
    checkNull(new Runnable() { public void run() { dec.decode(bb_null); }});
    checkNull(new Runnable() { public void run() { dec.wrap((InputStream)null); }});
}
 
Example 10
Source File: TestBase64.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
        throws Throwable {
    List<Integer> vals = Arrays.asList(Integer.MIN_VALUE,
            Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
            Integer.MAX_VALUE - 1, Integer.MAX_VALUE,
            rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
            rnd.nextInt());
    byte[] buf = new byte[3];
    for (int off : vals) {
        for (int len : vals) {
            if (off >= 0 && len >= 0 && off <= buf.length - len) {
                // valid args, skip them
                continue;
            }
            // invalid args, test them
            System.out.println("testing off=" + off + ", len=" + len);

            String input = "AAAAAAAAAAAAAAAAAAAAAA";
            ByteArrayInputStream bais =
                    new ByteArrayInputStream(input.getBytes("Latin1"));
            try (InputStream is = dec.wrap(bais)) {
                is.read(buf, off, len);
                throw new RuntimeException("Expected IOOBEx was not thrown");
            } catch (IndexOutOfBoundsException expected) {
            }
            if (bais.available() != input.length())
                throw new RuntimeException("No input should be consumed, "
                        + "but consumed " + (input.length() - bais.available())
                        + " bytes");
        }
    }
}
 
Example 11
Source File: TestBase64.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {
    ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
    InputStream is = dec.wrap(bais);
    is.read(new byte[10]);
    is.close();
    checkIOE(() -> is.read());
    checkIOE(() -> is.read(new byte[] {10}));
    checkIOE(() -> is.read(new byte[] {10}, 1, 4));
    checkIOE(() -> is.available());
    checkIOE(() -> is.skip(20));
}
 
Example 12
Source File: TestBase64.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testNull(Base64.Decoder dec) {
    checkNull(() -> dec.decode(ba_null));
    checkNull(() -> dec.decode(str_null));
    checkNull(() -> dec.decode(ba_null, new byte[10]));
    checkNull(() -> dec.decode(new byte[10], ba_null));
    checkNull(() -> dec.decode(bb_null));
    checkNull(() -> dec.wrap((InputStream)null));
}
 
Example 13
Source File: TokenGenerator.java    From InChat with Apache License 2.0 5 votes vote down vote up
public static String getUseridOnBase(Long userId) {
    Base64.Decoder decoder = Base64.getDecoder();
    Base64.Encoder encoder = Base64.getEncoder();
    String text = userId.toString();
    String encodedText = "";
    try {
        final byte[] textByte = text.getBytes("UTF-8");
        encodedText = encoder.encodeToString(textByte);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return encodedText;
}
 
Example 14
Source File: ConvertUtil.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param obj base64 加密后的图片
 * @return Buffer 流
 */
public static Future<Buffer> getImageFromBase64(String obj) {
    Future<Buffer> result = Future.future();
    if (obj == null) {
        result.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, "图片读取失败"));
        return result;
    }

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] bs;
    bs = decoder.decode(obj);
    Buffer buffer = Buffer.buffer(bs);
    result.complete(buffer);
    return result;
}
 
Example 15
Source File: TestBase64.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testIOE(final Base64.Decoder dec, byte[] decoded) throws Throwable {
    ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
    final InputStream is = dec.wrap(bais);
    is.read(new byte[10]);
    is.close();
    checkIOE(new Testable() { public void test() throws Throwable { is.read(); }});
    checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}); }});
    checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}, 1, 4); }});
    checkIOE(new Testable() { public void test() throws Throwable { is.available(); }});
    checkIOE(new Testable() { public void test() throws Throwable { is.skip(20); }});
}
 
Example 16
Source File: TestBase64.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private static void testMalformedPadding() throws Throwable {
    Object[] data = new Object[] {
        "$=#",       "",      0,      // illegal ending unit
        "A",         "",      0,      // dangling single byte
        "A=",        "",      0,
        "A==",       "",      0,
        "QUJDA",     "ABC",   4,
        "QUJDA=",    "ABC",   4,
        "QUJDA==",   "ABC",   4,

        "=",         "",      0,      // unnecessary padding
        "QUJD=",     "ABC",   4,      //"ABC".encode() -> "QUJD"

        "AA=",       "",      0,      // incomplete padding
        "QQ=",       "",      0,
        "QQ=N",      "",      0,      // incorrect padding
        "QQ=?",      "",      0,
        "QUJDQQ=",   "ABC",   4,
        "QUJDQQ=N",  "ABC",   4,
        "QUJDQQ=?",  "ABC",   4,
    };

    Base64.Decoder[] decs = new Base64.Decoder[] {
        Base64.getDecoder(),
        Base64.getUrlDecoder(),
        Base64.getMimeDecoder()
    };

    for (Base64.Decoder dec : decs) {
        for (int i = 0; i < data.length; i += 3) {
            final String srcStr = (String)data[i];
            final byte[] srcBytes = srcStr.getBytes("ASCII");
            final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);
            byte[] expected = ((String)data[i + 1]).getBytes("ASCII");
            int pos = (Integer)data[i + 2];

            // decode(byte[])
            checkIAE(new Runnable() { public void run() { dec.decode(srcBytes); }});

            // decode(String)
            checkIAE(new Runnable() { public void run() { dec.decode(srcStr); }});

            // decode(ByteBuffer)
            checkIAE(new Runnable() { public void run() { dec.decode(srcBB); }});

            // wrap stream
            checkIOE(new Testable() {
                public void test() throws IOException {
                    try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {
                        while (is.read() != -1);
                    }
            }});
        }
    }
}
 
Example 17
Source File: TestBase64.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void testMalformedPadding() throws Throwable {
    Object[] data = new Object[] {
        "$=#",       "",      0,      // illegal ending unit
        "A",         "",      0,      // dangling single byte
        "A=",        "",      0,
        "A==",       "",      0,
        "QUJDA",     "ABC",   4,
        "QUJDA=",    "ABC",   4,
        "QUJDA==",   "ABC",   4,

        "=",         "",      0,      // unnecessary padding
        "QUJD=",     "ABC",   4,      //"ABC".encode() -> "QUJD"

        "AA=",       "",      0,      // incomplete padding
        "QQ=",       "",      0,
        "QQ=N",      "",      0,      // incorrect padding
        "QQ=?",      "",      0,
        "QUJDQQ=",   "ABC",   4,
        "QUJDQQ=N",  "ABC",   4,
        "QUJDQQ=?",  "ABC",   4,
    };

    Base64.Decoder[] decs = new Base64.Decoder[] {
        Base64.getDecoder(),
        Base64.getUrlDecoder(),
        Base64.getMimeDecoder()
    };

    for (Base64.Decoder dec : decs) {
        for (int i = 0; i < data.length; i += 3) {
            final String srcStr = (String)data[i];
            final byte[] srcBytes = srcStr.getBytes("ASCII");
            final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);
            byte[] expected = ((String)data[i + 1]).getBytes("ASCII");
            int pos = (Integer)data[i + 2];

            // decode(byte[])
            checkIAE(() -> dec.decode(srcBytes));

            // decode(String)
            checkIAE(() -> dec.decode(srcStr));

            // decode(ByteBuffer)
            checkIAE(() -> dec.decode(srcBB));

            // wrap stream
            checkIOE(new Testable() {
                public void test() throws IOException {
                    try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {
                        while (is.read() != -1);
                    }
            }});
        }
    }
}
 
Example 18
Source File: TestBase64.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void testMalformedPadding() throws Throwable {
    Object[] data = new Object[] {
        "$=#",       "",      0,      // illegal ending unit
        "A",         "",      0,      // dangling single byte
        "A=",        "",      0,
        "A==",       "",      0,
        "QUJDA",     "ABC",   4,
        "QUJDA=",    "ABC",   4,
        "QUJDA==",   "ABC",   4,

        "=",         "",      0,      // unnecessary padding
        "QUJD=",     "ABC",   4,      //"ABC".encode() -> "QUJD"

        "AA=",       "",      0,      // incomplete padding
        "QQ=",       "",      0,
        "QQ=N",      "",      0,      // incorrect padding
        "QQ=?",      "",      0,
        "QUJDQQ=",   "ABC",   4,
        "QUJDQQ=N",  "ABC",   4,
        "QUJDQQ=?",  "ABC",   4,
    };

    Base64.Decoder[] decs = new Base64.Decoder[] {
        Base64.getDecoder(),
        Base64.getUrlDecoder(),
        Base64.getMimeDecoder()
    };

    for (Base64.Decoder dec : decs) {
        for (int i = 0; i < data.length; i += 3) {
            final String srcStr = (String)data[i];
            final byte[] srcBytes = srcStr.getBytes("ASCII");
            final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);
            byte[] expected = ((String)data[i + 1]).getBytes("ASCII");
            int pos = (Integer)data[i + 2];

            // decode(byte[])
            checkIAE(() -> dec.decode(srcBytes));

            // decode(String)
            checkIAE(() -> dec.decode(srcStr));

            // decode(ByteBuffer)
            checkIAE(() -> dec.decode(srcBB));

            // wrap stream
            checkIOE(new Testable() {
                public void test() throws IOException {
                    try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {
                        while (is.read() != -1);
                    }
            }});
        }
    }
}
 
Example 19
Source File: TestBase64.java    From native-obfuscator with GNU General Public License v3.0 4 votes vote down vote up
private static void testMalformedPadding() throws Throwable {
    Object[] data = new Object[] {
        "$=#",       "",      0,      // illegal ending unit
        "A",         "",      0,      // dangling single byte
        "A=",        "",      0,
        "A==",       "",      0,
        "QUJDA",     "ABC",   4,
        "QUJDA=",    "ABC",   4,
        "QUJDA==",   "ABC",   4,

        "=",         "",      0,      // unnecessary padding
        "QUJD=",     "ABC",   4,      //"ABC".encode() -> "QUJD"

        "AA=",       "",      0,      // incomplete padding
        "QQ=",       "",      0,
        "QQ=N",      "",      0,      // incorrect padding
        "QQ=?",      "",      0,
        "QUJDQQ=",   "ABC",   4,
        "QUJDQQ=N",  "ABC",   4,
        "QUJDQQ=?",  "ABC",   4,
    };

    Base64.Decoder[] decs = new Base64.Decoder[] {
        Base64.getDecoder(),
        Base64.getUrlDecoder(),
        Base64.getMimeDecoder()
    };

    for (Base64.Decoder dec : decs) {
        for (int i = 0; i < data.length; i += 3) {
            final String srcStr = (String)data[i];
            final byte[] srcBytes = srcStr.getBytes("ASCII");
            final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);
            byte[] expected = ((String)data[i + 1]).getBytes("ASCII");
            int pos = (Integer)data[i + 2];

            // decode(byte[])
            checkIAE(() -> dec.decode(srcBytes));

            // decode(String)
            checkIAE(() -> dec.decode(srcStr));

            // decode(ByteBuffer)
            checkIAE(() -> dec.decode(srcBB));

            // wrap stream
            checkIOE(new Testable() {
                public void test() throws IOException {
                    try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {
                        while (is.read() != -1);
                    }
            }});
        }
    }
}
 
Example 20
Source File: JWT.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public JsonObject getHeader() throws UnsupportedEncodingException {
    Base64.Decoder decoder = Base64.getUrlDecoder();
    return stringToJson(decoder.decode(header));
}