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.neovisionaries.security.DigestTest.java

@Test
public void test9() {
    String expected = "KuAUcjF9GTWoR5fsGYOuJD/Gqig=";
    String actual = sha1().update("Hello, world.").digestAsString(new Base64());

    assertEquals(expected, actual);/*from w  ww  . ja v  a 2 s.c  om*/
}

From source file:example.DecrypterException.java

/**
 * Performs the decryption algorithm.//ww w.j  av  a2s. c om
 *
 * This method decrypts the ciphertext using the encryption key and verifies
 * the integrity bits with the integrity key. The encrypted format is:
 * {initialization_vector (16 bytes)}{ciphertext}{integrity (4 bytes)}
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-
 * hyperlocal,
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt
 * -price and https://support.google.com/adxbuyer/answer/3221407?hl=en have
 * more details about the encrypted format of hyperlocal, winning price,
 * IDFA, hashed IDFA and Android Advertiser ID.
 */
public static byte[] decrypt(byte[] ciphertext, SecretKey encryptionKey, SecretKey integrityKey)
        throws DecrypterException {
    try {
        // Step 1. find the length of initialization vector and clear text.
        final int plaintext_length = ciphertext.length - INITIALIZATION_VECTOR_SIZE - SIGNATURE_SIZE;
        if (plaintext_length < 0) {
            throw new RuntimeException("The plain text length can't be negative.");
        }
        System.out.println(Arrays.toString(ciphertext));
        System.out.println(byte2hex(ciphertext));
        System.out.println(ciphertext.length);
        System.out.println(plaintext_length);

        byte[] iv = Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE);

        // Step 2. recover clear text
        final Mac hmacer = Mac.getInstance("HmacSHA1");
        hmacer.init(encryptionKey);

        final int ciphertext_end = INITIALIZATION_VECTOR_SIZE + plaintext_length;
        final byte[] plaintext = new byte[plaintext_length];
        boolean add_iv_counter_byte = true;
        for (int ciphertext_begin = INITIALIZATION_VECTOR_SIZE, plaintext_begin = 0; ciphertext_begin < ciphertext_end;) {
            System.out.println("=====> FOR:");
            hmacer.reset();
            hmacer.init(encryptionKey);
            System.out.println("iv: " + byte2hex(iv));
            final byte[] pad = hmacer.doFinal(iv);
            System.out.println("pad: " + byte2hex(pad) + "  len(pad): " + pad.length);
            Base64 encoder = new Base64();
            String pad_base64 = new String(encoder.encode(pad));
            System.out.println("pad Base64: " + pad_base64);

            int i = 0;
            while (i < BLOCK_SIZE && ciphertext_begin != ciphertext_end) {
                plaintext[plaintext_begin++] = (byte) (ciphertext[ciphertext_begin++] ^ pad[i++]);
            }

            if (!add_iv_counter_byte) {
                final int index = iv.length - 1;
                add_iv_counter_byte = ++iv[index] == 0;
            }

            if (add_iv_counter_byte) {
                add_iv_counter_byte = false;
                iv = Arrays.copyOf(iv, iv.length + 1);
            }
        }
        System.out.println("plaintext: " + byte2hex(plaintext));

        // Step 3. Compute integrity hash. The input to the HMAC is
        // clear_text
        // followed by initialization vector, which is stored in the 1st
        // section
        // or ciphertext.
        hmacer.reset();
        hmacer.init(integrityKey);
        hmacer.update(plaintext);
        hmacer.update(Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE));
        final byte[] computedSignature = Arrays.copyOf(hmacer.doFinal(), SIGNATURE_SIZE);
        final byte[] signature = Arrays.copyOfRange(ciphertext, ciphertext_end,
                ciphertext_end + SIGNATURE_SIZE);
        if (!Arrays.equals(signature, computedSignature)) {
            throw new DecrypterException("Signature mismatch.");
        }
        return plaintext;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HmacSHA1 not supported.", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Key is invalid for this purpose.", e);
    }
}

From source file:com.ning.metrics.collector.TestPerformance.java

private static String createThriftPayload() throws TException {
    ArrayList<ThriftField> data = new ArrayList<ThriftField>();
    data.add(ThriftField.createThriftField("Fuu", (short) 1));
    data.add(ThriftField.createThriftField(true, (short) 2));
    data.add(ThriftField.createThriftField(3.1459, (short) 3));
    return String.format("%s:%s", new DateTime().getMillis(),
            new Base64().encodeToString(new ThriftFieldListSerializer().createPayload(data)));
}

