Example usage for java.util Base64 getUrlEncoder

List of usage examples for java.util Base64 getUrlEncoder

Introduction

In this page you can find the example usage for java.util Base64 getUrlEncoder.

Prototype

public static Encoder getUrlEncoder() 

Source Link

Document

Returns a Encoder that encodes using the URL and Filename safe type base64 encoding scheme.

Usage

From source file:org.codelibs.fess.app.web.admin.user.AdminUserAction.java

private static OptionalEntity<User> getEntity(final CreateForm form) {
    switch (form.crudMode) {
    case CrudMode.CREATE:
        return OptionalEntity.of(new User()).map(entity -> {
            entity.setId(Base64.getUrlEncoder().encodeToString(form.name.getBytes(Constants.CHARSET_UTF_8)));
            return entity;
        });//from   w  ww.jav a  2  s .  c  o  m
    case CrudMode.EDIT:
        if (form instanceof EditForm) {
            return ComponentUtil.getComponent(UserService.class).getUser(((EditForm) form).id);
        }
        break;
    default:
        break;
    }
    return OptionalEntity.empty();
}

From source file:org.codelibs.fess.helper.DocumentHelper.java

public String encodeSimilarDocHash(final String hash) {
    if (hash != null && !hash.startsWith(SIMILAR_DOC_HASH_PREFIX)) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            try (GZIPOutputStream gos = new GZIPOutputStream(baos)) {
                gos.write(hash.getBytes(Constants.UTF_8));
            }/*w w  w .  jav  a2  s.  com*/
            return SIMILAR_DOC_HASH_PREFIX
                    + Base64.getUrlEncoder().withoutPadding().encodeToString(baos.toByteArray());
        } catch (final IOException e) {
            logger.warn("Failed to encode " + hash, e);
        }
    }
    return hash;
}

From source file:org.codelibs.fess.taglib.FessFunctions.java

public static String base64(final String value) {
    if (value == null) {
        return StringUtil.EMPTY;
    }/*w  ww.  j  a v a 2  s  .co m*/
    return Base64.getUrlEncoder().encodeToString(value.getBytes(Constants.CHARSET_UTF_8));
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java

private boolean validateToken(Map<String, String> credentials) {
    final String token = credentials.get(PROPERTY_TOKEN);
    final Map<String, String> tokenMap = parseToken(token);
    final String username = tokenMap.get(PROPERTY_USERNAME);
    final String time = tokenMap.get("time");
    final String password = credentialStore.findUser(username).value(PROPERTY_PASSWORD);
    final String salt = getBcryptSaltFromStoredPassword(password);
    final String expected = generateToken(username, salt, time);
    final Long timeLong = Long.parseLong(time);
    final Long currentTime = new Date().getTime();
    final String base64Token = new String(Base64.getUrlEncoder().encode(token.getBytes()));
    //Short circuit if the lengths aren't the same or time has expired
    if (timeLong + timeout < currentTime || expected.length() != base64Token.length()) {
        return false;
    } else {/*from w w w . j a  va2s  .c  om*/
        //Don't short circuit comparison to prevent timing attacks
        boolean isValid = true;
        for (int i = 0; i < expected.length(); i++) {
            if (base64Token.charAt(i) != expected.charAt(i)) {
                isValid = false;
            }
        }
        return isValid;
    }
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java

private String generateToken(final String username, final String salt, final String time) {
    try {/*from  ww  w. j  a  v  a  2  s. c  o  m*/
        final CharBuffer secretAndSalt = CharBuffer.allocate(secret.length + salt.length() + 1);
        secretAndSalt.put(secret);
        secretAndSalt.put(":");
        secretAndSalt.put(salt);
        final String tokenPrefix = username + ":" + time.toString() + ":";
        final SecretKeySpec keySpec = new SecretKeySpec(toBytes(secretAndSalt.array()), hmacAlgo);
        final Mac hmac = Mac.getInstance(hmacAlgo);
        hmac.init(keySpec);
        hmac.update(username.getBytes());
        hmac.update(time.toString().getBytes());
        final Base64.Encoder encoder = Base64.getUrlEncoder();
        final byte[] hmacbytes = encoder.encode(hmac.doFinal());
        final byte[] tokenbytes = tokenPrefix.getBytes();
        final byte[] token = ByteBuffer.wrap(new byte[tokenbytes.length + hmacbytes.length]).put(tokenbytes)
                .put(hmacbytes).array();
        return new String(encoder.encode(token));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.wso2.carbon.apimgt.keymgt.token.APIMJWTGenerator.java

public String generateJWT(JwtTokenInfoDTO jwtTokenInfoDTO) throws APIManagementException {

    String jwtHeader = buildHeader(jwtTokenInfoDTO);

    String base64UrlEncodedHeader = "";
    if (jwtHeader != null) {
        base64UrlEncodedHeader = Base64.getUrlEncoder()
                .encodeToString(jwtHeader.getBytes(Charset.defaultCharset()));
    }/*  w  w  w  .j ava 2  s.  c om*/

    String jwtBody = buildBody(jwtTokenInfoDTO);
    String base64UrlEncodedBody = "";
    if (jwtBody != null) {
        base64UrlEncodedBody = Base64.getUrlEncoder().encodeToString(jwtBody.getBytes());
    }

    if (SHA256_WITH_RSA.equals(signatureAlgorithm)) {
        String assertion = base64UrlEncodedHeader + '.' + base64UrlEncodedBody;

        //get the assertion signed
        byte[] signedAssertion = signJWT(assertion, jwtTokenInfoDTO.getEndUserName());

        if (log.isDebugEnabled()) {
            log.debug("signed assertion value : " + new String(signedAssertion, Charset.defaultCharset()));
        }
        String base64UrlEncodedAssertion = Base64.getUrlEncoder().encodeToString(signedAssertion);

        return base64UrlEncodedHeader + '.' + base64UrlEncodedBody + '.' + base64UrlEncodedAssertion;
    } else {
        return base64UrlEncodedHeader + '.' + base64UrlEncodedBody + '.';
    }
}

From source file:org.zoxweb.shared.util.Base64Test.java

public static void main(String[] arg) {
    byte[] num = { 0, 1, 2 };

    String toConvert = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";

    System.out.println(toConvert.length());
    //System.out.println(SharedBase64.computeBase64ArraySize(num));
    System.out.println(new String(SharedBase64.encode(num)));

    long tsOld = System.nanoTime();
    byte[] oldBase64 = SharedBase64.encode(toConvert.getBytes());

    byte[] decodedBase64 = SharedBase64.decode(oldBase64);

    tsOld = System.nanoTime() - tsOld;
    System.out.println(oldBase64.length);
    System.out.println(new String(oldBase64));
    System.out.println(new String(decodedBase64));
    System.out.println(tsOld + "nanos");

    String[] testArray = { "1", "12", "123", "1234", "12345", "123456", "1234567", "12345678", "123456789",
            "1234567890", "a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefgh", "abcdefghi",
            "abcdefghij", toConvert, "asure.", "sure.", "any carnal pleasure" };

    String partial = "naelmarwan";

    System.out.println("Length of Array: " + testArray.length);
    long tsJ, tsZW;
    byte[] sharedEncodedeBase64, sharedDecodedBase64, java64Encoded, java64Decodded;
    Encoder javaEncoder = java.util.Base64.getEncoder();
    Decoder javaDecoder = java.util.Base64.getDecoder();
    for (int i = 0; i < testArray.length; i++) {
        System.out.println(i + 1 + "." + "Original Value: " + testArray[i]);

        byte toEncode[] = testArray[i].getBytes();
        tsZW = System.nanoTime();
        sharedEncodedeBase64 = SharedBase64.encode(Base64Type.DEFAULT, toEncode, 0, toEncode.length);
        sharedDecodedBase64 = SharedBase64.decode(Base64Type.DEFAULT, sharedEncodedeBase64, 0,
                sharedEncodedeBase64.length);
        tsZW = System.nanoTime() - tsZW;

        tsZW = System.nanoTime();
        sharedEncodedeBase64 = SharedBase64.encode(Base64Type.DEFAULT, toEncode, 0, toEncode.length);
        sharedDecodedBase64 = SharedBase64.decode(Base64Type.DEFAULT, sharedEncodedeBase64, 0,
                sharedEncodedeBase64.length);
        tsZW = System.nanoTime() - tsZW;

        tsJ = System.nanoTime();/* w w  w  .ja  v  a  2s.  c  o  m*/
        java64Encoded = javaEncoder.encode(toEncode);//.encodeBase64(toEncode);
        java64Decodded = javaDecoder.decode(java64Encoded);
        tsJ = System.nanoTime() - tsJ;

        tsJ = System.nanoTime();
        java64Encoded = javaEncoder.encode(toEncode);//.encodeBase64(toEncode);
        java64Decodded = javaDecoder.decode(java64Encoded);
        tsJ = System.nanoTime() - tsJ;

        System.out.println(i + 1 + "." + "Encode Base64: " + new String(sharedEncodedeBase64) + ":\t\t"
                + Arrays.equals(sharedEncodedeBase64, java64Encoded));
        System.out.println(i + 1 + "." + "Decoded Base64: " + new String(sharedDecodedBase64) + ":\t\t"
                + Arrays.equals(sharedDecodedBase64, java64Decodded));
        System.out.println("zoxweb:" + tsZW + " java:" + tsJ + " delta:" + (tsJ - tsZW) + " factor:"
                + ((float) tsJ / (float) tsZW));
        System.out.println(tsZW + " nanos: " + testArray[i].equals(new String(sharedDecodedBase64)));
    }

    byte[] byteArray = new byte[256];

    for (int i = 0; i < byteArray.length; i++) {
        byteArray[i] = (byte) i;
    }

    byte[] byteArrayBase64 = SharedBase64.encode(byteArray);
    System.out.println(new String(byteArrayBase64));
    System.out
            .println("Original Array length:" + byteArray.length + " base 64 length:" + byteArrayBase64.length);
    byte[] byteArrayOriginal = SharedBase64.decode(byteArrayBase64);
    System.out.println(Arrays.equals(byteArray, byteArrayOriginal));

    System.out.println("BASE_64 length:" + SharedBase64.BASE_64.length + " REVERSE_BASE_64 length:"
            + SharedBase64.REVERSE_BASE_64.length);

    System.out.println("Partial test:" + new String(SharedBase64.encode(partial.getBytes(), 4, 6)) + ","
            + new String(SharedBase64.encode(partial.getBytes(), 1, 1)));
    byte fullname[] = SharedBase64.encode(partial.getBytes());
    System.out.println("Marwan " + new String(fullname));

    System.out.println("Equals:" + SharedUtil.slowEquals(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes(),
            SharedBase64.BASE_64));

    try {
        byte[] b64 = SharedBase64.encode("1234567890");
        String str = SharedStringUtil.toString(b64);
        System.out.println("1234567890 b64:" + str);
        System.out.println(SharedBase64.decodeAsString(Base64Type.DEFAULT, "MTIzNDU2Nzg5MA"));
        System.out.println(SharedBase64.decodeAsString(Base64Type.DEFAULT, "MTIzNDU2Nzg5MA="));

        b64 = SharedBase64.decode(str + "^");
    } catch (Exception e) {
        e.printStackTrace();
    }

    UUID uuid = UUID.randomUUID();

    byte[] uuidBytes = BytesValue.LONG.toBytes(null, 0, uuid.getMostSignificantBits(),
            uuid.getMostSignificantBits());
    String str = SharedStringUtil.toString(SharedBase64.encode(Base64Type.URL, uuidBytes));
    String str1 = Base64.getUrlEncoder().encodeToString(uuidBytes);
    System.out.println(str + " " + str1 + " " + str1.equals(str));

    byte[] b = SharedBase64.decode(Base64Type.URL, str);
    byte[] b1 = Base64.getUrlDecoder().decode(str);
    System.out.println(Arrays.equals(uuidBytes, b) + " " + Arrays.equals(uuidBytes, b1));
    str = SharedStringUtil.toString(SharedBase64.encode(Base64Type.URL, b));
    System.out.println(str);

    String base64URL = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
    String plain = SharedBase64.decodeAsString(Base64Type.URL, base64URL);
    System.out.println(plain);
    System.out.println(SharedBase64.encodeAsString(Base64Type.URL, plain));
}