Example usage for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString.

Prototype

public static String encodeBase64URLSafeString(final byte[] binaryData) 

Source Link

Document

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.

Usage

From source file:com.streamsets.datacollector.restapi.TestRestApiAuthorization.java

private void test(List<RestApi> apis, boolean authzEnabled) throws Exception {
    String baseUrl = startServer(authzEnabled);
    try {//from ww  w.  j ava 2  s . c om
        for (RestApi api : apis) {
            Set<String> has = api.roles;
            for (String user : ALL_ROLES) {
                user = "guest";
                URL url = new URL(baseUrl + api.uriPath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty(CsrfProtectionFilter.HEADER_NAME, "CSRF");
                if (authzEnabled) {
                    conn.setRequestProperty("Authorization",
                            "Basic " + Base64.encodeBase64URLSafeString((user + ":" + user).getBytes()));
                }
                conn.setRequestMethod(api.method.name());
                conn.setDefaultUseCaches(false);
                if (authzEnabled) {
                    if (has.contains(user)) {
                        Assert.assertNotEquals(
                                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                        api.method, api.uriPath),
                                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                    } else {
                        Assert.assertEquals(
                                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                        api.method, api.uriPath),
                                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                    }
                } else {
                    Assert.assertNotEquals(
                            Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                    api.method, api.uriPath),
                            HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                }
            }
        }
    } finally {
        stopServer();
    }
}

From source file:com.smartitengineering.cms.spi.impl.events.EventPublisherTest.java

public static String getContentMsg() {
    final byte[] contentId = StringUtils.getBytesUtf8(new StringBuilder(WORSPACE_NS).append('\n')
            .append(WORKSPACE_NAME).append('\n').append(CONTENT_ID).toString());
    final String msgContent = new StringBuilder("CONTENT\nCREATE\n")
            .append(Base64.encodeBase64URLSafeString(contentId)).toString();
    return msgContent;
}

From source file:com.cloud.vm.VMInstanceVO.java

public VMInstanceVO(long id, long serviceOfferingId, String name, String instanceName, Type type,
        Long vmTemplateId, HypervisorType hypervisorType, long guestOSId, long domainId, long accountId,
        long userId, boolean haEnabled) {
    this.id = id;
    hostName = name != null ? name : uuid;
    if (vmTemplateId != null) {
        templateId = vmTemplateId;// w w w .  j  a  v a2  s  . co m
    }
    this.instanceName = instanceName;
    this.type = type;
    this.guestOSId = guestOSId;
    this.haEnabled = haEnabled;
    state = State.Stopped;
    this.accountId = accountId;
    this.domainId = domainId;
    this.serviceOfferingId = serviceOfferingId;
    this.hypervisorType = hypervisorType;
    this.userId = userId;
    limitCpuUse = false;
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] randomBytes = new byte[16];
        random.nextBytes(randomBytes);
        vncPassword = Base64.encodeBase64URLSafeString(randomBytes);
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e);
    }
}

From source file:com.google.gerrit.server.mail.send.FromAddressGeneratorProvider.java

private static String hashOf(String data) {
    try {/*from  ww w  .ja  va 2 s.  com*/
        MessageDigest hash = MessageDigest.getInstance("MD5");
        byte[] bytes = hash.digest(data.getBytes(UTF_8));
        return Base64.encodeBase64URLSafeString(bytes);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("No MD5 available", e);
    }
}

From source file:manager.doUpdateToy.java

public String encodeImage(byte[] imageByteArray) {
    return Base64.encodeBase64URLSafeString(imageByteArray);

}

From source file:com.smartitengineering.cms.spi.impl.events.EventPublisherTest.java

public static String getContentTypeMsg() {
    final byte[] contentId = StringUtils
            .getBytesUtf8(new StringBuilder(WORSPACE_NS).append('\n').append(WORKSPACE_NAME).append('\n')
                    .append(CONTENT_TYPE_NS).append('\n').append(CONTENT_TYPE_NAME).toString());
    final String msgContent = new StringBuilder("CONTENT_TYPE\nCREATE\n")
            .append(Base64.encodeBase64URLSafeString(contentId)).toString();
    return msgContent;
}

