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.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *//*from  www.j  a  v a  2 s.  c o m*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

From source file:org.silverpeas.core.web.http.FileResponse.java

/**
 * Gets the file identifier//w ww. j a v a  2s .c o  m
 * @param path the path to the physical content.
 * @return the file identifier.
 * @throws IOException if the file is not readable.
 */
String getFileIdentifier(final Path path) throws IOException {
    if (isDefined(forcedFileId)) {
        return forcedFileId;
    }
    final File file = path.toFile();
    final String sb = String.valueOf(FileUtils.checksumCRC32(file)) + "|" + file.getName() + "|" + file.length()
            + "|" + file.lastModified();
    return Base64.getEncoder().encodeToString(sb.getBytes());
}

From source file:sh.isaac.api.util.DownloadUnzipTask.java

/**
 * Download.//from  w w  w .j  av a  2s .  c  om
 *
 * @param url the url
 * @return the file
 * @throws Exception the exception
 */
private File download(URL url) throws Exception {
    LOG.debug("Beginning download from " + url);
    updateMessage("Download from " + url);

    final HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    if (StringUtils.isNotBlank(this.username) || StringUtils.isNotBlank(this.psswrd)) {
        final String encoded = Base64.getEncoder()
                .encodeToString((this.username + ":" + this.psswrd).getBytes());

        httpCon.setRequestProperty("Authorization", "Basic " + encoded);
    }

    httpCon.setDoInput(true);
    httpCon.setRequestMethod("GET");
    httpCon.setConnectTimeout(30 * 1000);
    httpCon.setReadTimeout(60 * 60 * 1000);

    final long fileLength = httpCon.getContentLengthLong();
    String temp = url.toString();

    temp = temp.substring(temp.lastIndexOf('/') + 1, temp.length());

    final File file = new File(this.targetFolder, temp);

    try (InputStream in = httpCon.getInputStream(); FileOutputStream fos = new FileOutputStream(file);) {
        final byte[] buf = new byte[1048576];
        int read = 0;
        long totalRead = 0;

        while (!this.cancel && (read = in.read(buf, 0, buf.length)) > 0) {
            totalRead += read;

            // update every 1 MB
            updateProgress(totalRead, fileLength);

            final float percentDone = ((int) (((float) totalRead / (float) fileLength) * 1000)) / 10f;

            updateMessage(
                    "Downloading - " + url + " - " + percentDone + " % - out of " + fileLength + " bytes");
            fos.write(buf, 0, read);
        }
    }

    if (this.cancel) {
        LOG.debug("Download cancelled");
        throw new Exception("Cancelled!");
    } else {
        LOG.debug("Download complete");
    }

    return file;
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//w w  w  .  j  ava2  s  .c  om
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * See https://stackoverflow.com/questions/3313020/write-x509-certificate-into-pem-formatted-string-in-java
 *
 * @param key  An RSA private key/* w ww . j  a  v  a 2  s  .  c o m*/
 * @param file a file to which the private key will be written in PEM format
 * @throws FileNotFoundException
 */
private static void writePrivateKeyToPem(final PrivateKey key, File file) throws IOException {
    final Base64.Encoder encoder = Base64.getEncoder();

    final String keyHeader = "-----BEGIN PRIVATE KEY-----\n";
    final String keyFooter = "\n-----END PRIVATE KEY-----";
    final byte[] keyBytes = key.getEncoded();
    final String keyContents = new String(encoder.encode(keyBytes));
    final String keyPem = keyHeader + keyContents + keyFooter;
    FileUtils.write(file, keyPem);
}

From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

@Override
String encrypt(String command) {
    if (!encryptionReady) {
        return command;
    }//  w  w  w . j  a  va 2 s .c  o  m
    String str;
    if (salt != null && newSaltNeeded()) {
        String prevSalt = salt;
        salt = generateSalt();
        str = "nextSalt/" + prevSalt + "/" + salt + "/" + command + "\0";
    } else {
        if (salt == null) {
            salt = generateSalt();
        }
        str = "salt/" + salt + "/" + command + "\0";
    }

    logger.debug("[{}] Command for encryption: {}", debugId, str);
    try {
        String encrypted = Base64.getEncoder().encodeToString(aesEncryptCipher.doFinal(str.getBytes("UTF-8")));
        try {
            encrypted = URLEncoder.encode(encrypted, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn("[{}] Unsupported encoding for encrypted command conversion to URL.", debugId);
        }
        return CMD_ENCRYPT_CMD + encrypted;
    } catch (IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
        logger.warn("[{}] Command encryption failed: {}", debugId, e.getMessage());
        return command;
    }
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get a base64-encoded image for inclusion in an img tag with a chart with number of produced and consumed messages
 * per second.//from  ww  w. j av a2s.com
 *
 * @return chart as base64 string.
 */
public String getBase64MessagesPerSecondImage() {
    TimeSeries timeSeriesConsumed = new TimeSeries("Consumed");
    TimeSeries timeSeriesProduced = new TimeSeries("Produced");
    TimeSeries timeSeriesTotal = new TimeSeries("Total");
    for (PeriodMetrics m : getMessagesPerSecond()) {
        Second second = new Second(m.getPeriodStart());
        timeSeriesConsumed.add(second, m.getConsumed());
        timeSeriesProduced.add(second, m.getProduced());
        timeSeriesTotal.add(second, m.getConsumed() + m.getProduced());
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeriesConsumed);
    timeSeriesCollection.addSeries(timeSeriesProduced);
    timeSeriesCollection.addSeries(timeSeriesTotal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Messages per second (TPS)", "Time", "Messages",
                timeSeriesCollection);
        chart.getPlot().setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(bos, chart, 1024, 500);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}

From source file:com.epl.ticketws.services.QueryService.java

/**
 * Signs a string with the given key./*from  www. jav a2 s. c om*/
 *
 * @param data
 * @param key
 * @return
 * @throws SignatureException
 */
private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException {
    String result;

    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes(UTF_8));
        //byte[] base64 = Base64.encodeBase64(rawHmac);
        byte[] base64 = Base64.getEncoder().encode(rawHmac);

        // base64-encode the hmac
        result = new String(base64);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    return AUTHORIZATION_HEADER_HMAC_PREFIX + result;
}

From source file:org.carlspring.strongbox.artifact.generator.NugetPackageGenerator.java

private String toBase64(byte[] digest) {
    byte[] encoded = Base64.getEncoder().encode(digest);

    return new String(encoded, StandardCharsets.UTF_8);
}