AES256Util.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.icontrols.oauth.utils;
  2. import java.io.UnsupportedEncodingException;
  3. import java.security.GeneralSecurityException;
  4. import java.security.Key;
  5. import java.security.NoSuchAlgorithmException;
  6. import javax.crypto.Cipher;
  7. import javax.crypto.spec.IvParameterSpec;
  8. import javax.crypto.spec.SecretKeySpec;
  9. import org.apache.tomcat.util.codec.binary.Base64;
  10. public class AES256Util {
  11. private String iv;
  12. private Key keySpec;
  13. /**
  14. * 16자리의 키값을 입력하여 객체를 생성한다.
  15. *
  16. * @param key 암/복호화를 위한 키값
  17. * @throws UnsupportedEncodingException 키값의 길이가 16이하일 경우 발생
  18. */
  19. final static String key = "icontrolsrndcenter";
  20. public AES256Util() throws UnsupportedEncodingException {
  21. this.iv = key.substring(0, 16);
  22. byte[] keyBytes = new byte[16];
  23. byte[] b = key.getBytes("UTF-8");
  24. int len = b.length;
  25. if (len > keyBytes.length) {
  26. len = keyBytes.length;
  27. }
  28. System.arraycopy(b, 0, keyBytes, 0, len);
  29. SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
  30. this.keySpec = keySpec;
  31. }
  32. /**
  33. * AES256 으로 암호화 한다.
  34. *
  35. * @param str 암호화할 문자열
  36. * @return
  37. * @throws NoSuchAlgorithmException
  38. * @throws GeneralSecurityException
  39. * @throws UnsupportedEncodingException
  40. */
  41. public String encrypt(String str)
  42. throws NoSuchAlgorithmException, GeneralSecurityException, UnsupportedEncodingException {
  43. Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
  44. c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
  45. byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
  46. String enStr = new String(Base64.encodeBase64(encrypted));
  47. return enStr;
  48. }
  49. /**
  50. * AES256으로 암호화된 txt 를 복호화한다.
  51. *
  52. * @param str 복호화할 문자열
  53. * @return
  54. * @throws NoSuchAlgorithmException
  55. * @throws GeneralSecurityException
  56. * @throws UnsupportedEncodingException
  57. */
  58. public String decrypt(String str)
  59. throws NoSuchAlgorithmException, GeneralSecurityException, UnsupportedEncodingException {
  60. Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
  61. c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
  62. byte[] byteStr = Base64.decodeBase64(str.getBytes());
  63. return new String(c.doFinal(byteStr), "UTF-8");
  64. }
  65. }