1. Data Encryption Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public static String encryptAes256(String key, String initVector, String value) throws Exception { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(value.getBytes()); return Base64.encodeBase64String(encrypted); } public static String decryptAes256(String key, String initVector, String encrypted) throws Exception { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); return new String(original); } public static void main(String[] args) throws Exception { String key = "1234567890abcdef"; // 128 bit key String initVector = "0987654321ABCDEF"; // 16 bytes IV String encrypted = encryptAes256(key, initVector, "Hello World"); String decrypted = decryptAes256(key, initVector, encrypted); System.out.println( "encrypted: " + encrypted); System.out.println( "decrypted: " + decrypted); } |
Result:
encrypted: O/SLjrjo8eM9trB643lqdA== decrypted: Hello World
댓글 없음:
댓글 쓰기