AES加密(Advanced Encryption Standard)为最常见的对称加密算法,本文给出Java的实现方式,如下:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESUtils {
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
public static String encrypt(String text, String key) {
KeyGenerator kgen;
try {
kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
byte[] b = cipher.doFinal(text.getBytes());
return new String(Base64.encodeBase64(b));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
// Method descriptor #4 ([B)[B
public static String decrypt(String text, String key) {
KeyGenerator kgen;
try {
kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
byte[] b = cipher.doFinal(Base64.decodeBase64(text));
return new String(b);//Base64.encodeBase64(b)
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
String key="9bb36032d0ad415f";
String password="123456";
String b=encrypt(password,key);
System.out.println("密文:"+b);
String c=decrypt(b,key);
System.out.println("明文:"+c);
}
}