AES 128비트 암호화(ECB 모드, PKCS5Padding)

2019. 4. 2. 15:44 JAVA/Java

AES 128 비트 암호화 / 복호화


ECB 모드 <-- 중요(CBC 아님)

PKCS5Padding <-- 패딩방식


자바 버전

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class Aes128 {
    /**
     * 암호화
     *
     * @param input
     * @param key
     * @return
     */
    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {
 
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
 
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        catch(Exception e) {
            System.out.println(e.toString());
        }
 
        BASE64Encoder encoder = new BASE64Encoder();
 
        String str = encoder.encode(crypted);
 
        return new String(str);
    }
 
    /**
     * 복호화
     *
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
 
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
 
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(decoder.decodeBuffer(input));
 
        catch(Exception e) {
            System.out.println(e.toString());
        }
        return new String(output);
    }
}


사용 방법

public void aes_enc() throws Exception {
 
    Aes128 aes = new Aes128();
    String key = "0123456789abcdef";
 
    String str = "yangyag";
    String encode = aes.encrypt(str, key);
 
    System.out.println("encode--->" + encode);
}
 
public void aes_dec() throws Exception {
     
    Aes128 aes = new Aes128();
    String key = "0123456789abcdef";
     
    String str = "bcOXU9eLYKadQejOHkjvbg==";
    String decode = aes.decrypt(str, key);
     
    System.out.println("decode--->" + decode);
}



출처: https://yangyag.tistory.com/467 [Hello Brother!]