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.snowplowanalytics.snowplow.collectors.clojure.SnowplowAccessLogValve.java

/**
 * Base64-URL-safe encodes a string or returns a
 * "-" if not possible.// w  w w . ja  v  a  2  s  . c o m
 *
 * @param b The byte array to encode
 * @return The encoded string, or "-" if not possible
 */
protected static String base64EncodeSafely(byte[] b) {
    try {
        return Base64.encodeBase64URLSafeString(b);
    } catch (Exception e) {
        return "-";
    }
}

From source file:com.indeed.imhotep.web.QueryServlet.java

/**
 * Produces a Base64 encoded SHA-1 hash of the query and the list of shard names/versions which has to be sorted.
 *//*w w w  .ja v  a  2 s.  c  om*/
private String getQueryHash(String query, Collection<ShardIdWithVersion> shards, boolean csv) {
    final MessageDigest sha1;
    try {
        sha1 = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        log.error("Failed to init SHA1", e);
        throw Throwables.propagate(e);
    }
    final String standardizedQuery = query.trim().replace('"', '\'').replaceAll("\\s+", " ");
    sha1.update(standardizedQuery.getBytes(UTF8_CHARSET));
    if (shards != null) {
        for (ShardIdWithVersion shard : shards) {
            sha1.update(shard.getShardId().getBytes(UTF8_CHARSET));
            sha1.update(Longs.toByteArray(shard.getVersion()));
            sha1.update(csv ? (byte) 1 : 0);
        }
    }
    sha1.update(VERSION_FOR_HASHING);
    return Base64.encodeBase64URLSafeString(sha1.digest());
}

From source file:com.cloud.server.ConfigurationServerImpl.java

private void updateSSOKey() {
    try {/*from w  w  w.j a  v  a 2 s .  c  o m*/
        String encodedKey = null;

        // Algorithm for SSO Keys is SHA1, should this be configurable?
        KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
        SecretKey key = generator.generateKey();
        encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());

        _configDao.update(Config.SSOKey.key(), Config.SSOKey.getCategory(), encodedKey);
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating sso key", ex);
    }
}

From source file:com.squid.kraken.v4.api.core.analytics.AnalyticsServiceBaseImpl.java

/**
 * /* www  .  j  a v a2  s  .co  m*/
 * @param userContext
 * @param query
 * @param parent
 * @param filters
 * @param hierarchyMode
 * @param fullPath
 * @param content
 * @throws ScopeException
 */
private void listBoomarks(AppContext userContext, NavigationQuery query, String parent, String[] filters,
        HierarchyMode hierarchyMode, String fullPath, List<NavigationItem> content) throws ScopeException {
    // list the content first
    List<Bookmark> bookmarks = BookmarkManager.INSTANCE.findBookmarksByParent(userContext, fullPath);
    HashSet<String> folders = new HashSet<>();
    for (Bookmark bookmark : bookmarks) {
        Project project = ProjectManager.INSTANCE.getProject(userContext, bookmark.getId().getParent());
        String path = bookmark.getPath();
        // only handle the exact path
        boolean checkParent = (hierarchyMode == HierarchyMode.FLAT) ? path.startsWith(fullPath)
                : path.equals(fullPath);
        if (checkParent) {
            if (filters == null || filter(bookmark, project, filters)) {
                String actualParent = parent;
                if (hierarchyMode == HierarchyMode.FLAT) {
                    actualParent = (parent + path.substring(fullPath.length()));
                }
                NavigationItem item = new NavigationItem(query, project, bookmark, actualParent);
                if (query.getStyle() == Style.HUMAN || query.getStyle() == Style.HTML) {
                    item.setLink(createLinkToAnalysis(userContext, query, item));
                    item.setViewLink(createLinkToView(userContext, query, item));
                    item.setObjectLink(createObjectLink(userContext, query, bookmark));
                }
                HashMap<String, String> attrs = new HashMap<>();
                attrs.put("project", project.getName());
                item.setAttributes(attrs);
                content.add(item);
            }
        } else {
            // it's a sub folder
            path = bookmark.getPath().substring(fullPath.length() + 1);// remove first /
            String[] split = path.split("/");
            if (split.length > 0) {
                String name = "/" + (hierarchyMode != null ? path : split[0]);
                String selfpath = parent + name;
                if (!folders.contains(selfpath)) {
                    if (filters == null || filter(name, filters)) {
                        String oid = Base64.encodeBase64URLSafeString(selfpath.getBytes());
                        // legacy folder PK support
                        BookmarkFolderPK id = new BookmarkFolderPK(bookmark.getId().getCustomerId(), oid);
                        NavigationItem folder = new NavigationItem(query.getStyle() == Style.LEGACY ? id : null,
                                name, "", parent, selfpath, NavigationItem.FOLDER_TYPE);
                        if (query.getStyle() == Style.HUMAN || query.getStyle() == Style.HTML) {
                            folder.setLink(createLinkToFolder(userContext, query, folder));
                        }
                        content.add(folder);
                        folders.add(selfpath);
                    }
                }
            }
        }
    }
}

