public class CipherUtil { private Log LOG = LogFactory.getLog(this.getClass()); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub CipherUtil cu = new CipherUtil(); Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssss"); String key = sdf.format(cal.getTime()); System.out.println("key: " + key); String text = "가나다라마바사@★아&자@12!@#$%"; String encryptText = null; String decryptText = null; try { encryptText = cu.encryptAES(text, key); decryptText = cu.decryptAES(encryptText, key); } catch (Exception e) { e.printStackTrace(); } System.out.println("encryptText: " + encryptText); System.out.println("beforeText : " + text); System.out.println("decryptText: " + decryptText); // 2011051813190051 // abcdefgh01234567 } // key는 16바이트로 구성 되어야 한다. private String encryptAES(String s, String key) throws Exception { String encrypted = null; try { SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); encrypted = byteArrayToHex(cipher.doFinal(s.getBytes())); return encrypted; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e.getMessage(), e); } throw e; } } // key는 16 바이트로 구성 되어야 한다. private String decryptAES(String s, String key) throws Exception { String decrypted = null; try { SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); decrypted = new String(cipher.doFinal(hexToByteArray(s))); return decrypted; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e.getMessage(), e); } throw e; } } private byte[] hexToByteArray(String s) { byte[] retValue = null; if (s != null && s.length() != 0) { retValue = new byte[s.length() / 2]; for (int i = 0; i < retValue.length; i++) { retValue[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16); } } return retValue; } private String byteArrayToHex(byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); for (int i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) { strbuf.append("0"); } strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); } }
[출처] 구글링