---
title: "<转载>实现android的AES加密技术"
author: "hecal"
date: "2012-01-06T17:29:00Z"
tags: []
categories: ["移动开发"]
slug: "android-aes"
draft: false
lastmod: "2012-01-06T17:29:00Z"
id: 1336924
url: "https://hecal.iteye.com/blog/1336924"
---

**原文地址：**[实现android的AES加密技术](http://blog.sina.com.cn/s/blog_59f3b7970100fra2.html "实现android的AES加密技术")**作者：**[大牛](http://blog.sina.com.cn/u/1509144471 "大牛")

密码学中的高级加密标准（Advanced Encryption Standard，AES），又称Rijndael加密法，是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES，已经被多方分析且广为全世界所使用。经过五年的甄选流程，高级加密标准由美国国家标准与技术研究院（NIST）于2001年11月26日发布于FIPS PUB 197，并在2002年5月26日成为有效的标准。2006年，高级加密标准已然成为对称密钥加密中最流行的算法之一。该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计，结合两位[](http://photo.blog.sina.com.cn/showpic.html#blogid=616303e60100uryj&url=http://s16.sinaimg.cn/orignal/59f3b797x7603aa949aef&690)作者的名字，以Rijdael之命名之，投稿高级加密标准的甄选流程（Rijdael的发音近于 “Rhine doll”）。

AES 加密过程是在一个4×4的字节矩阵上运作，这个矩阵又称为“体（state）”，其初值就是一个明文区块（矩阵中一个元素大小就是明文区块中的一个 Byte）。（Rijndael加密法因支援更大的区块，其矩阵行数可视情况增加）加密时，各轮AES加密循环（除最后一轮外）均包含4个步骤：

1\. **AddRoundKey** — 矩阵中的每一个字节都与该次循环的子密钥（round key）做XOR运算；每个子密钥由密钥生成方案产生。  
2\. **SubBytes** — 透过一个非线性的替换函数，用查找表的方式把每个字节替换成对应的字节。  
3\. **ShiftRows** — 将矩阵中的每个横列进行循环式移位。  
4\. **MixColumns** — 为了充分混合矩阵中各个直行的操作。这个步骤使用线性转换来混合每行内的四个字节。

最后一个加密循环中省略MixColumns步骤，而以另一个AddRoundKey取代。

[![\[转载\]实现android的AES加密技术](http://s1.sinaimg.cn/bmiddle/59f3b797x7603acfa2870&690 "[转载]实现android的AES加密技术")](http://photo.blog.sina.com.cn/showpic.html#blogid=616303e60100uryj&url=http://s1.sinaimg.cn/orignal/59f3b797x7603acfa2870&690)

java类文件：

01. **import** java.security.SecureRandom;
02. **import** javax.crypto.Cipher;
03. **import** javax.crypto.KeyGenerator;
04. **import** javax.crypto.SecretKey;
05. **import** javax.crypto.spec.SecretKeySpec;
06. **public** **class** SimpleCrypto {
07. **public** **static** String encrypt(String seed, String cleartext) **throws** Exception {
08. **byte**\[] rawKey = getRawKey(seed.getBytes());
09. **byte**\[] result = encrypt(rawKey, cleartext.getBytes());
10. **return** toHex(result);
11. }
12. **public** **static** String decrypt(String seed, String encrypted) **throws** Exception {
13. **byte**\[] rawKey = getRawKey(seed.getBytes());
14. **byte**\[] enc = toByte(encrypted);
15. **byte**\[] result = decrypt(rawKey, enc);
16. **return** **new** String(result);
17. }
18. **private** **static** **byte**\[] getRawKey(**byte**\[] seed) **throws** Exception {
19. KeyGenerator kgen = KeyGenerator.getInstance("AES");
20. SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
21. sr.setSeed(seed);
22. kgen.init(128, sr); // 192 and 256 bits may not be available
23. SecretKey skey = kgen.generateKey();
24. **byte**\[] raw = skey.getEncoded();
25. **return** raw;
26. }
27. **private** **static** **byte**\[] encrypt(**byte**\[] raw, **byte**\[] clear) **throws** Exception {
28. SecretKeySpec skeySpec = **new** SecretKeySpec(raw, "AES");
29. Cipher cipher = Cipher.getInstance("AES");
30. cipher.init(Cipher.ENCRYPT\_MODE, skeySpec);
31. **byte**\[] encrypted = cipher.doFinal(clear);
32. **return** encrypted;
33. }
34. **private** **static** **byte**\[] decrypt(**byte**\[] raw, **byte**\[] encrypted) **throws** Exception {
35. SecretKeySpec skeySpec = **new** SecretKeySpec(raw, "AES");
36. Cipher cipher = Cipher.getInstance("AES");
37. cipher.init(Cipher.DECRYPT\_MODE, skeySpec);
38. **byte**\[] decrypted = cipher.doFinal(encrypted);
39. **return** decrypted;
40. }
41. **public** **static** String toHex(String txt) {
42. **return** toHex(txt.getBytes());
43. }
44. **public** **static** String fromHex(String hex) {
45. **return** **new** String(toByte(hex));
46. }
47. **public** **static** **byte**\[] toByte(String hexString) {
48. **int** len = hexString.length()/2;
49. **byte**\[] result = **new** **byte**\[len];
50. **for** (**int** i = 0; i &lt; len; i++)
51. result\[i] = Integer.valueOf(hexString.substring(2\*i, 2\*i+2), 16).bytue();
52. **return** result;
53. }
54. **public** **static** String toHex(**byte**\[] buf) {
55. **if** (buf == **null**)
56. **return** "";
57. StringBuffer result = **new** StringBuffer(2\*buf.length);
58. **for** (**int** i = 0; i &lt; buf.length; i++) {
59. appendHex(result, buf\[i]);
60. }
61. **return** result.toString();
62. }
63. **private** **final** **static** String HEX = "0123456789ABCDEF";
64. **private** **static** **void** appendHex(StringBuffer sb, **byte** b) {
65. sb.append(HEX.charAt((b&gt;&gt;4)&0x0f)).append(HEX.charAt(b&0x0f));
66. }
67. }

 加密：`String encryptingCode = SimpleCrypto.encrypt(masterPassword,originalText);`

`解密：String originalText = SimpleCrypto.decrypt(masterpassword, encryptingCode);`