From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java

@Override
public U2fSignRequest getSignRequest(String accountName, String appId) throws U2FException {
    Log.info(">> getSignRequest " + accountName);

    List<SecurityKeyData> securityKeyDataList = dataStore.getSecurityKeyData(accountName);

    byte[] challenge = challengeGenerator.generateChallenge(accountName);
    String challengeBase64 = Base64.encodeBase64URLSafeString(challenge);

    ImmutableList.Builder<RegisteredKey> registeredKeys = ImmutableList.builder();
    Log.info("  challenge: " + Hex.encodeHexString(challenge));
    for (SecurityKeyData securityKeyData : securityKeyDataList) {
        SignSessionData sessionData = new SignSessionData(accountName, appId, challenge,
                securityKeyData.getPublicKey());
        String sessionId = dataStore.storeSessionData(sessionData);

        byte[] keyHandle = securityKeyData.getKeyHandle();
        List<Transports> transports = securityKeyData.getTransports();
        Log.info("-- Output --");
        Log.info("  sessionId: " + sessionId);
        Log.info("  keyHandle: " + Hex.encodeHexString(keyHandle));

        String keyHandleBase64 = Base64.encodeBase64URLSafeString(keyHandle);

        Log.info("<< getRegisteredKey " + accountName);
        registeredKeys.add(new RegisteredKey(U2FConsts.U2F_V2, keyHandleBase64, transports, appId, sessionId));
    }//  ww  w .ja  va  2  s  . c om

    return new U2fSignRequest(challengeBase64, registeredKeys.build());
}

From source file:co.cask.cdap.gateway.util.Util.java

public static String encodeBinary(byte[] binary, String encoding, boolean counter) {
    if (counter && Bytes.SIZEOF_LONG == binary.length) {
        return Long.toString(Bytes.toLong(binary));
    }/*from  w ww  . j a v  a2  s.  c  o  m*/
    if (encoding == null) {
        return new String(binary, Charsets.US_ASCII);
    }
    if ("hex".equals(encoding)) {
        return toHex(binary);
    }
    if ("base64".equals(encoding)) {
        return Base64.encodeBase64URLSafeString(binary);
    }
    if ("url".equals(encoding)) {
        try {
            // URLEncoder does not take byte[], so we convert it into a String with the same code points using
            // ISO-8859-1. This string only contains code points 0-255. Then we URL-encode that string using
            // ISO-8859-1 again. This way, every byte ends up as the exact same, %-escaped byte, in the URL string
            return URLEncoder.encode(new String(binary, Charsets.ISO_8859_1), Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            // can't happen
            throw new RuntimeException("Charsets.ISO_8859_1 is unsupported? Something is wrong with the JVM",
                    e);
        }
    }
    // this can never happen because we only call it with null, hex, base64, or url
    throw new IllegalArgumentException(
            "Unexpected encoding: " + encoding + " Only hex, base64 and url are supported.");
}

From source file:me.adaptive.core.data.api.UserRegistrationService.java

/**
 * This will generate a token with the following format:
 * base64(id:sha1(currentPassword:SALT):base64(timestamp))
 *
 * @param user/*from  w  w  w.j  a va  2 s. c o  m*/
 * @return the token string
 */
String generateTemporaryValidationToken(UserEntity user) {

    return Base64.encodeBase64URLSafeString((user.getId().toString() + ':' + getValidationHash(user) + ':'
            + Base64.encodeBase64String(String.valueOf(System.currentTimeMillis()).getBytes())).getBytes());
}

From source file:com.smartitengineering.cms.spi.impl.events.EventPublisherTest.java

public static String getSequenceMsg() {
    final byte[] contentId = StringUtils.getBytesUtf8(new StringBuilder(WORSPACE_NS).append('\n')
            .append(WORKSPACE_NAME).append('\n').append(SEQUENCE_NAME).toString());
    final String msgContent = new StringBuilder("SEQUENCE\nCREATE\n")
            .append(Base64.encodeBase64URLSafeString(contentId)).toString();
    return msgContent;
}