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:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association setHandle(Association association) throws AssociationException, IOException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException {
    ByteArrayOutputStream encodedAssociation = new ByteArrayOutputStream();
    String type = association.getType();
    if (type == Association.TYPE_HMAC_SHA1) {
        encodedAssociation.write(1);//from  ww  w .  j  av  a  2  s  .  c o m
    } else if (type == Association.TYPE_HMAC_SHA256) {
        encodedAssociation.write(2);
    } else {
        throw new AssociationException("unknown type: " + type);
    }
    SecretKey macKey = association.getMacKey();
    byte[] macKeyBytes = macKey.getEncoded();
    encodedAssociation.write(macKeyBytes);
    Date expiry = association.getExpiry();
    Long time = expiry.getTime();
    DataOutputStream dos = new DataOutputStream(encodedAssociation);
    dos.writeLong(time);
    dos.flush();
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    byte[] iv = new byte[16];
    this.secureRandom.nextBytes(iv);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] handleValue = cipher.doFinal(encodedAssociation.toByteArray());
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    result.write(iv);
    result.write(handleValue);
    if (null != this.macSecretKeySpec) {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] toBeSigned = result.toByteArray();
        byte[] signature = mac.doFinal(toBeSigned);
        result = new ByteArrayOutputStream();
        result.write(signature);
        result.write(iv);
        result.write(handleValue);
    }
    String handle = Base64.encodeBase64URLSafeString(result.toByteArray());
    this.secureRandom.setSeed(result.toByteArray());
    if (handle.getBytes().length > 255) {
        throw new AssociationException("handle size > 255");
    }
    if (type == Association.TYPE_HMAC_SHA1) {
        return Association.createHmacSha1(handle, macKeyBytes, expiry);
    } else if (type == Association.TYPE_HMAC_SHA256) {
        return Association.createHmacSha256(handle, macKeyBytes, expiry);
    }
    throw new AssociationException("unknown type: " + type);
}

From source file:com.turo.pushy.apns.AuthenticationToken.java

public boolean verifySignature(final ApnsVerificationKey verificationKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    if (!this.header.getKeyId().equals(verificationKey.getKeyId())) {
        return false;
    }/*  w  w  w  .j av a 2  s  .c om*/

    if (!this.claims.getIssuer().equals(verificationKey.getTeamId())) {
        return false;
    }

    final byte[] headerAndClaimsBytes;

    final String headerJson = GSON.toJson(this.header);
    final String claimsJson = GSON.toJson(this.claims);

    final StringBuilder headerAndClaimsBuilder = new StringBuilder();

    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII)));
    headerAndClaimsBuilder.append('.');
    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII)));

    headerAndClaimsBytes = headerAndClaimsBuilder.toString().getBytes(StandardCharsets.US_ASCII);

    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initVerify(verificationKey);
    signature.update(headerAndClaimsBytes);

    return signature.verify(this.signatureBytes);
}

From source file:annis.libgui.Helper.java

