aes256 암호화
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.NoSuchAlgorithmException;
public class AES256 {
public static SecretKeySpec getKeySpec() throws IOException, NoSuchAlgorithmException {
byte[] bytes = new byte[32];
SecretKey key = null;
SecretKeySpec spec = null;
/*
File f = new File("aes_key");
if (f.exists()) {
new FileInputStream(f).read(bytes);
} else {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256);
key = kgen.generateKey();
bytes1 = key.getEncoded();
new FileOutputStream(f).write(bytes1);
}
*/
String keyStr="암호화된 대칭키";
bytes = Base64Utils.base64Decode(keyStr);
spec = new SecretKeySpec(bytes,"AES");
return spec;
}
public String encrypt(String text) throws Exception {
SecretKeySpec spec = getKeySpec();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, spec);
BASE64Encoder enc = new BASE64Encoder();
return enc.encode(cipher.doFinal(text.getBytes())).toString();
}
public String decrypt(String text) throws Exception {
SecretKeySpec spec = getKeySpec();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, spec);
BASE64Decoder dec = new BASE64Decoder();
return new String(cipher.doFinal(dec.decodeBuffer(text)));
}
public static void main(String[] args) throws Exception {
String mode = "encrypt";
String text = "!mpluse0218";
String encText = "";
String decText = "";
AES256 aes = new AES256();
encText=aes.encrypt(text);
System.out.println("5ClhQFro0UAI+LrZkilamw==");
System.out.println("enc::"+encText);
decText = aes.decrypt(encText);
System.out.println("dec::"+decText);
}
}
댓글 없음:
댓글 쓰기