java代码:

 1 public class AESCoder {
 2     private static String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
 3     private static String KEY_ALGORITHM = "AES";
 4 
 5     public static String decrypt(String sSrc, String sKey) throws Exception {
 6         SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes("ASCII"), KEY_ALGORITHM);
 7         Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
 8         cipher.init(2, skeySpec);
 9         byte[] encrypted1 = hex2byte(sSrc);
10         byte[] original = cipher.doFinal(encrypted1);
11         return new String(original);
12     }
13 
14     public static String encrypt(String sSrc, String sKey) throws Exception {
15         SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes("ASCII"), KEY_ALGORITHM);
16         Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
17         cipher.init(1, skeySpec);
18         byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
19         return byte2hex(encrypted);
20     }
21 
22     private static byte[] hex2byte(String strhex) {
23         if (strhex == null)
24             return null;
25 
26         int l = strhex.length();
27         if (l % 2 == 1)
28             return null;
29 
30         byte[] b = new byte[l / 2];
31         for (int i = 0; i != l / 2; ++i)
32             b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
33 
34         return b;
35     }
36 
37     private static String byte2hex(byte[] b) {
38         String hs = "";
39         String stmp = "";
40         for (int n = 0; n < b.length; ++n) {
41             stmp = Integer.toHexString(b[n] & 0xFF);
42             if (stmp.length() == 1)
43                 hs = hs + "0" + stmp;
44             else
45                 hs = hs + stmp;
46         }
47 
48         return hs.toUpperCase();
49     }
View Code

相关文章: