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:org.cerberus.service.sikuli.impl.SikuliService.java

private JSONObject generatePostParameters(String action, String locator, String text, long defaultWait)
        throws JSONException, IOException, MalformedURLException, MimeTypeException {
    JSONObject result = new JSONObject();
    String picture = "";
    String extension = "";
    /**/*from w  ww .  j  a  v  a2s. c  o  m*/
     * Get Picture from URL and convert to Base64
     */
    if (locator != null) {
        URL url = new URL(locator);
        URLConnection connection = url.openConnection();

        InputStream istream = new BufferedInputStream(connection.getInputStream());

        /**
         * Get the MimeType and the extension
         */
        String mimeType = URLConnection.guessContentTypeFromStream(istream);
        MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
        MimeType mt = allTypes.forName(mimeType);
        extension = mt.getExtension();

        /**
         * Encode in Base64
         */
        byte[] bytes = IOUtils.toByteArray(istream);
        picture = Base64.encodeBase64URLSafeString(bytes);
    }
    /**
     * Build JSONObject with parameters action : Action expected to be done
     * by Sikuli picture : Picture in Base64 format text : Text to type
     * defaultWait : Timeout for the action pictureExtension : Extension for
     * Base64 decoding
     */
    result.put("action", action);
    result.put("picture", picture);
    result.put("text", text);
    result.put("defaultWait", defaultWait);
    result.put("pictureExtension", extension);
    return result;
}

From source file:org.cloudfoundry.identity.uaa.util.UaaTokenUtils.java

public static String constructToken(Map<String, Object> header, Map<String, Object> claims, Signer signer) {
    byte[] headerJson = header == null ? new byte[0] : JsonUtils.writeValueAsBytes(header);
    byte[] claimsJson = claims == null ? new byte[0] : JsonUtils.writeValueAsBytes(claims);

    String headerBase64 = Base64.encodeBase64URLSafeString(headerJson);
    String claimsBase64 = Base64.encodeBase64URLSafeString(claimsJson);
    String headerAndClaims = headerBase64 + "." + claimsBase64;
    byte[] signature = signer.sign(headerAndClaims.getBytes());

    String signatureBase64 = Base64.encodeBase64URLSafeString(signature);

    return headerAndClaims + "." + signatureBase64;
}

From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

/**
 * @param keystore// w w w .j ava  2s.c o m
 * @return
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 */
public static final String keyStore2String(KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    keystore.store(baos, FixedSslCertificateService.PASSPHRASE);
    final byte[] bytes = baos.toByteArray();
    baos.close();
    return Base64.encodeBase64URLSafeString(bytes);
}

From source file:org.dasein.cloud.google.GenerateToken.java

public static String getToken(String iss, String p12File) {

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claimTemplate = "'{'\"iss\": \"{0}\", \"scope\": \"{1}\", \"aud\": \"{2}\", \"exp\": \"{3}\", \"iat\": \"{4}\"'}'";

    try {/* w  w w .j a v  a 2s. com*/
        StringBuffer token = new StringBuffer();

        //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[5];
        claimArray[0] = iss;
        claimArray[1] = "https://www.googleapis.com/auth/compute";
        claimArray[2] = "https://accounts.google.com/o/oauth2/token";
        claimArray[3] = Long.toString((System.currentTimeMillis() / 1000) + 300);
        claimArray[4] = Long.toString((System.currentTimeMillis() / 1000));
        MessageFormat claims;
        claims = new MessageFormat(claimTemplate);
        String payload = claims.format(claimArray);
        //         System.out.println(claimArray[3]);
        //         System.out.println(claimArray[4]);
        //Add the encoded claims object
        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        char[] password = "notasecret".toCharArray();
        FileInputStream fin = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(fin, password);
        } finally {
            try {
                fin.close();
            } catch (IOException e) {
            }
        }
        String alias = "";
        // KeyStore keystore = getKeyStore(password);            
        Enumeration<String> enum1 = store.aliases(); // List the aliases
        while (enum1.hasMoreElements()) {
            String keyStoreAlias = enum1.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) { //Does alias refer to a private key?
                alias = keyStoreAlias;
                break;
            }
        }
        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        //Sign the JWT Header + "." + JWT Claims Object
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(token.toString().getBytes("UTF-8"));
        String signedPayload = Base64.encodeBase64URLSafeString(signature.sign());

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

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

        //      System.out.println(token.toString());
        return token.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.dasein.cloud.google.GoogleMethod.java