From source file:jlib.xml.XMLUtil.java

public static String encode64AsString(String cs) {
    Base64 base64 = new Base64();
    byte[] arrBytes = cs.getBytes();
    byte[] tOut = base64.encode(arrBytes);
    String csOut = new String(tOut);
    return csOut;
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * /*from ww  w. java  2  s .  c  o m*/
 * This method is used for decrypt by using Algorithm - AES/CBC/PKCS5Padding
 * 
 * @param String
 * @return String
 * @throws Exception
 */
@SuppressWarnings("static-access")
public static String decryptAESPBKDF2(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(SECRET_KEY.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_ALGO);
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {

        LOGGER.error("error " + e.getMessage());
    } catch (BadPaddingException e) {
        LOGGER.error("error " + e.getMessage());
    }

    return new String(decryptedTextBytes);
}

From source file:com.forsrc.utils.MyRsa2Utils.java

/**
 * Gets private key.//  w ww .  j  a va 2  s  . com
 *
 * @param key the key
 * @return the private key
 * @throws RsaException the rsa exception
 */
public static PrivateKey getPrivateKey(String key) throws RsaException {
    byte[] keyBytes;
    try {
        keyBytes = (new Base64()).decode(key);
    } catch (Exception e) {
        throw new RsaException(e);
    }
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RsaException(e);
    }
    PrivateKey privateKey = null;
    try {
        privateKey = keyFactory.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new RsaException(e);
    }
    return privateKey;
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.SVGImageExporter.java

private static String svgToImageTag(final String id, final SVGImage svgImage, final float cellWidth,
        final float cellHeight, final boolean scale) {
    final String baseEncoded = new Base64().encodeAsString(svgImage.getImageData());
    final StringBuilder result = new StringBuilder("<image id=\"").append(id).append('\"');

    final String xscale = scale ? num2str(cellWidth / svgImage.getSVGWidth()) : null;
    final String yscale = scale ? num2str(cellHeight / svgImage.getSVGHeight()) : null;

    result.append(" xlink:href=\"data:image/svg+xml;base64,").append(baseEncoded).append('\"');
    result.append(" width=\"").append(num2str(svgImage.getSVGWidth())).append("\" height=\"")
            .append(svgImage.getSVGHeight()).append('\"');
    if (scale) {//w  w  w  . j a v a  2  s . c  o m
        result.append(" transform=\"scale(").append(xscale).append(',').append(yscale).append(")\"");
    }

    result.append("/>");
    return result.toString();
}

From source file:ch.entwine.weblounge.maven.MyGengoI18nImport.java

private URLConnection getMyGengoConn() {
    // Request MyGengo i18n file
    URLConnection conn;//from   w  w  w  . ja va 2  s.c  o  m
    try {
        conn = myGengoUrl.openConnection();
        if (StringUtils.isNotBlank(myGengoUsername) && StringUtils.isNotBlank(myGengoPassword))
            conn.setRequestProperty("Authorization", "Basic "
                    + (new Base64()).encode((myGengoUsername + ":" + myGengoPassword).getBytes()).toString());
    } catch (IOException e) {
        log.error("Error getting zip file from myGengo.");
        return null;
    }
    return conn;
}

From source file:com.ligadata.Utils.EncryptDecryptUtils.java

/**
 * Encode(Base64 encoding) given byte array to a string
 * //from   ww  w.j  ava 2 s  . c o m
 * @param bytes
 *          : an array of bytes corresponding to string being encoded
 * @return String
 * @throws java.lang.Exception
 */

public static String encode(byte[] bytes) {
    try {
        Base64 base64 = new Base64();
        String encoded = new String(base64.encode(bytes));
        return encoded;
    } catch (Exception e) {
        logger.error("Failed to encode a  byte array", e);
        throw e;
    }
}

From source file:com.ooyala.api.OoyalaAPI.java

/**
 * Constructor with keys//from   w w w . j  ava 2 s .c  o  m
 * @param apiKey The API key
 * @param secretKey The secret key
 */
public OoyalaAPI(String _apiKey, String _secretKey) {
    secretKey = _secretKey;
    apiKey = _apiKey;
    baseURL = "https://api.ooyala.com/v2/";
    expirationWindow = 15;
    roundUpTime = 300;
    new Base64();
    contentType = "application/json";
}