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

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

Introduction

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

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:com.aol.webservice_base.cache.CacheManager.java

protected String hashKey(String key, String hashMechanism) {
    try {//from w w w  . j  a  v a 2s.co  m
        MessageDigest md = MessageDigest.getInstance(hashMechanism);
        md.update(key.getBytes());
        Base64 b64 = new Base64();
        return new String(b64.encode(md.digest()), "UTF-8");
    } catch (Exception e) {
        logger.error("Problem hashing: " + key + " with " + hashMechanism);
        e.printStackTrace();
        return null;
    }
}

From source file:fr.aliasource.webmail.server.proxy.client.http.UploadAttachmentMethod.java

public void upload(String attachementId, AttachmentMetadata meta, InputStream attachement) {
    logger.info("Pushing attachment to backend. " + attachementId + " fn: " + meta.getFileName() + " size: "
            + meta.getSize() + " mime: " + meta.getMime());
    Map<String, String> params = new HashMap<String, String>();
    params.put("token", token);

    params.put("id", attachementId);
    params.put("filename", meta.getFileName());
    params.put("size", "" + meta.getSize());
    params.put("mime", meta.getMime());

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/* ww w. j a  v a  2 s. c  om*/
        transfer(attachement, out, true);
        Base64 encoder = new Base64();
        String encoded = new String(encoder.encode(out.toByteArray()));
        out = null;
        params.put("content", encoded);
        executeVoid(params);
    } catch (Exception e) {
        logger.error("Error encoding attachment as base64", e);
    }
}

From source file:inti.util.Base64OutputByteBufferTest.java

public void writeSmallDataSmallBuffer(String str) throws Exception {
    byte[] data = new String(str).getBytes(UTF_8);
    int bufferSize = 32;
    ByteBuffer buffer;//from www  .j  a va  2  s  . c  om

    base64OutputByteBuffer = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET,
            Base64OutputByteBuffer.DEFAULT_PADDING, bufferSize);

    base64OutputByteBuffer.write(data);
    base64OutputByteBuffer.flush();
    buffer = base64OutputByteBuffer.getByteBuffer();

    assertEquals(new Base64().encodeAsString(data), new String(buffer.array()).trim());

    base64OutputByteBuffer = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET,
            Base64OutputByteBuffer.DEFAULT_PADDING, bufferSize);

    for (int i = 0; i < data.length; i++) {
        base64OutputByteBuffer.write(data[i]);
    }
    base64OutputByteBuffer.flush();
    buffer = base64OutputByteBuffer.getByteBuffer();

    assertEquals(new Base64().encodeAsString(data), new String(buffer.array()).trim());

    if (data.length % 2 == 0) {
        base64OutputByteBuffer = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET,
                Base64OutputByteBuffer.DEFAULT_PADDING, bufferSize);

        for (int i = 0; i < data.length; i += 2) {
            base64OutputByteBuffer.write(new byte[] { data[i], data[i + 1] });
        }
        base64OutputByteBuffer.flush();
        buffer = base64OutputByteBuffer.getByteBuffer();

        assertEquals(new Base64().encodeAsString(data), new String(buffer.array()).trim());
    }
}

From source file:adminpassword.Encryption.java

public String encrypt(String word, String idKey) throws Exception {

    byte[] ivBytes;
    String password = idKey; //you can give whatever you want. This is for testing purpose
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);//w w  w .  j a va  2  s  . c  o  m

    byte[] saltBytes = bytes;

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);
    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //encrypting the word
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8"));

    //prepend salt and vi
    byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
    System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
    System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
    System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length,
            encryptedTextBytes.length);
    return new Base64().encodeToString(buffer);
}

From source file:fr.aliasource.webmail.attachments.UploadAttachmentAction.java

public void execute(IProxy p, IParameterSource req, IResponder responder) {
    String filename = req.getParameter("filename");
    String id = req.getParameter("id");
    String size = req.getParameter("size");
    String mime = req.getParameter("mime");

    IAccount account = p.getAccount();//w  w  w. j av  a2  s. c o  m
    AttachmentManager mgr = account.getAttachementManager();

    Map<String, String> metadata = new HashMap<String, String>();
    metadata.put(AttachmentManager.META_FILENAME, filename);
    metadata.put(AttachmentManager.META_SIZE, size);
    metadata.put(AttachmentManager.META_MIME, mime);
    metadata.put(AttachmentManager.META_CONTENT_ID, "");

    Base64 decoder = new Base64();
    String contentB64 = req.getParameter("content");
    byte[] decoded = decoder.decode(contentB64.getBytes());

    try {
        mgr.store(id, metadata, new ByteArrayInputStream(decoded));
        logger.info("Attachment " + id + ": " + filename + " " + size + " " + mime + " uploaded.");
    } catch (Exception e) {
        logger.error("Error storing attachment on server", e);
    }
}

