基于BC库的国密算法 SM2算法工具

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.engines.SM2Engine.Mode;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.custom.gm.SM2P256V1Curve;
 
import java.math.BigInteger;
import java.security.SecureRandom;
 
 
/**
 * SM2算法工具
 *
 */
public final class SM2Utils
{
    /**
     * Begin: SM2推荐曲线参数
     */
    private static final String SM2_ECC_GY_VAL = "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0";
    private static final String SM2_ECC_GX_VAL = "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7";
 
    private static final SM2P256V1Curve CURVE = new SM2P256V1Curve();
    private final static BigInteger SM2_ECC_N = CURVE.getOrder();
    private final static BigInteger SM2_ECC_H = CURVE.getCofactor();
 
    private final static BigInteger SM2_ECC_GX = new BigInteger(SM2_ECC_GX_VAL, 16);
    private final static BigInteger SM2_ECC_GY = new BigInteger(SM2_ECC_GY_VAL, 16);
 
    private static final ECPoint G_POINT = CURVE.createPoint(SM2_ECC_GX, SM2_ECC_GY);
    private static final ECDomainParameters DOMAIN_PARAMS = new ECDomainParameters(CURVE, G_POINT, SM2_ECC_N, SM2_ECC_H);
    /**
     * End: SM2推荐曲线参数
     */
 
    private SM2Utils()
    {
    }
 
    /**
     * 生成ECC密钥对
     *
     * @return ECC密钥对
     */
    public static AsymmetricCipherKeyPair generateKeyPairParameter()
    {
        final SecureRandom random = new SecureRandom();
        return BCECUtils.generateKeyPairParameter(DOMAIN_PARAMS, random);
    }
 
    /**
     * @param pubKey
     *                   公钥
     * @param srcData
     *                   原文
     * @return 默认输出C1C3C2顺序的密文。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @throws InvalidCipherTextException
     */
    public static byte[] encrypt(final BCECPublicKey pubKey, final byte[] srcData) throws InvalidCipherTextException
    {
        return encrypt(Mode.C1C3C2, pubKey, srcData);
    }
 
    /**
     * @param pubKeyParams
     *                        公钥
     * @param srcData
     *                        原文
     * @return 默认输出C1C3C2顺序的密文。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @throws InvalidCipherTextException
     */
    public static byte[] encrypt(final ECPublicKeyParameters pubKeyParams, final byte[] srcData) throws InvalidCipherTextException
    {
        return encrypt(Mode.C1C3C2, pubKeyParams, srcData);
    }
 
    /**
     * @param priKey
     *                     私钥
     * @param sm2Cipher
     *                     默认输入C1C3C2顺序的密文。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @return 原文。SM2解密返回了数据则一定是原文,因为SM2自带校验,如果密文被篡改或者密钥对不上,都是会直接报异常的。
     * @throws InvalidCipherTextException
     */
    public static byte[] decrypt(final BCECPrivateKey priKey, final byte[] sm2Cipher) throws InvalidCipherTextException
    {
        return decrypt(Mode.C1C3C2, priKey, sm2Cipher);
    }
 
    /**
     * @param priKeyParams
     *                        私钥
     * @param sm2Cipher
     *                        默认输入C1C3C2顺序的密文。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @return 原文。SM2解密返回了数据则一定是原文,因为SM2自带校验,如果密文被篡改或者密钥对不上,都是会直接报异常的。
     * @throws InvalidCipherTextException
     */
    public static byte[] decrypt(final ECPrivateKeyParameters priKeyParams, final byte[] sm2Cipher)
            throws InvalidCipherTextException
    {
        return decrypt(Mode.C1C3C2, priKeyParams, sm2Cipher);
    }
 
    /**
     * 签名
     *
     * @param priKey
     *                   私钥
     * @param srcData
     *                   原文
     * @return DER编码后的签名值
     * @throws CryptoException
     */
    public static byte[] sign(BCECPrivateKey priKey, byte[] srcData) throws CryptoException
    {
        return sign(priKey, null, srcData);
    }
 
