AES加密java程序
程序员文章站
2024-03-14 15:47:34
...
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
/**
* *AES加密解密工具类
* *@author
*
*/
public class AESUtil {
public static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede
public static Key getKey(String strKey) {
try {
if (strKey == null) {
strKey = "";
}
KeyGenerator _generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(strKey.getBytes());
_generator.init(128, secureRandom);
return _generator.generateKey();
} catch (Exception e) {
throw new RuntimeException(" 初始化**出现异常 ");
}
}
public static String encrypt(String data, String key) throws Exception {
SecureRandom sr = new SecureRandom();
Key secureKey = getKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
byte[] bt = cipher.doFinal(data.getBytes());
String strS = new BASE64Encoder().encode(bt);
return strS;
}
public static String decrypt(String message, String key) {
try {
SecureRandom sr = new SecureRandom();
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
Key secureKey = getKey(key);
cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
byte[] res = new BASE64Decoder().decodeBuffer(message);
res = cipher.doFinal(res);
return new String(res);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
String enc = encrypt("66666666", "123456");
System.out.println(enc);
String dec = decrypt("oZfiu/Mpn+v64BiF+AWwcg==", "123456");
System.out.println(dec);
// if ("e".equals(args[0])) {
// System.out.println(encrypt(args[1], args[2]));
// } else if ("d".equals(args[0])) {
// System.out.println(decrypt(args[1], args[2]));
// }
}
}
上一篇: 微信小程序使用AES加密和解密