1.背景
数据库加密与java程序加密算法保持一致,统一采用AES加密算法。
2. java 代码加密
1 package com.pacific.permission.test;
2
3 import javax.crypto.Cipher;
4 import javax.crypto.spec.SecretKeySpec;
5 import java.util.Base64;
6
7 /**
8 * @author luzhiming
9 * @desc AES 加解密工具类
10 */
11 public class SymmetricEncryptionExample {
12
13 /**
14 * 加密算法
15 */
16 private static final String ALGORITHM = "AES";
17
18 /**
19 * 加密密钥
20 */
21 private static final String KEY = "v2uU!Sd3XT5LeVU$";
22
23
24 /**
25 * 加密
26 *
27 * @param plaintext
28 * @return
29 * @throws Exception
30 */
31 public static String encrypt(String plaintext) throws Exception {
32 SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
33 Cipher cipher = Cipher.getInstance(ALGORITHM);
34 cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
35 byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
36 return Base64.getEncoder().encodeToString(encryptedBytes);
37 }
38
39 /**
40 * 解密
41 *
42 * @param ciphertext
43 * @return
44 * @throws Exception
45 */
46 public static String decrypt(String ciphertext) throws Exception {
47 SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
48 Cipher cipher = Cipher.getInstance(ALGORITHM);
49 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
50 byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
51 return new String(decryptedBytes);
52 }
53
54 public static void main(String[] args) throws Exception {
55 String plaintext = "%¥#@上海市浦东新区陆家嘴东方明珠-/。,";
56 String ciphertext = encrypt(plaintext);
57 System.out.println("Ciphertext: " + ciphertext);
58 String decryptedText = decrypt(ciphertext);
59 System.out.println("Decrypted Text: " + decryptedText);
60 }
61 }
程序运行结果:
### 加密结果
Ciphertext: 6SrQkpMGYRMtYIYahyAOGi0lzAWUnXTFJ8q74PHzR0eJbmEGCs5ZVBA+QfW2md3q1CgyIckKqzMKxGNepPtd9g==
### 解密结果
Decrypted Text: %¥#@上海市浦东新区陆家嘴东方明珠-/。,
3.数据库加密
数据库加密语法如下
SELECT to_base64(aes_encrypt('%¥#@上海市浦东新区陆家嘴东方明珠-/。,','v2uU!Sd3XT5LeVU$'));
数据库加密结果:
6SrQkpMGYRMtYIYahyAOGi0lzAWUnXTFJ8q74PHzR0eJbmEGCs5ZVBA+QfW2md3q1CgyIckKqzMKxGNepPtd9g==
数据库解密语法如下:
SELECT AES_DECRYPT(from_base64('6SrQkpMGYRMtYIYahyAOGi0lzAWUnXTFJ8q74PHzR0eJbmEGCs5ZVBA+QfW2md3q1CgyIckKqzMKxGNepPtd9g=='),'v2uU!Sd3XT5LeVU$');
数据库解密结果:
1 %¥#@上海市浦东新区陆家嘴东方明珠-/。,