    /**
     * 签名,默认withId为字节数组:"1234567812345678".getBytes()
     *
     * @param priKeyParams
     *                        私钥
     * @param srcData
     *                        原文
     * @return DER编码后的签名值
     * @throws CryptoException
     */
    public static byte[] sign(final ECPrivateKeyParameters priKeyParams, final byte[] srcData) throws CryptoException
    {
        return sign(priKeyParams, null, srcData);
    }
 
    /**
     * 验签
     *
     * @param pubKey
     *                   公钥
     * @param srcData
     *                   原文
     * @param sign
     *                   DER编码的签名值
     * @return boolean
     */
    public static boolean verify(final BCECPublicKey pubKey, final byte[] srcData, final byte[] sign)
    {
        return verify(pubKey, null, srcData, sign);
    }
 
    /**
     * 验签 不指定withId,则默认withId为字节数组:"1234567812345678".getBytes()
     *
     * @param pubKeyParams
     *                        公钥
     * @param srcData
     *                        原文
     * @param sign
     *                        DER编码的签名值
     * @return 验签成功返回true,失败返回false
     */
    public static boolean verify(final ECPublicKeyParameters pubKeyParams, final byte[] srcData, final byte[] sign)
    {
        return verify(pubKeyParams, null, srcData, sign);
    }
 
    /**
     * @param mode
     *                   指定密文结构,新的[《SM2密码算法使用规范》 GM/T 0009-2012]标准为C1C3C2
     * @param pubKey
     *                   公钥
     * @param srcData
     *                   原文
     * @return 根据mode不同,输出的密文C1C2C3排列顺序不同。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @throws InvalidCipherTextException
     */
    private static byte[] encrypt(final Mode mode, final BCECPublicKey pubKey, final byte[] srcData)
            throws InvalidCipherTextException
    {
        final ECPublicKeyParameters pubKeyParams = BCECUtils.convertPublicKeyToParameters(pubKey);
        return encrypt(mode, pubKeyParams, srcData);
    }
 
    /**
     * @param mode
     *                        指定密文结构,新的[《SM2密码算法使用规范》 GM/T 0009-2012]标准为C1C3C2
     * @param pubKeyParams
     *                        公钥
     * @param srcData
     *                        原文
     * @return 根据mode不同,输出的密文C1C2C3排列顺序不同。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @throws InvalidCipherTextException
     */
    private static byte[] encrypt(final Mode mode, final ECPublicKeyParameters pubKeyParams, final byte[] srcData)
            throws InvalidCipherTextException
    {
        final SM2Engine engine = new SM2Engine(mode);
        final ParametersWithRandom pwr = new ParametersWithRandom(pubKeyParams, new SecureRandom());
        engine.init(true, pwr);
        return engine.processBlock(srcData, 0, srcData.length);
    }
 
    /**
     * 验签
     *
     * @param pubKey
     *                   公钥
     * @param withId
     *                   可以为null,若为null,则默认withId为字节数组:"1234567812345678".getBytes()
     * @param srcData
     *                   原文
     * @param sign
     *                   DER编码的签名值
     * @return boolean
     */
    private static boolean verify(final BCECPublicKey pubKey, final byte[] withId, final byte[] srcData, final byte[] sign)
    {
        final ECPublicKeyParameters pubKeyParams = BCECUtils.convertPublicKeyToParameters(pubKey);
        return verify(pubKeyParams, withId, srcData, sign);
    }
 
