JDK 1.8 自带 Crypto 加密封装工具类
工具类
public class CryptoUtil {
private static final String ALGORITHM = "DESede";
private static final String SECRET = "PUBLICSTATICVOIDMAINSTRINGARGS";
public static byte[] encode(byte[] encode) {
byte[] result = new byte[0];
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, getKey(SECRET));
result = cipher.doFinal(encode);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String encode2Base64(String encode) {
return Base64.getEncoder().encodeToString(encode(encode.getBytes()));
}
public static Key getKey(String key) {
return getDESedeKey(key.getBytes());
}
public static Key getDESedeKey(byte[] key) {
Key secretKey = null;
try {
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
secretKey = keyFactory.generateSecret(spec);
}catch (Exception e){
e.printStackTrace();
}
return secretKey;
}
public static byte[] decode(byte[] decode) {
byte[] result = new byte[0];
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getKey(SECRET));
result = cipher.doFinal(decode);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String decodeBase64(String baseDecode) {
byte[] decode = Base64.getDecoder().decode(baseDecode.getBytes());
byte[] bytes = decode(decode);
return new String(bytes);
}
public static void main(String[] args) {
String content = "";
System.out.println("encode: " + new String(CryptoUtil.encode(content.getBytes())));
System.out.println("encode2Base64: " + CryptoUtil.encode2Base64(content));
String secret = "";
System.out.println("decodeBase64: " + CryptoUtil.decodeBase64(secret));
}
}