Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

In this page you can find the example usage for java.util Base64 getEncoder.

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:org.onehippo.forge.content.pojo.model.BinaryValue.java

/**
 * Returns a URI representation of the underlying data.
 * Either a <code>data:</code> URL or an external URL based on an internal {@link FileObject}.
 * @return a <code>data:</code> URL or an external URL based on an internal {@link FileObject}
 * @throws IOException if any IO exception occurs
 *//*w  w  w  .  java2 s .c o  m*/
public String toUriString() throws IOException {
    if (data != null) {
        StringBuilder sb = new StringBuilder(data.length + 20);
        sb.append("data:");

        if (StringUtils.isNotBlank(mediaType)) {
            sb.append(mediaType);
        }

        if (StringUtils.isNotBlank(charset)) {
            sb.append(';').append(charset);
        }

        sb.append(";base64,");

        sb.append(Base64.getEncoder().encodeToString(data));

        return sb.toString();
    } else if (fileObject != null) {
        return fileObject.getURL().toString();
    }

    throw new IOException("No data nor fileObject set.");
}

From source file:com.github.horrorho.inflatabledonkey.KeyBagManager.java

Set<String> keyBagUUIDs(Collection<Asset> assets) {
    return assets.stream().map(Asset::encryptionKey).map(key -> key.flatMap(FileKeyAssistant::uuid))
            .filter(Optional::isPresent).map(Optional::get)
            .map(uuid -> Base64.getEncoder().encodeToString(uuid)).collect(Collectors.toSet());
}

From source file:org.codice.ddf.security.common.jaxrs.RestSecurity.java

/**
 * Deflates a value and Base64 encodes the result.
 *
 * @param value value to deflate and Base64 encode
 * @return String//from  w  w  w.  ja va  2 s .  com
 * @throws IOException if the value cannot be converted
 */
public static String deflateAndBase64Encode(String value) throws IOException {
    ByteArrayOutputStream valueBytes = new ByteArrayOutputStream();
    try (OutputStream tokenStream = new DeflaterOutputStream(valueBytes,
            new Deflater(Deflater.DEFLATED, GZIP_COMPATIBLE))) {
        tokenStream.write(value.getBytes(StandardCharsets.UTF_8));
        tokenStream.close();

        return Base64.getEncoder().encodeToString(valueBytes.toByteArray());
    }
}

From source file:org.wso2.carbon.apimgt.impl.reportgen.ReportGenerator.java

private String getMetaCount(String origCount) {
    String count = origCount;/*from  w  ww  .jav  a 2  s  .  c  om*/
    Cipher cipher;

    try {
        cipher = Cipher.getInstance(MGW_ALGO);
        SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(MGW_KEY), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] bytes = cipher.doFinal(origCount.getBytes());
        count = new String(Base64.getEncoder().encode(bytes));
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | BadPaddingException
            | IllegalBlockSizeException e) {
        log.info("Couldn't generate the value for Summary report meta field.", e);
    }

    return count;
}

From source file:org.apache.lens.client.SpnegoClientFilter.java

