Example usage for org.apache.commons.codec.binary Base64 encodeBase64

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64.

Prototype

public static byte[] encodeBase64(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:com.xwiki.authentication.AbstractAuthServiceImpl.java

protected String encryptText(String text, XWikiContext context) {
    try {/*from   w  w w.  java  2  s.  c o m*/
        String secretKey = null;
        secretKey = context.getWiki().Param("xwiki.authentication.encryptionKey");
        secretKey = secretKey.substring(0, 24);

        if (secretKey != null) {
            SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "TripleDES");
            Cipher cipher = Cipher.getInstance("TripleDES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encrypted = cipher.doFinal(text.getBytes());
            String encoded = new String(Base64.encodeBase64(encrypted));
            return encoded.replaceAll("=", "_");
        } else {
            LOG.error("Encryption key not defined");
        }
    } catch (Exception e) {
        LOG.error("Failed to encrypt text", e);
    }

    return null;
}

From source file:net.alegen.datpass.library.Generator.java

public String password(String input, int length) throws GeneratorException {
    if (this.currentProfile == null) {
        log.error("Cannot generate a password without having loaded a profile first.");
        throw new GeneratorException();
    }//from w w w  .  j a v a  2  s  .co  m
    try {
        // calculate bit length
        int bitLength = (int) (length * 4.0 / 3 * 8); // take into account length for base64 encoding
        if (bitLength % 8 != 0)
            bitLength = (bitLength / 8) * 8; // ensure multiple of 8

        // generate password
        SecretKey secretKey = CryptoManager.getInstance().derivateKey(
                KeyDerivationFunctions.fromString(this.currentProfile.getValue(FieldManager.FUNCTION_FIELD)),
                input, this.currentProfile.getValue(FieldManager.SALT_FIELD).getBytes("UTF-8"), bitLength,
                Integer.parseInt(this.currentProfile.getValue(FieldManager.ITER_FIELD)));
        byte[] encodedPassword = Base64.encodeBase64(secretKey.getEncoded());
        String retval = new String(encodedPassword, "UTF-8");

        // trim to desired length
        if (retval.length() != length)
            retval = retval.substring(0, length);

        // substitute characters to have just a-z, A-z, 0-9
        retval = retval.replace('/', retval.charAt(retval.length() / 2));
        retval = retval.replace('+', retval.charAt(retval.length() / 3));
        retval = retval.replace('=', retval.charAt(retval.length() / 5));
        return retval;
    } catch (UnsupportedEncodingException e) {
        log.error("UTF-8 encoding seems to not be supported?!");
        e.printStackTrace();
        throw new RuntimeException("An internall error occured and the operation failed.");
    }
}

From source file:monasca.api.infrastructure.persistence.influxdb.InfluxV9RepoReader.java

@Inject
public InfluxV9RepoReader(final ApiConfig config) {

    this.influxName = config.influxDB.getName();
    logger.debug("Influxdb database name: {}", this.influxName);

    this.influxUrl = config.influxDB.getUrl() + "/query";
    logger.debug("Influxdb URL: {}", this.influxUrl);

    this.influxUser = config.influxDB.getUser();
    this.influxPass = config.influxDB.getPassword();
    this.influxCreds = this.influxUser + ":" + this.influxPass;

    this.gzip = config.influxDB.getGzip();
    logger.debug("Influxdb gzip responses: {}", this.gzip);

    logger.debug("Setting up basic Base64 authentication");
    this.baseAuthHeader = "Basic " + new String(Base64.encodeBase64(this.influxCreds.getBytes()));

    // We inject InfluxV9RepoReader as a singleton. So, we must share connections safely.
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(config.influxDB.getMaxHttpConnections());

    if (this.gzip) {

        logger.debug("Setting up gzip responses from Influxdb");

        this.httpClient = HttpClients.custom().setConnectionManager(cm)
                .addInterceptorFirst(new HttpRequestInterceptor() {

                    public void process(final HttpRequest request, final HttpContext context)
                            throws HttpException, IOException {
                        if (!request.containsHeader("Accept-Encoding")) {
                            request.addHeader("Accept-Encoding", "gzip");
                        }/* w  w w.j a  v a  2 s .c  om*/
                    }
                }).addInterceptorFirst(new HttpResponseInterceptor() {

                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            Header ceheader = entity.getContentEncoding();
                            if (ceheader != null) {
                                HeaderElement[] codecs = ceheader.getElements();
                                for (int i = 0; i < codecs.length; i++) {
                                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }).build();

    } else {

        logger.debug("Setting up non-gzip responses from Influxdb");

        this.httpClient = HttpClients.custom().setConnectionManager(cm).build();

    }
}

From source file:com.altcanvas.asocial.Twitter.java

public Twitter setBasicAuth(String username, String password) {
    headers.put("Authorization",
            "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes())));
    return this;
}

From source file:com.aurel.track.report.query.ReportQueryBL.java

private static String encrypt(String clearText, char[] password) {
    // Create PBE parameter set
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
    byte[] ciphertext = { 0 };

    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    try {//from w w w .j  a v  a 2 s.c  o  m
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Encrypt the cleartext
        ciphertext = pbeCipher.doFinal(clearText.getBytes());
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return new String(Base64.encodeBase64(ciphertext));
}

From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java

/**
 * ??/*  w ww  . j  a va2 s. c  om*/
 * 
 * @param pubFile public file
 * @param priFile private file
 * @throws IOException IOException
 */
@SuppressWarnings("PMD.PrematureDeclaration")
protected void generater(File pubFile, File priFile) throws IOException {
    try {
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);
        SecureRandom secrand = new SecureRandom();
        keygen.initialize(KEY_SIZE, secrand);
        KeyPair keys = keygen.genKeyPair();
        PublicKey pubkey = keys.getPublic();
        PrivateKey prikey = keys.getPrivate();
        byte[] priKey = Base64.encodeBase64(prikey.getEncoded());
        byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded());
        if (pubFile.exists()) {
            throw new IOException(pubFile.getPath() + " is exist!");
        }
        if (priFile.exists()) {
            throw new IOException(priFile.getPath() + " is exist!");
        }
        OutputStream pubOutput = new FileOutputStream(pubFile);
        try {
            IOUtils.write(pubKey, pubOutput);
        } finally {
            IOUtils.closeQuietly(pubOutput);
        }
        OutputStream priOutput = new FileOutputStream(priFile);
        try {
            IOUtils.write(priKey, priOutput);
        } finally {
            IOUtils.closeQuietly(priOutput);
        }
    } catch (NoSuchAlgorithmException e) {
        log.error("?", e);
    }
}

From source file:com.mastfrog.acteur.util.BasicCredentials.java

public String toString() {
    String merged = username + ':' + password;
    //        return "Basic " + Base64.getEncoder().encodeToString(merged.getBytes(UTF_8));
    byte[] b = merged.getBytes(UTF_8);
    b = Base64.encodeBase64(b);
    return "Basic " + new String(b, US_ASCII);
}

From source file:com.syncthemall.enml4j.util.Utils.java

/**
 * Encode an {@code byte[]} representing a file in base64.
 * //w  w  w  .j  ava 2  s .c  om
 * @param bytes the source to encode
 * @return a {@code String} representation of the {@code InputStream} in parameter, encoded in base64
 */
public static String encodeFileToBase64Binary(final byte[] bytes) {
    byte[] encoded = Base64.encodeBase64(bytes);
    return new String(encoded, Charset.forName(CHARSET));
}

From source file:com.klarna.checkout.Digest.java

/**
 * Create a digest from an input stream.
 *
 * @param stream character stream to hash
 *
 * @return Base64 and SHA256 hashed string
 *
 * @throws UnsupportedEncodingException if UTF-8 is unsupported
 *///  w  w  w  .  j a v a 2s .c o m
public String create(final InputStream stream) throws UnsupportedEncodingException {
    md.reset();

    if (stream != null) {

        byte[] b = new byte[1024];
        int read;

        try {
            while ((read = stream.read(b)) >= 0) {
                md.update(b, 0, read);
            }
        } catch (IOException ex) {
            Logger.getLogger(Digest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    md.update(secret.getBytes("UTF-8"));

    return new String(Base64.encodeBase64(md.digest()));
}

From source file:info.debatty.sparkpackages.maven.plugin.PublishMojo.java

@Override
public final void realexe() throws MojoFailureException {

    File zip_file = new File(getZipPath());
    byte[] zip_base64 = null;
    try {/*from   www.  j  av a2s.c o  m*/
        zip_base64 = Base64.encodeBase64(FileUtils.readFileToByteArray(zip_file));

    } catch (IOException ex) {
        throw new MojoFailureException("Error!", ex);
    }

    HttpEntity request = MultipartEntityBuilder.create()
            .addBinaryBody("artifact_zip", zip_base64, ContentType.APPLICATION_OCTET_STREAM, "artifact_zip")
            .addTextBody("version", getVersion()).addTextBody("license_id", getLicenseId())
            .addTextBody("git_commit_sha1", getGitCommit())
            .addTextBody("name", getOrganization() + "/" + getRepo()).build();

    HttpPost post = new HttpPost(getSparkpackagesUrl());
    post.setEntity(request);

    post.setHeader("Authorization", getAuthorizationHeader());

    getLog().info("Executing request " + post.getRequestLine());

    // .setProxy(new HttpHost("127.0.0.1", 8888))
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to perform HTTP request", ex);
    }
    getLog().info("Server responded " + response.getStatusLine());

    HttpEntity response_content = response.getEntity();
    if (response_content == null) {
        throw new MojoFailureException("Server responded with an empty response");
    }

    StringBuilder sb = new StringBuilder();
    String line;
    BufferedReader br;
    try {
        br = new BufferedReader(new InputStreamReader(response_content.getContent()));

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException | UnsupportedOperationException ex) {
        throw new MojoFailureException("Could not read response...", ex);
    }
    System.out.println(sb.toString());

    try {
        System.out.println(EntityUtils.toString(response_content));
    } catch (IOException | ParseException ex) {

    }
}