자바 aes 암호화 복호화
package test;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESTest2 {
public static void main(String[] args) throws Exception {
String keyPassword="1234567890123456"; //여러문이 만들 키
String target="plainText";
byte[] targetBytes = target.getBytes("UTF-8");
// 128bit AES 사용으로 블럭사이즈는 16. 16 byte의 블럭을 사용
int blockSize = 128 / 8;
//위에서 정한 패스워드로 키를 만듬
SecretKeySpec keySpec = new SecretKeySpec(keyPassword.getBytes(), "AES");
Cipher cipher = null;
IvParameterSpec iv = null;
try{
// AES 알고리즘에 CBC blockcipher 모드에 PKCS5Padding을 사용하는 Cipher 생성
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 블럭사이즈 만큼의 바이트 배열 선언
byte[] randomSalt = new byte[blockSize];
// Initiallizr Vector에 사용할 배열
System.arraycopy(keySpec.getEncoded(), 0, randomSalt, 0, blockSize);
// 만들어진 랜덤 솔트로 IV를 만듬
iv=new IvParameterSpec(randomSalt);
// 암호화 모드로 init
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// 암호화
byte[] crypted = cipher.doFinal(targetBytes);
// 암호화 된것은 바이너리
System.out.println("암호화 Base64 인코딩 전 = " + new String(crypted));
// 바이너리를 base64로 인코딩
Encoder encoder = Base64.getEncoder();
// Encoder#encode(byte[] src) :: 바이트배열로 반환
byte[] encodedBytes = encoder.encode(crypted);
System.out.println("인코딩 바이트배열 text = " + new String(encodedBytes));
// Encoder#encodeToString(byte[] src) :: 문자열로 반환
String encodedString = encoder.encodeToString(crypted);
System.out.println("인코딩 문자열 text = " + encodedString);
// Base64 디코딩 ///////////////////////////////////////////////////
Decoder decoder = Base64.getDecoder();
// Decoder#decode(bytes[] src)
byte[] decodedBytes1 = decoder.decode(encodedBytes);
System.out.println("암호화 Base64 디코드 = " + new String(decodedBytes1));
// Decoder#decode(String src)
byte[] decodedBytes2 = decoder.decode(encodedString);
// 디코딩한 문자열을 표시
String decodedString = new String(decodedBytes1, "UTF-8");
System.out.println("바이트 배열 디코드 = " + decodedString);
System.out.println("문자열 디코드 = " + new String(decodedBytes2, "UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
//byte[] decoded = Base64.decodeBase64(encoded);
byte[] decrypted = cipher.doFinal(crypted);
System.out.println(new String(decrypted));
byte[] decrypted2 = cipher.doFinal(decodedBytes2);
System.out.println(new String(decrypted2));
}catch(Exception e){
e.printStackTrace();
}
}
}