    /**
     * @param mode
     *                     指定密文结构,新的[《SM2密码算法使用规范》 GM/T 0009-2012]标准为C1C3C2
     * @param priKey
     *                     私钥
     * @param sm2Cipher
     *                     根据mode不同,需要输入的密文C1C2C3排列顺序不同。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @return 原文。SM2解密返回了数据则一定是原文,因为SM2自带校验,如果密文被篡改或者密钥对不上,都是会直接报异常的。
     * @throws InvalidCipherTextException
     */
    private static byte[] decrypt(final Mode mode, final BCECPrivateKey priKey, final byte[] sm2Cipher)
            throws InvalidCipherTextException
    {
        final ECPrivateKeyParameters priKeyParams = BCECUtils.convertPrivateKeyToParameters(priKey);
        return decrypt(mode, priKeyParams, sm2Cipher);
    }
 
    /**
     * @param mode
     *                        指定密文结构,新的[《SM2密码算法使用规范》 GM/T 0009-2012]标准为C1C3C2
     * @param priKeyParams
     *                        私钥
     * @param sm2Cipher
     *                        根据mode不同,需要输入的密文C1C2C3排列顺序不同。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
     * @return 原文。SM2解密返回了数据则一定是原文,因为SM2自带校验,如果密文被篡改或者密钥对不上,都是会直接报异常的。
     * @throws InvalidCipherTextException
     */
    private static byte[] decrypt(final Mode mode, final ECPrivateKeyParameters priKeyParams, final byte[] sm2Cipher)
            throws InvalidCipherTextException
    {
        final SM2Engine engine = new SM2Engine(mode);
        engine.init(false, priKeyParams);
        return engine.processBlock(sm2Cipher, 0, sm2Cipher.length);
    }
 
    /**
     * 私钥签名
     *
     * @param priKey
     *                   私钥
     * @param withId
     *                   可以为null,若为null,则默认withId为字节数组:"1234567812345678".getBytes()
     * @param srcData
     *                   原文
     * @return DER编码后的签名值
     * @throws CryptoException
     */
    private static byte[] sign(final BCECPrivateKey priKey, final byte[] withId, final byte[] srcData) throws CryptoException
    {
        final ECPrivateKeyParameters priKeyParams = BCECUtils.convertPrivateKeyToParameters(priKey);
        return sign(priKeyParams, withId, srcData);
    }
 
    /**
     * 签名
     *
     * @param priKeyParams
     *                        私钥
     * @param withId
     *                        可以为null,若为null,则默认withId为字节数组:"1234567812345678".getBytes()
     * @param srcData
     *                        源数据
     * @return DER编码后的签名值
     * @throws CryptoException
     */
    private static byte[] sign(final ECPrivateKeyParameters priKeyParams, final byte[] withId, final byte[] srcData)
            throws CryptoException
    {
        SM2Signer signer = new SM2Signer();
        CipherParameters param = null;
        ParametersWithRandom pwr = new ParametersWithRandom(priKeyParams, new SecureRandom());
        if (withId != null)
        {
            param = new ParametersWithID(pwr, withId);
        }
        else
        {
            param = pwr;
        }
        signer.init(true, param);
        signer.update(srcData, 0, srcData.length);
        return signer.generateSignature();
    }
 
    /**
     * 验签
     *
     * @param pubKeyParams
     *                        公钥
     * @param withId
     *                        可以为null,若为null,则默认withId为字节数组:"1234567812345678".getBytes()
     * @param srcData
     *                        原文
     * @param sign
     *                        DER编码的签名值
     * @return 验签成功返回true,失败返回false
     */
    private static boolean verify(final ECPublicKeyParameters pubKeyParams, final byte[] withId, final byte[] srcData,
            final byte[] sign)
    {
        final SM2Signer signer = new SM2Signer();
        CipherParameters param;
        if (withId != null)
        {
            param = new ParametersWithID(pubKeyParams, withId);
        }
        else
        {
            param = pubKeyParams;
        }
        signer.init(false, param);
        signer.update(srcData, 0, srcData.length);
        return signer.verifySignature(sign);
    }
}

  

posted @   小小菜包子  阅读(594)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示