Snippets

David Whitehurst AESCryptoUtil.java (modified salt)

Created by David Whitehurst
/**
 * Copyright (c) CI Wise Inc.  All rights reserved.  http://www.ciwise.com
 * The software in this package is published under the terms of the Apache
 * version 2.0 license, a copy of which has been included with this distribution 
 * in the LICENSE.txt file.
 * 
 */ 

package com.ciwise.accounting.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 *  @author <a href="mailto:david@ciwise.com">David L. Whitehurst</a>
 *
 */
public class AESCryptoUtil {

    /**
     * This method encrypts a string and returns a byte array of
     * the encrypted result.
     * 
     * @param value
     * @return
     */
    public static byte[] encrypt(String value) {
        byte[] encrypted = null;
        try {
            byte[] raw = new byte[]{'A', 'b', 'c', 'D', 'E', 'f', 'g', 'z', '4', 'x', '9', '9', '0', 'O', 'c', 'j'};
            Key skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] iv = new byte[cipher.getBlockSize()];

            IvParameterSpec ivParams = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParams);
            encrypted = cipher.doFinal(value.getBytes());
            //System.out.println("encrypted string:" + encrypted.length);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return encrypted;
    }

    /**
     * @param encrypted
     * @return
     */
    public static byte[] decrypt(byte[] encrypted) {
        byte[] original = null;
        Cipher cipher = null;
        try {
            byte[] raw = new byte[]{'A', 'b', 'c', 'D', 'E', 'f', 'g', 'z', '4', 'x', '9', '9', '0', 'O', 'c', 'j'};

            Key key = new SecretKeySpec(raw, "AES");
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //the block size (in bytes), or 0 if the underlying algorithm is not a block cipher
            byte[] ivByte = new byte[cipher.getBlockSize()];
            //This class specifies an initialization vector (IV). Examples which use
            //IVs are ciphers in feedback mode, e.g., DES in CBC mode and RSA ciphers with OAEP encoding operation.
            IvParameterSpec ivParamsSpec = new IvParameterSpec(ivByte);
            cipher.init(Cipher.DECRYPT_MODE, key, ivParamsSpec);
            original = cipher.doFinal(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return original;
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.