private String getAuthorization(URI currentURI) {
    try {/* w ww . ja v a2 s  .com*/
        String spn = getCompleteServicePrincipalName(currentURI);

        Oid oid = new Oid(SPNEGO_OID);

        byte[] token = getToken(spn, oid);
        String encodedToken = new String(Base64.getEncoder().encode(token), StandardCharsets.UTF_8);
        return NEGOTIATE_SCHEME + " " + encodedToken;
    } catch (LoginException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (GSSException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.bekwam.resignator.util.CryptUtils.java

public String encrypt(String encrypted, String passPhrase)
        throws IOException, PGPException, NoSuchProviderException {

    if (StringUtils.isBlank(encrypted)) {
        throw new IllegalArgumentException("encrypted text is blank");
    }/*from   ww w . j  a v a  2  s. c  o m*/

    if (StringUtils.isBlank(passPhrase)) {
        throw new IllegalArgumentException("passPhrase is required");
    }

    byte[] ciphertext = encrypt(encrypted.getBytes(StandardCharsets.ISO_8859_1), passPhrase.toCharArray());
    String ciphertext64 = Base64.getEncoder().encodeToString(ciphertext); // uses ISO_8859_1
    return ciphertext64;
}

From source file:com.amalto.workbench.utils.ResourcesUtil.java

private static String readFileAsString(String fileName) throws Exception {
    FileInputStream fis = new FileInputStream(fileName);
    BufferedInputStream in = new BufferedInputStream(fis);
    byte buffer[] = new byte[256];
    StringBuffer picStr = new StringBuffer();
    Encoder encoder = Base64.getEncoder();
    while (in.read(buffer) >= 0) {
        picStr.append(encoder.encodeToString(buffer));
    }// w w  w.j ava2s  .c  o m
    fis.close();
    fis = null;
    in.close();
    in = null;
    buffer = null;
    return picStr.toString();
}

From source file:org.eclipse.packagedrone.testing.server.channel.UploadApiV3Test.java

protected CloseableHttpResponse upload(final URIBuilder uri, final File file)
        throws IOException, URISyntaxException {
    final HttpPut http = new HttpPut(uri.build());

    final String encodedAuth = Base64.getEncoder()
            .encodeToString(uri.getUserInfo().getBytes(StandardCharsets.ISO_8859_1));

    http.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);

    http.setEntity(new FileEntity(file));
    return httpclient.execute(http);
}

From source file:org.hawkular.openshift.auth.BasicAuthenticator.java

private boolean verifySHA1Password(String storedPassword, String passedPassword) {
    //Remove the SHA_PREFIX from the password string
    storedPassword = storedPassword.substring(SHA_PREFIX.length());

    //Get the SHA digest and encode it in Base64
    byte[] digestedPasswordBytes = DigestUtils.sha1(passedPassword);
    String digestedPassword = Base64.getEncoder().encodeToString(digestedPasswordBytes);

    //Check if the stored password matches the passed one
    return digestedPassword.equals(storedPassword);
}

From source file:org.fcrepo.apix.registry.HttpClientFactory.java

/**
 * Construct a new HttpClient./*from w  ww .j  a v  a2 s.  c  o m*/
 *
 * @return HttpClient impl.
 */
public CloseableHttpClient getClient() {
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    final CredentialsProvider provider = new BasicCredentialsProvider();

    for (final AuthSpec authSpec : getAuthSpecs()) {
        LOG.debug("Using basic auth to {}://{}:{} with client", authSpec.scheme, authSpec.host, authSpec.port);
        final HttpHost host = new HttpHost(authSpec.host, authSpec.port, authSpec.scheme);

        provider.setCredentials(new AuthScope(host, AuthScope.ANY_REALM, authSpec.scheme),
                new UsernamePasswordCredentials(authSpec.username(), authSpec.passwd()));
    }

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest req, final HttpContext cxt)
                        throws HttpException, IOException {
                    if (!req.containsHeader(HttpHeaders.AUTHORIZATION)) {
                        final String[] hostInfo = req.getFirstHeader(HttpHeaders.HOST).getValue().split(":");
                        final Credentials creds = provider.getCredentials(new AuthScope(
                                new HttpHost(hostInfo[0],
                                        hostInfo.length > 1 ? Integer.valueOf(hostInfo[1]) : 80),
                                AuthScope.ANY_REALM, "http"));

                        if (creds != null) {
                            req.addHeader(HttpHeaders.AUTHORIZATION,
                                    "Basic " + Base64.getEncoder().encodeToString(
                                            String.format("%s:%s", creds.getUserPrincipal().getName(),
                                                    creds.getPassword()).getBytes()));
                            LOG.debug("Added auth header");
                        }
                    }
                }
            }).setDefaultCredentialsProvider(provider).build();
}