0
点赞
收藏
分享

微信扫一扫

AES加密实例

Python百事通 2023-04-30 阅读 33

1. public class AES {  
2.      
3.    private static final String AES = "AES";  
4.  
5.  密钥长度要是16位的
6.    private static final String CRYPT_KEY = "YUUAtestYUUAtest";  
7.  
8.      
9.    public static byte[] encrypt(byte[] src, String key) throws Exception {  
10.        Cipher cipher = Cipher.getInstance(AES);  
11.        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);  
12.        cipher.init(Cipher.ENCRYPT_MODE, securekey);//设置密钥和加密形式  
13.        return cipher.doFinal(src);  
14.    }  
15.  
16.      
17.    public static byte[] decrypt(byte[] src, String key)  throws Exception  {  
18.        Cipher cipher = Cipher.getInstance(AES);  
19.        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);//设置加密Key  
20.        cipher.init(Cipher.DECRYPT_MODE, securekey);//设置密钥和解密形式  
21.        return cipher.doFinal(src);  
22.    }  
23.      
24.      
25.    public static String byte2hex(byte[] b) {  
26.        String hs = "";  
27.        String stmp = "";  
28.        for (int n = 0; n < b.length; n++) {  
29.            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
30.            if (stmp.length() == 1)  
31.                hs = hs + "0" + stmp;  
32.            else  
33.                hs = hs + stmp;  
34.        }  
35.        return hs.toUpperCase();  
36.    }  
37.  
38.    public static byte[] hex2byte(byte[] b) {  
39.        if ((b.length % 2) != 0)  
40.            throw new IllegalArgumentException("长度不是偶数");  
41.        byte[] b2 = new byte[b.length / 2];  
42.        for (int n = 0; n < b.length; n += 2) {  
43.            String item = new String(b, n, 2);  
44.            b2[n / 2] = (byte) Integer.parseInt(item, 16);  
45.        }  
46.        return b2;  
47.    }  
48.      
49.      
50.    public final static String decrypt(String data) {  
51.        try {  
52.            return new String(decrypt(hex2byte(data.getBytes()),  
53.                    CRYPT_KEY));  
54.        } catch (Exception e) {  
55.        }  
56.        return null;  
57.    }  
58.  
59.      
60.    public final static String encrypt(String data) {  
61.        try {  
62.            return byte2hex(encrypt(data.getBytes(), CRYPT_KEY));  
63.        } catch (Exception e) {  
64.        }  
65.        return null;  
66.    }  
67.      
68.  
69.    public static void main(String[] args) {  
70.        String ID = "611111";  
71.          
72.        String idEncrypt = encrypt(ID);  
73.        System.out.println(idEncrypt);  
74.        String idDecrypt = decrypt(idEncrypt);  
75.        System.out.println(idDecrypt);  
76.    }  
77.      
78. }

举报

相关推荐

0 条评论