AES java加密与MySql加密算法一致
  tDpTloHDC5uy 2023年12月12日 27 0

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 %¥#@上海市浦东新区陆家嘴东方明珠-/。,

 



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: golang之媒体处理 下一篇: RSA分段加密方案
  1. 分享:
最后一次编辑于 2023年12月12日 0

暂无评论

推荐阅读
tDpTloHDC5uy