最近在看Android安全方面的书,提到了AES加密,为了方便日后调用,写了一个实用类。
/**
* AESUtil
* @author 健健
* @date 2014/10/28
* @QQ 4999315
*/
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
/**
* generate AES key
*
* @param randomNumberSeed
* @return
*/
public static byte[] generateKey(byte[] randomNumberSeed) {
SecretKey sKey = null;
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(randomNumberSeed);
keyGen.init(128, random);
sKey = keyGen.generateKey();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sKey.getEncoded();
}
/**
* encrypt
*
* @param key
* @param data
* @return
*/
public static byte[] encrypt(byte[] key, byte[] data) {
SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = null;
byte[] cipherText = null;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec); // encrypt
cipherText = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cipherText;
}
/**
* decrypt
*
* @param key
* @param data
* @return
*/
public static byte[] decrypt(byte[] key, byte[] data) {
SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = null;
byte[] cipherText = null;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec); // encrypt
cipherText = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cipherText;
}
public static void main(String[] args) {
byte[] key = generateKey("this is the key".getBytes());
String originalData = "this is the data";
// encrypt
byte[] cipherText = encrypt(key, originalData.getBytes());
// decrypt
String decryptData = new String(decrypt(key, cipherText));
System.out.println(decryptData);
}
}