Created
March 2, 2017 06:43
-
-
Save dlwhitehurst/053e59e98fd717101e9e1aa7c29aae19 to your computer and use it in GitHub Desktop.
AESCryptoUtil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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:[email protected]">David L. Whitehurst</a> | |
* | |
*/ | |
public class AESCryptoUtil { | |
/** | |
* @param value | |
* @return | |
*/ | |
public static byte[] encrypt(String value) { | |
byte[] encrypted = null; | |
try { | |
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'}; | |
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[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'}; | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment