注册

AES加密,解密



【代码】
private static final String password = "test";
private static SecretKeySpec keypSpec;
private static Cipher cipher;

private static void init(){

try {

KeyGenerator kenGen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kenGen.init(128, secureRandom);

SecretKey secretKey = kenGen.generateKey();
byte[] encodeFormat = secretKey.getEncoded();

keypSpec = new SecretKeySpec(encodeFormat, "AES");

cipher = Cipher.getInstance("AES");

} catch (Exception e) {
log.error("init AES Key fail", e);
}
}

public final static byte[] AESencrypt(String content){

byte[] result = null;

try {

init();

byte[] byteContent = content.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, keypSpec);

result = cipher.doFinal(byteContent);

} catch (Exception e) {
log.error("encrypt AES fail", e);
}

return result;
}

public final static String AESdecrypt(byte[] content){

String result = null;

try {

init();

cipher.init(Cipher.DECRYPT_MODE, keypSpec);

result = new String(cipher.doFinal(content),"UTF-8");

} catch (Exception e) {
log.error("decrypt AES fail", e);
}

return result;
}

已邀请:

要回复问题请先登录注册