private static String encodeBase64URL(String val) {
    try {/*from ww w. ja va  2  s  .c  o  m*/
        return Base64.encodeBase64URLSafeString(val.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        log.error("Java Virtual Maschine can't handle UTF-8: I'm utterly confused", ex);
    }
    return "";
}

From source file:com.jaeksoft.searchlib.util.StringUtils.java

/**
 * /*from   w w  w.j  a  v  a 2s. c o m*/
 * @param text
 *            the text to encode
 * @return a base64 encoded string
 * @throws UnsupportedEncodingException
 */
public final static String base64encode(String text) throws UnsupportedEncodingException {
    if (isEmpty(text))
        return null;
    return Base64.encodeBase64URLSafeString(text.getBytes("UTF-8"));
}

From source file:com.zotoh.maedr.etc.CmdApps.java

/**
 * @param appdir/* www  .  j  a  v  a 2s .  c  o  m*/
 * @param appprops
 * @param props
 * @throws Exception
 */
protected void create2(File appdir, String appprops, Properties props) throws Exception {
    boolean wdb = (Boolean) props.get("storage");
    File realm = new File(appdir, REALM);
    File cfg = new File(appdir, CFG);
    //        File w= new File(appdir, TMP);
    File db = new File(appdir, DB);
    //        File mf= (File)props.get("mf");
    String pcfg = niceFPath(cfg);
    String dfcz = Module.getPipelineModule().getDefDelegateClass();
    String s = rc2Str("com/zotoh/maedr/env/" + APPPROPS, "utf-8");
    if (!isEmpty(appprops)) {
        s = appprops;
    }
    String pwd = PwdFactory.getInstance().createRandomText(24);
    writeFile(new File(realm, KEYFILE), "B64:" + Base64.encodeBase64URLSafeString(asBytes(pwd)), "utf-8");

    String dg = fullClassNS(props, "delegate", dfcz);
    s = strstr(s, "${DELEGATE_CLASS}", dg);
    s = strstr(s, "${MANIFEST_FILE}", ""); //niceFPath(mf));
    s = strstr(s, "${WORK_DIR}", ""); //niceFPath(w));
    s = strstr(s, "${DB_URL}", niceFPath(db));
    s = strstr(s, "${DB_FLAG}", (wdb ? "" : "#"));
    s = strstr(s, "${WANT_DB}", (wdb ? "true" : "false"));

    File out = new File(pcfg + "/" + APPPROPS);
    writeFile(out, s, "utf-8");

    s = rc2Str("com/zotoh/maedr/env/" + CLOUDDATA, "utf-8");
    out = new File(pcfg + "/" + CLOUDDATA);
    writeFile(out, s, "utf-8");

    // copy test server p12 file
    byte[] bits = rc2bytes("com/zotoh/maedr/env/test.p12", getCZldr());
    out = new File(pcfg + "/test.p12");
    writeFile(out, bits);
}

From source file:com.cloudera.impala.security.PersistedDelegationTokenSecretManager.java

public static String encodeWritable(Writable key) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    key.write(dos);/*from   www.  j a v a 2  s .  co  m*/
    dos.flush();
    return Base64.encodeBase64URLSafeString(bos.toByteArray());
}

From source file:com.here.account.auth.OAuth1SignerTest.java

@Test
public void test_OAuth1Signer_uses_HMAC_SHA256()
        throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
    this.clockCurrentTimeMillis = System.currentTimeMillis();

    byte[] nonceBytes = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
    String nonce = Base64.encodeBase64URLSafeString(nonceBytes).substring(0, nonceBytes.length);

    long oauth_timestamp = clockCurrentTimeMillis / 1000L; // oauth1 uses seconds

    String shaVariant = "SHA256";//"SHA1";

    String requestParameters = "oauth_consumer_key=" + clientId + "&oauth_nonce=" + nonce
            + "&oauth_signature_method=HMAC-" + shaVariant + "&oauth_timestamp=" + oauth_timestamp
            + "&oauth_version=1.0";
    String signatureBaseString = "GET&" + urlEncode(url) + "&" + urlEncode(requestParameters); // no request parameters in this test case

    System.out.println("test       signatureBaseString " + signatureBaseString);

    String key = urlEncode(clientSecret) + "&"; // no token shared-secret

    String expectedSignature = HmacSHAN(key, "Hmac" + shaVariant, signatureBaseString);

    String expectedSignatureInAuthorizationHeader = urlEncode(expectedSignature);

    oauth1Signer.authorize(httpRequest, method, url, null);
    String actualHeader = httpRequest.getAuthorizationHeader();

    Pattern pattern = Pattern.compile("\\A.*oauth_signature=\\\"([^\\\"]+).*\\z");
    Matcher matcher = pattern.matcher(actualHeader);
    assertTrue("pattern wasn't matched: " + actualHeader, matcher.matches());
    String actualSignature = matcher.group(1);

    assertTrue("expected signature " + expectedSignatureInAuthorizationHeader + ", actual signature "
            + actualSignature, expectedSignatureInAuthorizationHeader.equals(actualSignature));
}

