반응형

이번 포스팅은 대칭키 암복호화 중 가장 많이 사용하는 AES 알고리즘 암복호화에 대하여 알아보도록 하겠습니다.

 

1. 암호화

public byte[] Encrypt(String text, String key) throws Exception {

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

byte[] keyBytes= new byte[16];

byte[] b= key.getBytes("UTF-8");

 

int len= b.length;

if (len > keyBytes.length) len = keyBytes.length;

System.arraycopy(b, 0, keyBytes, 0, len);

 

SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);

cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);

 

byte[] results = cipher.doFinal(text.getBytes("UTF-8"))

return result;

}

 

2. 복호화

public String Decrypt(String text, String key) throws Exception {

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

byte[] keyBytes= new byte[16];

byte[] b= key.getBytes("UTF-8");

int len= b.length;

if (len > keyBytes.length) len = keyBytes.length;

                    

System.arraycopy(b, 0, keyBytes, 0, len);

SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);

byte [] results =cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);

        return results;

 }              

반응형

+ Recent posts