티스토리 뷰
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 |
---|