· 9 years ago · Oct 12, 2016, 11:32 PM
1public class AesEncryptDecrypt {
2
3 //åŠ å¯†æ–¹æ³•
4 public static byte[] Encrypt(SecretKey secretKey, String msg)
5 throws Exception {
6 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // : ç‰åŒ AES/ECB/PKCS5Padding
7 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec("1234567890654321".getBytes()));//ivçš„å€¼åœ¨è§£å¯†æ™‚å¿…é ˆè·ŸåŠ å¯†æ™‚ä½¿ç”¨çš„ä¸€æ¨£ï¼Œå¦å‰‡ç„¡æ³•解密。
8 byte[] byteCipherText = cipher.doFinal(msg.getBytes("UTF-8"));
9
10 return byteCipherText;
11 }
12 //解密方法
13 public static byte[] Decrypt(SecretKey secretKey, byte[] cipherText)
14 throws Exception {
15 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
16 cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec("1234567890654321".getBytes())); //ivçš„å€¼åœ¨è§£å¯†æ™‚å¿…é ˆè·ŸåŠ å¯†æ™‚ä½¿ç”¨çš„ä¸€æ¨£ï¼Œå¦å‰‡ç„¡æ³•解密。
17 byte[] decryptedText = cipher.doFinal(cipherText);
18 //String strDecryptedText = new String(decryptedText);
19 //System.out.println("è§£å¯†çµæžœï¼š" + strDecryptedText);
20 return decryptedText;
21 }
22
23 //將資料庫內的金鑰轉æ›ç‚ºSecretKeyï¼Œé‡‘é‘°é ˆç‚º16bytes,å¯è‹±æ•¸æ··åˆã€‚
24 public static SecretKey stringToKey(String secretKeyString)
25 throws Exception {
26 byte[] encodedKey = secretKeyString.getBytes("UTF-8");
27 SecretKey secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
28 return secretKey;
29 }
30
31 //å°‡SecretKey轉æ›ç‚ºé‡‘é‘°å—ä¸²ï¼Œé‡‘é‘°é ˆç‚º16bytes,å¯è‹±æ•¸æ··åˆã€‚
32 public static String keyToString(SecretKey secretKey)
33 throws Exception {
34 String stringKey = new Base64().encodeToString(secretKey.getEncoded());
35 return stringKey;
36 }
37
38}