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.cliqset.magicsig.encoding.Base64URLMagicSigEncoding.java

public String encodeToString(byte[] data) {
    String b64 = Base64.encodeBase64URLSafeString(data);
    //looks like encodeBase64URLSafeString doesn't pad to / 4
    while (b64.length() % 4 != 0) {
        b64 += (char) 61;
    }/* w  w  w.  j a  v a  2  s  .co  m*/
    return b64;
}

From source file:guru.bubl.module.model.User.java

private String encode(String password) {
    if (password == null)
        throw new IllegalArgumentException("Missing password");

    // the salt is composed of the email and salt. This way, two member objects with
    // the same email and same password can have two different hash
    return Base64.encodeBase64URLSafeString(DigestUtils.sha512(password + salt));
}

From source file:de.eod.jliki.users.utils.PasswordHashUtility.java

/**
 * Generates a hash string (url save) from the given data.<br/>
 * @param data the data to hash/* www .  j a v  a  2 s  .  c  om*/
 * @return a string in url save format
 */
public static String generateHashForUrl(final String data) {
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance(ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        LOGGER.fatal("Hash algorithm not found: " + ALGORITHM, e);
        return "";
    }
    digest.reset();
    byte[] hashBytes;
    try {
        hashBytes = digest.digest(data.getBytes(ENCODING));
    } catch (final UnsupportedEncodingException e) {
        LOGGER.fatal("Character encoding not supported: " + ENCODING, e);
        return "";
    }

    final String hashString = Base64.encodeBase64URLSafeString(hashBytes);
    return hashString;
}

From source file:ch.newscron.encryption.Encryption.java

/**
 * Given a JSONObject, and maybe an hash, it is encoded and returned as a String.
 * @param inviteData is a JSONObject having the data with the keys "customerId", "rew1", "rew2" and "val"
 * @param md5Hash is a String that substitute the hash computed using md5 algorithm, in case it is not null and not empty
 * @return encoded string //from   ww w.j  a v a 2s . c o  m
 */
protected static String encode(JSONObject inviteData, String md5Hash) {

    try {
        //Check in case we want to add a given hash (having at the end a corrupt data)
        if (md5Hash != null && !md5Hash.isEmpty()) {
            //Add md5Hash to JSONObject
            inviteData.put("hash", md5Hash);
        } else {
            return null;
        }

        //Encode inviteData (with hash) JSONObject
        String params = inviteData.toString();
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));
        return Base64.encodeBase64URLSafeString(cipher.doFinal(params.getBytes())); //to ensure valid URL characters
    } catch (Exception e) {
    }

    return null;
}

From source file:guru.bubl.module.model.UserTest.java

@Test
public void password_is_encoded_with_salt() {
    String password = "Potatoe";
    User user = User.withEmail("roger@lamothe.org").password(password);
    String expectedPasswordHash = Base64.encodeBase64URLSafeString(DigestUtils.sha512(password + user.salt()));
    assertThat(user.passwordHash(), is(expectedPasswordHash));
}

From source file:ch.newscron.newscronjsp.ReferralSignUpServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   www  .  j a  v a  2  s.co  m*/

        String[] urlPartsPath = request.getRequestURI().split("/");
        String encodedDataString = urlPartsPath[urlPartsPath.length - 1];

        String decodedDataString = Encryption.decode(encodedDataString);

        if (decodedDataString != null) {
            JSONParser parser = new JSONParser();
            JSONObject decodedJSON = (JSONObject) parser.parse(decodedDataString);

            String dateValidity = (String) decodedJSON.get("val");
            if (isDateValid(dateValidity)) { // Date validity not expired & not null from decoding URL
                String rewardNewUser = (String) decodedJSON.get("rew2");
                String signupPageReferral = "%s/%s";
                signupPageReferral = String.format(signupPageReferral, encodedDataString,
                        Base64.encodeBase64URLSafeString(rewardNewUser.getBytes()));
                signupPage += signupPageReferral;
            }
        }

    } catch (Exception ex) {
        Logger.getLogger(ShortUrlCreator.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        response.sendRedirect(signupPage);
    }
}

From source file:com.muk.ext.security.impl.DefaultNonceService.java

@Override
public String encodeUrlSafe(byte[] byteArray) {
    return Base64.encodeBase64URLSafeString(byteArray);
}

From source file:com.yalin.fidouaf.res.util.DeregRequestProcessor.java

public DeregistrationRequest[] process(String payload) {
    DeregistrationRequest[] deregFromJson = null;
    try {/*from   w  w w.  jav a2  s .  c  o m*/
        deregFromJson = gson.fromJson(payload, DeregistrationRequest[].class);
        DeregistrationRequest deregRequest = deregFromJson[0];
        deregRequest.header = new OperationHeader();
        deregRequest.header.op = Operation.Dereg;
        deregRequest.header.appID = appId;
        deregRequest.header.upv = new Version(1, 0);
        Dash.getInstance().stats.put(Dash.LAST_DEREG_REQ, deregFromJson);
        AuthenticatorRecord authRecord = new AuthenticatorRecord();
        for (DeregisterAuthenticator authenticator : deregRequest.authenticators) {
            authRecord.AAID = authenticator.aaid;
            authRecord.KeyID = Base64.encodeBase64URLSafeString(authenticator.keyID.getBytes());
            try {
                String Key = authRecord.toString();
                StorageImpl.getInstance().deleteRegistrationRecord(Key);
            } catch (Exception e) {
                return null;
            }
        }
    } catch (Exception e) {
        return null;
    }
    return deregFromJson;
}

From source file:cloud.google.oauth2.MyWayAuthentication.java

public String getAssertion(long exp, long iat) throws Exception {
    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claimTemplate = "'{'\"iss\": \"{0}\", \"scope\": \"{1}\", \"aud\": \"{2}\", \"exp\": {3}, \"iat\": {4}'}'";
    StringBuffer token = new StringBuffer();

    /**/*  w ww .j ava  2  s . c  o m*/
     * Encode the JWT Header and add it to our string to sign
     * */
    token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

    /**
     * Separate with a period
     * */
    token.append(".");

    /**
     * Create the JWT Claims Object
     * */
    String[] claimArray = new String[6];
    claimArray[0] = this.iss;
    claimArray[1] = GCDStatic.getScope();
    claimArray[2] = GCDStatic.getAud();
    claimArray[3] = "" + exp;
    claimArray[4] = "" + iat;

    MessageFormat claims = new MessageFormat(claimTemplate);
    String payload = claims.format(claimArray);

    /**
     * Add the encoded claims object
     * */
    token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

    /**
     * Load the private key
     * */
    PrivateKey privateKey = getPrivateKey(this.keystoreLoc, GCDStatic.getPassword());
    byte[] sig = signData(token.toString().getBytes("UTF-8"), privateKey);

    String signedPayload = Base64.encodeBase64URLSafeString(sig);

    /**
     * Separate with a period
     * */
    token.append(".");

    /**
     * Add the encoded signature
     * */
    token.append(signedPayload);

    return token.toString();
}

From source file:com.github.sshw.crypt.EncryptionBean.java

public String encrypt(String message, String password) throws Exception {
    Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    Key key = keyFromPassword(password);
    IvParameterSpec ivb = new IvParameterSpec(key.getEncoded());
    encrypt.init(Cipher.ENCRYPT_MODE, key, ivb);
    byte[] cb = encrypt.doFinal(message.getBytes());
    String c = Base64.encodeBase64URLSafeString(cb);
    return c;//w w w. j  a v a 2  s  .c  om
}