whycxzp
2023-10-24 3c070ab9dbd3042ee55e1e2380ae90b2ff6a1346
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.whyc.util;
 
 
import lombok.extern.slf4j.Slf4j;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
 
@Slf4j
public final class JasyptUtils {
 
    public static void main(String[] args) {
        String a = encrypt("123456");
        decrypt(a);
 
    }
 
    /**
     * 加密使用密钥
     */
    private static final String PRIVATE_KEY = "9Lu6HgEvttjj8vYhy3ID+PqPbumuXhcH";
 
    private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
 
    static {
        basicTextEncryptor.setPassword(PRIVATE_KEY);
    }
 
    /**
     * 私有构造方法,防止被意外实例化
     */
    private JasyptUtils() {
    }
 
    /**
     * 明文加密
     *
     * @param plaintext 明文
     * @return String
     */
    public static String encrypt(String plaintext) {
        log.info("明文字符串为:{}", plaintext);
        // 使用的加密算法参考2.2节内容,也可以在源码的类注释中看到
        String ciphertext = basicTextEncryptor.encrypt(plaintext);
        log.info("密文字符串为:{}", ciphertext);
        return ciphertext;
    }
 
    /**
     * 解密
     *
     * @param ciphertext 密文
     * @return String
     */
    public static String decrypt(String ciphertext) {
        log.info("密文字符串为:{}", ciphertext);
        ciphertext = "ENC(" + ciphertext + ")";
        if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
            String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
            log.info("明文字符串为:{}", plaintext);
            return plaintext;
        }
        log.error("解密失败!");
        return "";
    }
}