티스토리 뷰

728x90
반응형

https://mvnrepository.com/artifact/commons-codec/commons-codec

위 링크로 commons-code 1.10  pom.xml에추가 


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);
}


728x90
반응형

'보안 > 암호화' 카테고리의 다른 글

[암호화] Java SHA256 암호화하는법  (0) 2019.08.29
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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 27 28 29 30 31
글 보관함