낭만 프로그래머
Java 간단한 암호화 복호화 본문
간단하게 암호화 복호화 소스
- Apache Commons Codec 라이브러리가 필요
https://commons.apache.org/proper/commons-codec/download_codec.cgi
import org.apache.commons.codec.binary.Base64;
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;
public class AES256Util {
private Key keySpec;
private String iv;
private String key = "변경하자 키";
public AES256Util() throws UnsupportedEncodingException {
iv = this.key.substring(0, 16);
byte[] keyBytes = new byte[16];
byte[] b = iv.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");
this.keySpec = keySpec;
}
// 암호화
public String aesEncode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(this.iv.getBytes()));
byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
String enStr = new String(Base64.encodeBase64(encrypted));
return enStr;
}
//복호화
public String aesDecode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(this.iv.getBytes("UTF-8")));
byte[] byteStr = Base64.decodeBase64(str.getBytes());
return new String(c.doFinal(byteStr),"UTF-8");
}
}
'Java > Common' 카테고리의 다른 글
Java Swing에서 Nimbus LookAndFeel 사용 후 일괄로 Font 변경 (0) | 2018.11.29 |
---|---|
Java Swing 에서 Nimbus Look and Feel 사용하기 (0) | 2018.11.20 |
Java8 에서 MS Access 하는 JDBC 사용 (0) | 2018.02.01 |
org.apache.commons.lang3 의 StringEscapeUtils를 사용하여 Xml, Java, Javascript, Json 으로 문법형태로 문자열 변환하기 (0) | 2017.04.06 |
Java POI를 이용한 Big Data Export (0) | 2017.04.06 |