1. AES算法简介
AES加密过程涉及到4种操作:字节替代(SubBytes)、行移位(ShiftRows)、列混淆(MixColumns)和轮密钥加(AddRoundKey)。解密过程分别为对应的逆操作。由于每一步操作都是可逆的,按照相反的顺序进行解密即可恢复明文。加解密中每轮的密钥分别由初始密钥扩展得到。算法中16(byte)字节的明文、密文和轮密钥都以一个4x4的矩阵表示。
AES的密码必须是16byte。
参考博客:http://www.cnblogs.com/OneFri/p/5924605.html
![](https://box.kancloud.cn/683db905338afdafe92a717fd18f22df_280x280.jpg)
2. AES算法实现
AES的java实现比较简单,只需要把密码设置为16byte,然后将DES算法实现的java代码中,将DES修改为AES即可。
~~~
1. package com;
2.
3. import java.io.UnsupportedEncodingException;
4. import java.security.InvalidKeyException;
5. import java.security.Key;
6. import java.security.NoSuchAlgorithmException;
7.
8. import javax.crypto.BadPaddingException;
9. import javax.crypto.Cipher;
10. import javax.crypto.IllegalBlockSizeException;
11. import javax.crypto.NoSuchPaddingException;
12. import javax.crypto.spec.SecretKeySpec;
13.
14. public class AESTest {
15. private static String psw = "1234656789765432";
16. public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException,
17. NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
18. UnsupportedEncodingException {
19. String str = "你好,黑马!";
20. String encrypte = encrypte(str, psw);
System.out.println("加密后:"+encrypte);
22. String decrypte = decrypte(encrypte, psw);
23. System.out.println("解密后:"+decrypte);
24. }
25.
26. private static String encrypte(String original,String psw) throws NoSuchAlgorithmException,
27. NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
28.
29. Cipher cipher = Cipher.getInstance("AES");
30. Key key = getAESKey(psw);
31. cipher.init(Cipher.ENCRYPT_MODE, key);
32. byte[] doFinal = cipher.doFinal(original.getBytes());
33. return Base64.encode(doFinal);
34. }
35.
36. private static Key getAESKey(String psw) {
37. byte[] buffer = new byte[16];
38. byte[] bytes = psw.getBytes();
39. for(int i=0;i<buffer.length&&i<bytes.length;i++){
40. buffer[i] = bytes[i];
41. }
42. return new SecretKeySpec(buffer, "AES");
43. }
44.
45. private static String decrypte(String original,String psw) throws NoSuchAlgorithmException,
46. NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
47. UnsupportedEncodingException{
48. Cipher cipher = Cipher.getInstance("AES");
49. Key aesKey = getAESKey(psw);
50. cipher.init(Cipher.DECRYPT_MODE, aesKey);
51. byte[] doFinal = cipher.doFinal(Base64.decode(original));
52. return new String(doFinal);
53. }
54. }
~~~