[Cryptography] Java AES 128 암호화 예제
AES 128bit 임으로 string length 16인(16 * 8 = 128bit) key를 넣어 준다.
public String encryptByAES(String plain, String key) { try { SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, spec); byte[] encTxt = cipher.doFinal(plain.getBytes()); return Base64.getEncoder().encodeToString(encTxt); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Cipher exception: " + e.getMessage()); } } // encTxt: base64 encoded. public String decryptByAES(String b64EncTxt, String key) { try { SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, spec); byte[] b64Decoded = Base64.getDecoder().decode(b64EncTxt.getBytes()); byte[] plain = cipher.doFinal(b64Decoded); return new String(plain); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Cipher exception: " + e.getMessage()); } }
댓글
댓글 쓰기