From source file:com.credomatic.gprod.db2query2csv.Security.java

/**
 * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). 
 * @param KeySize tamao de la llave autogenerada para relizar el cifrado
 * @param value cadena de caracteres que sera cifrada
 * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado
 *///from  www . j  av a 2 s. c o m
public static SecurityParams encrypt(int KeySize, String value) {

    SecurityParams result = null;
    try {
        // Get the KeyGenerator
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(KeySize);

        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        final Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        final String key = new Base64().encodeAsString(raw);
        final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));

        result = new SecurityParams(encrypt, key, KeySize);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:adminpassword.AESDemo.java

@SuppressWarnings("static-access")
public String decrypt(String encryptedText) throws Exception {

    byte[] saltBytes = salt.getBytes("UTF-8");
    byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // Decrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {/*  w ww . j a  va 2 s.  c  o m*/
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return new String(decryptedTextBytes);
}

From source file:eu.serco.dhus.config.ConfigurationManager.java

public static String getHashedConnectionString() {
    String hashedString = "";
    try {//w w w  . ja  va  2  s  .c om
        String unhashedString = getExternalDHuSUsername() + ":" + getExternalDHuSPassword();
        Base64 base64 = new Base64();
        hashedString = (String) base64.encodeToString(unhashedString.getBytes());
    } catch (Exception e) {
        logger.error("Error retrieving Hashed Connection String");
        e.printStackTrace();
    }
    return hashedString;
}

From source file:net.mobid.codetraq.utils.PasswordProcessor.java

/**
 * Encrypts a text using the <code>passPhrase</code> above and an algorithm supported
 * by your virtual machine implementation. You can change the default algorithm with
 * another algorithm, but please make sure your virtual machine supports it.
 * @param valueToEncrypt - text to encrypt
 * @return an encrypted, Base64 encoded text
 *///w  w  w.  jav a2  s  . com
public static String encryptString(String valueToEncrypt) {
    String output = null;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        // begin encrypting...
        byte[] byteToEncrypt = valueToEncrypt.getBytes("UTF8");
        byte[] encrypted = cipher.doFinal(byteToEncrypt);
        output = new Base64().encodeToString(encrypted);
    } catch (Exception ex) {
        Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:inti.util.Base64OutputByteBufferPerformanceTest.java

public void writePerformance(int count, int bufferSize) throws Exception {
    Base64OutputByteBuffer output = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET,
            Base64OutputByteBuffer.DEFAULT_PADDING, 104857600);
    byte[] data;//  w  w w.j  a  v  a  2s .c om
    long start, end;
    Base64 b64 = new Base64();
    StringBuilder message = new StringBuilder();

    for (int i = 0; i < bufferSize / 10; i++) {
        message.append("0123456789");
    }
    data = message.toString().getBytes(Charset.forName("utf-8"));

    for (int i = 0; i < 10; i++) {
        output.reset();
        output.write(data);
        output.flush();
    }

    for (int i = 0; i < 100; i++) {
        Thread.sleep(10);
    }

    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        output.reset();
        output.write(data);
        output.flush();
    }
    end = System.currentTimeMillis();
    output.close();

    System.out.format("writePerformance(Inti) - size: %d, duration: %dms, ratio: %#.4f", bufferSize,
            end - start, count / ((end - start) / 1000.0));
    System.out.println();

    for (int i = 0; i < 10; i++) {
        b64.encode(data);
    }

    for (int i = 0; i < 100; i++) {
        Thread.sleep(10);
    }

    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        b64.encode(data);
    }
    end = System.currentTimeMillis();
    System.out.format("writePerformance(commons.codec) - size: %d, duration: %dms, ratio: %#.4f", bufferSize,
            end - start, count / ((end - start) / 1000.0));
    System.out.println();
}