Java Security/AES Encryptoin, Decryption

Java Encryption/Decryption

Soul-Learner 2014. 7. 26. 15:59

Java에서 AES 알고리즘을 이용한 암호화/복호화 (Encryption/Decryption) 예제


KeyStore에 저장된 AES 키를 로드하여 암호화/복호화에 사용하는 예는 여기를 참조하세요


import java.security.Key;

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;


public class Java_AES_Test {


    public void run() {

      try {

         String text = "Hello World";

         String key = "Bar12345Bar12345"; // 128 bit key


         System.out.println("원래의 텍스트:" + text);

         

         // Create key and cipher

         Key aesKey = new SecretKeySpec(key.getBytes(), "AES");

         Cipher cipher = Cipher.getInstance("AES");


         // encrypt the text

         cipher.init(Cipher.ENCRYPT_MODE, aesKey);

         byte[] encrypted = cipher.doFinal(text.getBytes());


         System.out.println("암호화된 텍스트:" + new String(encrypted));


         // decrypt the text

         cipher.init(Cipher.DECRYPT_MODE, aesKey);

         String decrypted = new String(cipher.doFinal(encrypted));


         System.out.println("복호화된 텍스트:" + decrypted);


      }catch(Exception e) {

         e.printStackTrace();

      }

    }


    public static void main(String[] args) {


    Java_AES_Test app = new Java_AES_Test();

    app.run();

    }

}