From source file:com.microsoft.aad.adal4j.AuthenticationContext.java

private String computeSha256Hash(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(input.getBytes("UTF-8"));
    byte[] hash = digest.digest();
    return Base64.encodeBase64URLSafeString(hash);
}

From source file:com.cloud.migration.Db20to21MigrationUtil.java

private void updateSSOKey() {
    try {//from   ww  w. jav a  2 s. com
        String encodedKey = null;

        // Algorithm for SSO Keys is SHA1, should this be configuable?
        KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
        SecretKey key = generator.generateKey();
        encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());

        _configDao.update("security.singlesignon.key", encodedKey);
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating sso key", ex);
    }
}

From source file:TestDataLoader.java

/**
 * Generate a random security hash. The hash must be unique and not
 * currently being used by a submission.
 * /*  w ww .j a v a2  s  .co  m*/
 * @return The new hash.
 */
public static String generateCommitteEmailHash() {

    String hash = null;

    do {
        byte[] randomBytes = new byte[8];
        new Random().nextBytes(randomBytes);
        String proposed = Base64.encodeBase64URLSafeString(randomBytes);
        proposed = proposed.replaceAll("[^A-Za-z0-9]", "");

        // Check if the hash already exists
        if (subRepo.findSubmissionByEmailHash(proposed) == null) {
            // We're done, otherwise keep looping.
            hash = proposed;
        }
    } while (hash == null);

    return hash;
}

From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java

private String getSha256(String mesosHostingDir) throws UnsupportedEncodingException {
    MessageDigest md;/*from   www  .  j  a v  a  2  s.c  o  m*/
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
    md.update(mesosHostingDir.getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(md.digest());
}

From source file:com.cloud.user.AccountManagerImpl.java

private String createUserApiKey(long userId) {
    try {/*from www  .  j a va2 s .c  o m*/
        UserVO updatedUser = _userDao.createForUpdate();

        String encodedKey = null;
        Pair<User, Account> userAcct = null;
        int retryLimit = 10;
        do {
            // FIXME: what algorithm should we use for API keys?
            KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
            SecretKey key = generator.generateKey();
            encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
            userAcct = _accountDao.findUserAccountByApiKey(encodedKey);
            retryLimit--;
        } while ((userAcct != null) && (retryLimit >= 0));

        if (userAcct != null) {
            return null;
        }
        updatedUser.setApiKey(encodedKey);
        _userDao.update(userId, updatedUser);
        return encodedKey;
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating secret key for user id=" + userId, ex);
    }
    return null;
}

From source file:com.cloud.user.AccountManagerImpl.java

private String createUserSecretKey(long userId) {
    try {/*from ww  w. j a  va  2  s.co m*/
        UserVO updatedUser = _userDao.createForUpdate();
        String encodedKey = null;
        int retryLimit = 10;
        UserVO userBySecretKey = null;
        do {
            KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
            SecretKey key = generator.generateKey();
            encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
            userBySecretKey = _userDao.findUserBySecretKey(encodedKey);
            retryLimit--;
        } while ((userBySecretKey != null) && (retryLimit >= 0));

        if (userBySecretKey != null) {
            return null;
        }

        updatedUser.setSecretKey(encodedKey);
        _userDao.update(userId, updatedUser);
        return encodedKey;
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating secret key for user id=" + userId, ex);
    }
    return null;
}