AESUtils

2765 ワード


import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

private static KeyGenerator keyGen;
private static Cipher cipher;
private static final String algorithmStr = "AES/ECB/PKCS5Padding";
private static String keyStr = "aaaaaa";

static {
try {
// keyGen
keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
// cipher
cipher = Cipher.getInstance(algorithmStr);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws NoSuchAlgorithmException {
String string = "{\"name\": \"test\"}";
String string2 = "www";
String encryptString = encrypt(string);
System.out.println(" : " + string + " : " + encryptString + " : " + decrypt(encryptString));
String encryptString2 = encrypt(string2);
System.out.println(" : " + string2 + " : " + encryptString2 + " : " + decrypt(encryptString2));
}

/**
* .
*/
public static String encrypt(String content) {
byte[] encryptedBytes = null;
Key key = new SecretKeySpec(keyStr.getBytes(), "AES");
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedBytes = cipher.doFinal(stringToBytes(content));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return bytesToString(Base64.getEncoder().encode(encryptedBytes));
}

/**
* .
*/
public static String decrypt(String content) {
byte[] originBytes = null;

Key key = new SecretKeySpec(keyStr.getBytes(), "AES");
try {
cipher.init(Cipher.DECRYPT_MODE, key);
originBytes = cipher.doFinal(Base64.getDecoder().decode(content));
} catch (Exception e) {
e.printStackTrace();
}
return bytesToString(originBytes);
}

/**
* .
*/
private static byte[] stringToBytes(String str) {
return str.getBytes();
}

/**
* .
*/
private static String bytesToString(byte[] bytes) {
String string = null;
try {
string = new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
}