提交 | 用户 | 时间
|
722af2
|
1 |
package com.dl.common.encrypt.encryptor; |
X |
2 |
|
|
3 |
import cn.hutool.core.util.StrUtil; |
|
4 |
import cn.hutool.crypto.SmUtil; |
|
5 |
import cn.hutool.crypto.symmetric.SM4; |
|
6 |
import com.dl.common.encrypt.EncryptContext; |
|
7 |
import com.dl.common.enums.AlgorithmType; |
|
8 |
import com.dl.common.enums.EncodeType; |
|
9 |
|
|
10 |
import java.nio.charset.StandardCharsets; |
|
11 |
|
|
12 |
/** |
|
13 |
* sm4算法实现 |
|
14 |
* |
|
15 |
* @author 老马 |
|
16 |
* @version 4.6.0 |
|
17 |
*/ |
|
18 |
public class Sm4Encryptor extends AbstractEncryptor { |
|
19 |
|
|
20 |
private final SM4 sm4; |
|
21 |
|
|
22 |
public Sm4Encryptor(EncryptContext context) { |
|
23 |
super(context); |
|
24 |
String password = context.getPassword(); |
|
25 |
if (StrUtil.isBlank(password)) { |
|
26 |
throw new IllegalArgumentException("SM4没有获得秘钥信息"); |
|
27 |
} |
|
28 |
// sm4算法的秘钥要求是16位长度 |
|
29 |
if (16 != password.length()) { |
|
30 |
throw new IllegalArgumentException("SM4秘钥长度应该为16位,实际为" + password.length() + "位"); |
|
31 |
} |
|
32 |
this.sm4 = SmUtil.sm4(password.getBytes(StandardCharsets.UTF_8)); |
|
33 |
} |
|
34 |
|
|
35 |
/** |
|
36 |
* 获得当前算法 |
|
37 |
*/ |
|
38 |
@Override |
|
39 |
public AlgorithmType algorithm() { |
|
40 |
return AlgorithmType.SM4; |
|
41 |
} |
|
42 |
|
|
43 |
/** |
|
44 |
* 加密 |
|
45 |
* |
|
46 |
* @param value 待加密字符串 |
|
47 |
* @param encodeType 加密后的编码格式 |
|
48 |
*/ |
|
49 |
@Override |
|
50 |
public String encrypt(String value, EncodeType encodeType) { |
|
51 |
if (encodeType == EncodeType.HEX) { |
|
52 |
return sm4.encryptHex(value); |
|
53 |
} else { |
|
54 |
return sm4.encryptBase64(value); |
|
55 |
} |
|
56 |
} |
|
57 |
|
|
58 |
/** |
|
59 |
* 解密 |
|
60 |
* |
|
61 |
* @param value 待加密字符串 |
|
62 |
*/ |
|
63 |
@Override |
|
64 |
public String decrypt(String value) { |
|
65 |
return this.sm4.decryptStr(value); |
|
66 |
} |
|
67 |
} |