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.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java

public String getChecksumBy(final String key)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()));
    mac.update((cardToken + mctTransAuthId + ocTransAuthId
            + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(mac.doFinal());
}

From source file:com.monitor.baseservice.utils.XCodeUtil.java

public static String sha1UrlSafeB64(byte[] bytes) {
    try {//from   ww w.  j a  va2 s  . c  o m
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(bytes);
        return Base64.encodeBase64URLSafeString(md.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:GCS_Auth.java

public GCS_Auth(String client_id, String key) {
    String SCOPE = "https://www.googleapis.com/auth/shoppingapi";
    SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent";
    try {//from w w w .  j a va 2s  .  c o  m
        String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

        long now = System.currentTimeMillis() / 1000L;
        long exp = now + 3600;
        String iss = client_id;
        String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE
                + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now
                + "}";

        String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));

        byte[] jwt_data = jwt.getBytes("UTF8");

        Signature sig = Signature.getInstance("SHA256WithRSA");

        KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), "notasecret".toCharArray());

        sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray()));
        sig.update(jwt_data);
        byte[] signatureBytes = sig.sign();
        String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        String assertion = jwt + "." + b64sig;

        //System.out.println("Assertion: " + assertion);

        String data = "grant_type=assertion";
        data += "&" + "assertion_type" + "="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
        data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8");

        URLConnection conn = null;
        try {
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            InputStream error = ((HttpURLConnection) conn).getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        //System.out.println(access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.mobicage.rogerthat.mfr.dal.Streamable.java

public String toBase64() {
    try {/*from   w  ww.  ja  v  a2s.c  o m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ZipOutputStream zip = new ZipOutputStream(bos);
            try {
                zip.setLevel(9);
                zip.putNextEntry(new ZipEntry("entry"));
                try {
                    ObjectOutput out = new ObjectOutputStream(zip);
                    try {
                        out.writeObject(this);
                    } finally {
                        out.flush();
                    }
                } finally {
                    zip.closeEntry();
                }
                zip.flush();
                return Base64.encodeBase64URLSafeString(bos.toByteArray());
            } finally {
                zip.close();
            }
        } finally {
            bos.close();
        }
    } catch (IOException e) {
        log.log((Level.SEVERE), "IO Error while serializing member", e);
        return null;
    }
}

From source file:com.google.u2f.gaedemo.impl.DataStoreImpl.java

@Override
public String storeSessionData(EnrollSessionData sessionData) {

    SecretKey key = new SecretKeySpec(SecretKeys.get().sessionEncryptionKey(), "AES");
    byte[] ivBytes = new byte[16];
    random.nextBytes(ivBytes);/* w  w  w  .j  a v a  2 s.  c o  m*/
    final IvParameterSpec IV = new IvParameterSpec(ivBytes);
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, IV);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }

    SealedObject sealed;
    try {
        sealed = new SealedObject(sessionData, cipher);
    } catch (IllegalBlockSizeException | IOException e) {
        throw new RuntimeException(e);
    }

    ByteArrayOutputStream out;
    try {
        out = new ByteArrayOutputStream();
        ObjectOutputStream outer = new ObjectOutputStream(out);

        outer.writeObject(sealed);
        outer.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return Base64.encodeBase64URLSafeString(out.toByteArray());
}

From source file:com.google.u2f.client.impl.U2FClientReferenceImpl.java

@Override
public void register(String origin, String accountName) throws U2FException {
    RegistrationRequest registrationRequest = server.getRegistrationRequest(accountName, origin);

    String version = registrationRequest.getVersion();
    String serverChallengeBase64 = registrationRequest.getChallenge();
    String appId = registrationRequest.getAppId();
    String sessionId = registrationRequest.getSessionId();

    if (!version.equals(U2FConsts.U2F_V2)) {
        throw new U2FException(String.format("Unsupported protocol version: %s", version));
    }/*  w w  w  . j  a  v a  2  s .c o  m*/

    appIdVerifier.validateOrigin(appId, origin);

    JsonObject channelIdJson = channelIdProvider.getJsonChannelId();

    String clientData = ClientDataCodec.encodeClientData(ClientDataCodec.REQUEST_TYPE_REGISTER,
            serverChallengeBase64, origin, channelIdJson);

    byte[] appIdSha256 = crypto.computeSha256(appId);
    byte[] clientDataSha256 = crypto.computeSha256(clientData);

    RegisterResponse registerResponse = key.register(new RegisterRequest(appIdSha256, clientDataSha256));

    byte[] rawRegisterResponse = RawMessageCodec.encodeRegisterResponse(registerResponse);
    String rawRegisterResponseBase64 = Base64.encodeBase64URLSafeString(rawRegisterResponse);
    String clientDataBase64 = Base64.encodeBase64URLSafeString(clientData.getBytes());

    server.processRegistrationResponse(
            new RegistrationResponse(rawRegisterResponseBase64, clientDataBase64, sessionId),
            System.currentTimeMillis());
}

From source file:com.github.ambry.commons.BlobId.java

@Override
public String getID() {
    return Base64.encodeBase64URLSafeString(toBytes());
}

From source file:com.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java

public boolean isValidBy(final String key, final String checksum)
        throws NoSuchAlgorithmException, IOException, InvalidKeyException {
    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()));
    mac.update((cardToken + mctTransAuthId + ocTransAuthId
            + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(mac.doFinal()).equals(checksum);
}

From source file:com.vmware.vchs.api.samples.services.Compute.java

/**
 * This method will log in to compute using the provided URL (which should be the /api/sessions
 * path)./*w w  w . j  a va  2  s .  c  o m*/
 * 
 * @param url the url to the VCD API to make requests to
 * @param username the username to log in with
 * @param password the password to log in with
 * @param orgName the org name to use as part of the login process
 * @param version the version of the API to call
 * @return the value of the header x-vcloud-authorization if login success
 */
public static final String login(String url, String username, String password, String orgName, String version) {
    // Default base URL to log in to using the provided URL
    HttpPost post = new HttpPost(url);

    // Encode the username and password provided via the command line options.username and
    // options.password appending the provided orgName to the username before encoding. Compute
    // services require username@orgName:password syntax to log in with.
    String auth = "Basic " + Base64
            .encodeBase64URLSafeString(new String(username + "@" + orgName + ":" + password).getBytes());

    post.setHeader(HttpHeaders.AUTHORIZATION, auth);
    post.setHeader(HttpHeaders.ACCEPT,
            SampleConstants.APPLICATION_PLUS_XML_VERSION + version + ";charset=utf-8");

    HttpResponse response = HttpUtils.httpInvoke(post);

    if (null != response) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Return the response header x-vcloud-authorization which contains the session
            // token for the now logged in user.
            return response.getFirstHeader(SampleConstants.VCD_AUTHORIZATION_HEADER).getValue();
        }
    }

    return null;
}

From source file:net.oauth.signatures.SignedOAuthToken.java

private String getBodyHash(byte[] requestBody) {
    Preconditions.checkNotNull(requestBody);
    String hashAlg = getSignatureAlgorithm().getHashAlgorithm();
    MessageDigest digest;//from ww  w  .j  ava2 s .c om
    try {
        digest = MessageDigest.getInstance(hashAlg);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("platform is missing hash algorithm: " + hashAlg);
    }
    byte[] hash = digest.digest(requestBody);
    return Base64.encodeBase64URLSafeString(hash);
}