static @Nonnull String getToken(@Nonnull String iss, @Nonnull String p12File) throws CloudException {
    if (logger.isDebugEnabled()) {
        logger.debug("iss: " + iss);
        logger.debug("p12File: " + p12File);
    }/*  w  ww. ja  va2s. co m*/

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    StringBuffer token = new StringBuffer();

    try {
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        token.append(".");

        String scope = "https://www.googleapis.com/auth/compute";
        String aud = "https://accounts.google.com/o/oauth2/token";
        String expiry = Long.toString((System.currentTimeMillis() / 1000) + 3600);
        String startTime = Long.toString((System.currentTimeMillis() / 1000));

        String payload = "{\"iss\": \"" + iss + "\", \"scope\": \"" + scope + "\", \"aud\": \"" + aud
                + "\", \"exp\": \"" + expiry + "\", \"iat\": \"" + startTime + "\"}";

        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        // TODO: the password is hardcoded. This has to be read from the ctx or from the environment variable
        char[] password = "notasecret".toCharArray();
        FileInputStream iStream = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(iStream, password);
        } finally {
            try {
                iStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Could not read the keystore file");
                throw new CloudException(e);
            }
        }
        String alias = "";

        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String keyStoreAlias = aliases.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) {
                alias = keyStoreAlias;
                break;
            }
        }

        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        Signature shaSignature = Signature.getInstance("SHA256withRSA");
        shaSignature.initSign(privateKey);
        shaSignature.update(token.toString().getBytes("UTF-8"));
        String signedToken = Base64.encodeBase64URLSafeString(shaSignature.sign());

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

        //Add the encoded signature
        token.append(signedToken);
        return token.toString();

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Could not sign the payload with the private key");
        throw new CloudException(e);
    }
}

From source file:org.dashbuilder.dataset.backend.BackendUUIDGenerator.java

public String uuidToBase64(String str) {
    Base64 base64 = new Base64();
    UUID uuid = UUID.fromString(str);
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return base64.encodeBase64URLSafeString(bb.array());
}

From source file:org.dashbuilder.dataset.UUIDGeneratorImpl.java

public String uuidToBase64(String str) {
    UUID uuid = UUID.fromString(str);
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}

From source file:org.ebayopensource.fido.uaf.ops.AuthenticationRequestGeneration.java

private String generateChallenge() {
    return Base64.encodeBase64URLSafeString(BCrypt.gensalt().getBytes());
}

From source file:org.ebayopensource.fido.uaf.ops.AuthenticationRequestGeneration.java

private String generateServerData(String challenge, Notary notary) {
    String dataToSign = Base64.encodeBase64URLSafeString(("" + System.currentTimeMillis()).getBytes()) + "."
            + Base64.encodeBase64URLSafeString(challenge.getBytes());
    String signature = notary.sign(dataToSign);

    return Base64.encodeBase64URLSafeString((signature + "." + dataToSign).getBytes());
}

From source file:org.ebayopensource.fido.uaf.ops.AuthenticationResponseProcessing.java

private AuthenticatorRecord processAssertions(AuthenticatorSignAssertion authenticatorSignAssertion,
        StorageInterface storage) {//from w  w  w . j a  v  a2  s  .  c o  m
    TlvAssertionParser parser = new TlvAssertionParser();
    AuthenticatorRecord authRecord = new AuthenticatorRecord();
    RegistrationRecord registrationRecord = null;

    try {
        Tags tags = parser.parse(authenticatorSignAssertion.assertion);
        authRecord.AAID = new String(tags.getTags().get(TagsEnum.TAG_AAID.id).value);
        authRecord.KeyID = Base64.encodeBase64URLSafeString(tags.getTags().get(TagsEnum.TAG_KEYID.id).value);
        // authRecord.KeyID = new String(
        // tags.getTags().get(TagsEnum.TAG_KEYID.id).value);
        registrationRecord = getRegistration(authRecord, storage);
        Tag signnedData = tags.getTags().get(TagsEnum.TAG_UAFV1_SIGNED_DATA.id);
        Tag signature = tags.getTags().get(TagsEnum.TAG_SIGNATURE.id);
        Tag info = tags.getTags().get(TagsEnum.TAG_ASSERTION_INFO.id);
        AlgAndEncodingEnum algAndEncoding = getAlgAndEncoding(info);
        String pubKey = registrationRecord.PublicKey;
        try {
            if (!verifySignature(signnedData, signature, pubKey, algAndEncoding)) {
                logger.log(Level.INFO,
                        "Signature verification failed for authenticator: " + authRecord.toString());
                authRecord.status = "FAILED_SIGNATURE_NOT_VALID";
                return authRecord;
            }
        } catch (Exception e) {
            logger.log(Level.INFO, "Signature verification failed for authenticator: " + authRecord.toString(),
                    e);
            authRecord.status = "FAILED_SIGNATURE_VERIFICATION";
            return authRecord;
        }
        authRecord.username = registrationRecord.username;
        authRecord.deviceId = registrationRecord.deviceId;
        authRecord.status = "SUCCESS";
        return authRecord;
    } catch (IOException e) {
        logger.log(Level.INFO, "Fail to parse assertion: " + authenticatorSignAssertion.assertion, e);
        authRecord.status = "FAILED_ASSERTION_VERIFICATION";
        return authRecord;
    }
}