From source file:eu.openanalytics.rsb.component.DataDirectoriesResource.java

@Path("/{rootId}{b64extension : (/b64extension)?}")
@GET//from  w ww. j  a v  a 2 s .c om
public Directory browsePath(@PathParam("rootId") final String rootId,
        @PathParam("b64extension") final String b64extension, @Context final HttpHeaders httpHeaders,
        @Context final UriInfo uriInfo) throws URISyntaxException, IOException {

    final File rootDataDir = rootMap.get(rootId);
    if (rootDataDir == null) {
        throw new NotFoundException(new RuntimeException("No root data dir configured"));
    }

    final String extension = (b64extension != null ? new String(Base64.decodeBase64(b64extension)) : "");
    final File targetDataDir = new File(rootDataDir, extension);

    if (!targetDataDir.exists()) {
        throw new NotFoundException(new RuntimeException("Invalid root data dir: " + targetDataDir));
    }

    // ensure the target data dir is below the root dir to prevent tampering
    final String rootDataDirCanonicalPath = rootDataDir.getCanonicalPath();
    final String targetDataDirCanonicalPath = targetDataDir.getCanonicalPath();
    if (!StringUtils.startsWith(targetDataDirCanonicalPath, rootDataDirCanonicalPath)) {
        throw new AccessDeniedException("Target data dir: " + targetDataDirCanonicalPath
                + " is not below root dir: " + rootDataDirCanonicalPath);
    }

    final Directory result = Util.REST_OBJECT_FACTORY.createDirectory();
    result.setPath(rootDataDirCanonicalPath + extension);
    result.setName(targetDataDir.getName());
    result.setUri(Util.buildDataDirectoryUri(httpHeaders, uriInfo, rootId, b64extension).toString());

    final File[] targetDataDirFiles = targetDataDir.listFiles();
    result.setEmpty(targetDataDirFiles.length == 0);

    for (final File child : targetDataDirFiles) {
        if (FileUtils.isSymlink(child)) {
            getLogger().warn("Symlinks are not supported: " + child);
        } else if (child.isFile()) {
            final FileType fileType = Util.REST_OBJECT_FACTORY.createFileType();
            fileType.setPath(child.getCanonicalPath());
            fileType.setName(child.getName());
            result.getFiles().add(fileType);
        } else if (child.isDirectory()) {
            final Directory childDir = Util.REST_OBJECT_FACTORY.createDirectory();
            childDir.setPath(child.getCanonicalPath());
            childDir.setName(child.getName());
            final String childB64extension = Base64.encodeBase64URLSafeString(
                    StringUtils.difference(rootDataDirCanonicalPath, child.getCanonicalPath()).getBytes());
            childDir.setUri(
                    Util.buildDataDirectoryUri(httpHeaders, uriInfo, rootId, childB64extension).toString());
            childDir.setEmpty(isDirectoryEmpty(child));
            result.getDirectories().add(childDir);
        } else {
            getLogger().warn("Unsupported file type: " + child);
        }
    }

    return result;
}

From source file:flpitu88.web.backend.psicoweb.config.Jwt.java

/**
 * Private method to encode a String in base64
 *
 * @param bytes Bytes to encode/*www .ja v a 2 s. com*/
 *
 * @return String
 *
 * @throws UnsupportedEncodingException
 */
private static String base64Encode(byte[] bytes) throws UnsupportedEncodingException {
    return Base64.encodeBase64URLSafeString(bytes);
}

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

@Test
public void testContentConsumptionWithInvalidMessage() {
    mockery.checking(new Expectations() {

        {/*from  ww w  .  j a  v  a  2 s . c  om*/
        }
    });
    EventConsumer consumer = injector.getInstance(EventConsumer.class);
    consumer.consume(MSG_TYPE, "CONTENT\nCREATE\n"
            + Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8("random string\nfor test")));
    mockery.assertIsSatisfied();
}