ab
2024-11-05 bead00668eebce8d39d027515d564376de2f5978
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
package com.nova.sankuai.domain.api.weiyaquanyi;
 
import cn.hutool.core.codec.Base64;
import com.nova.sankuai.infra.config.CommonException;
import lombok.extern.slf4j.Slf4j;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
 
@Slf4j
public final class WeiYaKeyUtil {
 
    // ("数据加密 plainTextData要加密的字符串")
    public static String encryptAES(String plainTextData, String key) {
        try {
            // 加密数据
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
            byte[] encryptedData = cipher.doFinal(plainTextData.getBytes(StandardCharsets.UTF_8));
            // return Base64.encode(encryptedData);
            return URLEncoder.encode(Base64.encode(encryptedData), "UTF-8");
        } catch (Exception e) {
            log.error("纬雅权益 - 加密失败! data={}, error={}", plainTextData, e.getMessage());
            throw new CommonException("纬雅权益 - 加密失败! ", e);
        }
    }
 
    // ("数据解密 encryptedData要解密的字符串")
    public static String decryptAES(String encryptedData, String key) {
        try {
            // 解密数据
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
            byte[] decryptedData = cipher.doFinal(encryptedData.getBytes(StandardCharsets.UTF_8));
 
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("纬雅权益 - 解密失败! data={}, error={}", encryptedData, e.getMessage());
            throw new CommonException("纬雅权益 - 解密失败! ", e);
        }
    }
}