반응형
프로젝트 bulid path에 아래 jar 파일 추가 필요
AES128 클래스를 만든다.
package 패키지명;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES128 {
private String ips;
private Key keySpec;
public AES128(String key) {
try {
byte[] keyBytes = new byte[16];
byte[] b = key.getBytes("UTF-8");
System.arraycopy(b, 0, keyBytes, 0, keyBytes.length);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
this.ips = key.substring(0, 16);
this.keySpec = keySpec;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public String encrypt(String str) {
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec,
new IvParameterSpec(ips.getBytes()));
byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
String Str = new String(Base64.encodeBase64(encrypted));
return Str;
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| IllegalBlockSizeException | BadPaddingException
| UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public String decrypt(String str) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec,
new IvParameterSpec(ips.getBytes("UTF-8")));
byte[] byteStr = Base64.decodeBase64(str.getBytes());
String Str = new String(cipher.doFinal(byteStr), "UTF-8");
return Str;
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| IllegalBlockSizeException | BadPaddingException
| UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
호출부분
public class TestJava {
public static void main(String[] args) {
AES128 aes128 = new AES128("key");
// 암호화
String enc = aes128.encrypt("암호화 하려는 값");
System.out.println(enc);
// 복호화
System.out.println(aes128.decrypt(enc));
}
}
반응형
'개발 > java' 카테고리의 다른 글
String(문자열) 가공하기 (0) | 2021.01.17 |
---|---|
java (jdk) 버전별 다운로드 링크 (0) | 2021.01.17 |
e.printStackTrace() 를 String 으로 변환하기 (printStackTrace to String) (0) | 2021.01.17 |
byteArrayToHex (0) | 2021.01.17 |
한글 <-> 유니코드 변환 (0) | 2021.01.17 |
댓글