常用加密算法

Base64

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.apache.commons.codec.binary.Base64;

public class Base64Utils {

public static void main(String args[]) {
String value = "hello world";

// 加密
String encode = Base64.encodeBase64String(value.getBytes());
System.out.println("encode:" + encode);
// 解密
String decode = new String(Base64.decodeBase64(encode));
System.out.println("decode:" + decode);
}
}

AES

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
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

public static String encrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.ENCRYPT_MODE);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
return Base64.encodeBase64String(encryptedByte);
}

public static String decrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.DECRYPT_MODE);
byte[] decryptedByte = cipher.doFinal(Base64.decodeBase64(data));
return new String(decryptedByte);
}

private static Cipher initCipher(String key, int encryptMode) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(encryptMode, new SecretKeySpec(key.getBytes(), "AES"));
return cipher;
}

public static void main(String[] args) throws Exception {
// 16字节秘钥即128比特
String key = "1234567890123456";
String value = "HelloWorld";

// 16进制的加密参数key
System.out.println("key hex: " + Hex.encodeHexString(key.getBytes()));

// 加密
String encrypt = encrypt(key, value);
System.out.println("encrypt: " + encrypt);
// 解密
String decrypt = decrypt(key, encrypt);
System.out.println("decrypt: " + decrypt);
}

}

DES

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
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class DESUtils {

public static String encrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.ENCRYPT_MODE);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
return Base64.encodeBase64String(encryptedByte);
}

public static String decrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.DECRYPT_MODE);
byte[] decryptedByte = cipher.doFinal(Base64.decodeBase64(data));
return new String(decryptedByte);
}

private static Cipher initCipher(String key, int encryptMode) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(encryptMode, new SecretKeySpec(key.getBytes(), "DES"));
return cipher;
}

public static void main(String[] args) throws Exception {
String key = "12345678";
String value = "HelloWorld";

// 16进制的加密参数key
System.out.println("key hex: " + Hex.encodeHexString(key.getBytes()));

// 加密
String encrypt = encrypt(key, value);
System.out.println("encrypt: " + encrypt);
// 解密
String decrypt = decrypt(key, encrypt);
System.out.println("decrypt: " + decrypt);
}

}

RSA

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
import java.io.*;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;


/**
* RSA非对称加密算法
*
* 生成私钥(格式未转换):openssl genrsa -out pvk0.pem 1024
* 生成公钥:openssl rsa -in pvk0.pem -out puk.pem -pubout
* 私钥格式转换:openssl pkcs8 -topk8 -in pvk0.pem -out pvk.pem -nocrypt
*/
public class RSASignUtil {

private static final String SIGNATURE_INSTANCE = "SHA256WithRSA";
private static final String RSA_INSTANCE = "RSA";
private static final int MAX_ENCRYPT_BLOCK = 245;
private static final int MAX_DECRYPT_BLOCK = 256;

/**
* RSA私钥签名
*
* @param pvkString 秘钥
* @param source 文本
*/
public static String signBySHA256WithRSA(String pvkString, String source) throws Exception {
Signature signature = Signature.getInstance(SIGNATURE_INSTANCE);

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decodeBase64(pvkString.getBytes()));
KeyFactory ky = KeyFactory.getInstance(RSA_INSTANCE);
PrivateKey privateKey = ky.generatePrivate(spec);

signature.initSign(privateKey);
signature.update(source.getBytes());
byte result[] = signature.sign();

return Base64.encodeBase64String(result);
}

/**
* RSA公钥验签
*
* @param pukString 公钥
* @param signValue 签名
* @param source 文本
*/
public static boolean verifySignBySHA256WithRSA(String pukString, String signValue, String source) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(pukString.getBytes()));
KeyFactory ky = KeyFactory.getInstance(RSA_INSTANCE);
PublicKey pukKey = ky.generatePublic(spec);

Signature signature = Signature.getInstance(SIGNATURE_INSTANCE);
signature.initVerify(pukKey);
signature.update(source.getBytes());
// 验证商户签名
return signature.verify(Base64.decodeBase64(signValue.getBytes()));
}

/**
* RSA公钥加密
*
* @param data 文本
* @param publicKey 公钥
*/
public static byte[] encryptByPuk(byte[] data, String publicKey) throws Exception {
byte[] decoded = Base64.decodeBase64(publicKey);
PublicKey pubKey = KeyFactory.getInstance(RSA_INSTANCE).generatePublic(new X509EncodedKeySpec(decoded));
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Cipher cipher = Cipher.getInstance(RSA_INSTANCE);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
int offSet = 0;
while (data.length > offSet) {
int length = data.length - offSet > MAX_ENCRYPT_BLOCK ? MAX_ENCRYPT_BLOCK : data.length - offSet;
byte[] cache = cipher.doFinal(data, offSet, length);
out.write(cache, 0, cache.length);
offSet += length;
}
return out.toByteArray();
}
}

/**
* RSA私钥解密
*
* @param data 文本
* @param privateKey 私钥
*/
public static byte[] decryptByPvk(byte[] data, String privateKey) throws Exception {
byte[] decoded = Base64.decodeBase64(privateKey);
PrivateKey priKey = KeyFactory.getInstance(RSA_INSTANCE).generatePrivate(new PKCS8EncodedKeySpec(decoded));
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Cipher cipher = Cipher.getInstance(RSA_INSTANCE);
cipher.init(Cipher.DECRYPT_MODE, priKey);
int offSet = 0;
while (data.length > offSet) {
int length = data.length - offSet > MAX_DECRYPT_BLOCK ? MAX_DECRYPT_BLOCK : data.length - offSet;
byte[] cache = cipher.doFinal(data, offSet, length);
out.write(cache, 0, cache.length);
offSet += length;
}
return out.toByteArray();
}
}

/**
* 读取公钥
*/
private static String getPemPukkey(String pukPath) {
String pukString = null;
try (InputStream in = new FileInputStream(pukPath)) {
pukString = IOUtils.toString(in);
pukString = pukString.replace("-----BEGIN PUBLIC KEY-----", "");
pukString = pukString.replace("-----END PUBLIC KEY-----", "");
pukString = pukString.replaceAll("\n", "");
} catch (Exception e) {
e.printStackTrace();
}
return pukString;
}

/**
* 读取私钥
*/
private static String getPemPriKey(String pvkPath) {
String pvkString = null;
try (InputStream in = new FileInputStream(pvkPath)) {
pvkString = IOUtils.toString(in);
pvkString = pvkString.replace("-----BEGIN PRIVATE KEY-----", "");
pvkString = pvkString.replace("-----END PRIVATE KEY-----", "");
pvkString = pvkString.replaceAll("\n", "");
} catch (Exception e) {
e.printStackTrace();
}
return pvkString;
}

/**
* 生成RSA公钥私钥
*/
public static Pair<RSAPublicKey, RSAPrivateKey> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_INSTANCE);
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
return new Pair<>(publicKey, privateKey);
}

public static void main(String[] args) throws Exception {
String pukPath = "C:/Users/zm/Desktop/puk.pem";
String publicKey = getPemPukkey(pukPath);

String pvkPath = "C:/Users/zm/Desktop/pvk.pem";
String privateKey = getPemPriKey(pvkPath);

String value = "43554656786889";

// 加密
byte[] encrypt = encryptByPuk(value.getBytes(), publicKey);
System.out.println("encrypt:" + Base64.encodeBase64String(encrypt));
// 解密
byte[] decrypt = decryptByPvk(encrypt, privateKey);
System.out.println("decrypt:" + new String(decrypt));

// 签名
String sign = signBySHA256WithRSA(privateKey, value);
System.out.println("sign:" + sign);
// 验签
boolean isSuccess = verifySignBySHA256WithRSA(publicKey, sign, value);
System.out.println(isSuccess);
}
}

SM2

sm2,sm3,sm4国密算法的纯c语言版本

SM2国密算法SDK包SADK-3.2.1.3.jar

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
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

import cfca.sadk.cgb.toolkit.SM2Toolkit;
import org.apache.commons.io.IOUtils;

/**
* 国密SM2非对称加密算法公钥私钥生成器
*/
public class SM2GenKey {

public static void keyGen(String fileName) throws Exception {
SM2Toolkit tool = new SM2Toolkit();
KeyPair key = tool.SM2GenerateKeyPair();

// 私钥
PrivateKey pvk = key.getPrivate();
byte[] pvkBytes = pvk.getEncoded();
String pvkPath = String.format("cert/%s.pvk", fileName);

// 公钥
PublicKey puk = key.getPublic();
byte[] pukBytes = puk.getEncoded();
String pukPath = String.format("cert/%s.puk", fileName);

File dir = new File("cert");
if (!dir.exists()) {
dir.mkdir();
}

try (FileOutputStream pukOut = new FileOutputStream(pukPath);
FileOutputStream pvkOut = new FileOutputStream(pvkPath)) {
IOUtils.write(pukBytes, pukOut);
IOUtils.write(pvkBytes, pvkOut);
}
}

public static void main(String[] args) throws Exception {
String keyName = "100000";
keyGen(keyName);
}
}
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
import cfca.sadk.algorithm.sm2.SM2PrivateKey;
import cfca.sadk.algorithm.sm2.SM2PublicKey;
import cfca.sadk.cgb.toolkit.BASE64Toolkit;
import cfca.sadk.cgb.toolkit.SM2Toolkit;
import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;

/**
* SM2国密算法
*/
public class SM2Utils {

/**
* 签名
*/
public static String signString(String srcStr, byte[] pvkBytes) throws Exception {
SM2Toolkit sm2Tool = new SM2Toolkit();
SM2PrivateKey sm2PrivateKey = (SM2PrivateKey) sm2Tool.SM2BuildPrivateKey(BASE64Toolkit.encode(pvkBytes));
return BASE64Toolkit.encode(sm2Tool.SM2Sign(sm2PrivateKey, srcStr.getBytes()));
}

/**
* 验签
*/
public static boolean verfySignString(byte[] pukBytes, String signValue, String srcString) throws Exception {
//读取公钥
SM2Toolkit sm2Tool = new SM2Toolkit();
SM2PublicKey sm2MerPublicKey = (SM2PublicKey) sm2Tool.SM2BuildPublicKey(BASE64Toolkit.encode(pukBytes));
//验证签名
return sm2Tool.SM2Verify(sm2MerPublicKey, srcString.getBytes(), BASE64Toolkit.decode(signValue));
}

/**
* 使用公钥加密
*/
public static String encrypt(byte[] pukBytes, String data) throws Exception {
SM2Toolkit sm2Tool = new SM2Toolkit();
SM2PublicKey sm2MerPublicKey = (SM2PublicKey) sm2Tool.SM2BuildPublicKey(BASE64Toolkit.encode(pukBytes));
return BASE64Toolkit.encode(sm2Tool.SM2EncryptData(sm2MerPublicKey, data.getBytes()));
}

/**
* 使用私钥解密
*/
public static String decrypt(byte[] pvkBytes, String data) throws Exception {
SM2Toolkit sm2Tool = new SM2Toolkit();
SM2PrivateKey sm2PrivateKey = (SM2PrivateKey) sm2Tool.SM2BuildPrivateKey(BASE64Toolkit.encode(pvkBytes));
return new String(sm2Tool.SM2DecryptData(sm2PrivateKey, BASE64Toolkit.decode(data)));
}

public static void main(String[] args) throws Exception {
String pvkPath = "C:/Users/zm/Desktop/dppaykey.pvk";
byte[] pvkBytes = IOUtils.toByteArray(new FileInputStream(pvkPath));
String pukPath = "C:/Users/zm/Desktop/dppaykey.puk";
byte[] pukBytes = IOUtils.toByteArray(new FileInputStream(pukPath));

String value = "hello world";

// 加密
String encrypt = encrypt(pukBytes, value);
System.out.println("encrypt:" + encrypt);
// 解密
String decrypt = decrypt(pvkBytes, encrypt);
System.out.println("decrypt:" + decrypt);

// 签名
String sign = SM2Utils.signString(value, pvkBytes);
System.out.println("sign:" + sign);
// 验签
boolean isSuccess = SM2Utils.verfySignString(pukBytes, sign, value);
System.out.println(isSuccess);
}
}

SM4

sm2,sm3,sm4国密算法的纯c语言版本

SM4国密算法SDK包SADK-3.2.1.3.jar

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
import cfca.sadk.cgb.toolkit.BASE64Toolkit;
import cfca.sadk.cgb.toolkit.SM4Toolkit;

/**
* SM4国密算法
*/
public class SM4Utils {

/**
* 使用国密SM4加密字符串
*/
public static String encrypt(String key, String data) throws Exception {
SM4Toolkit toolkit = new SM4Toolkit();
toolkit.SM4Init(key.getBytes(), key.getBytes());
byte[] enByte = toolkit.SM4EncryptData(data.getBytes());
return BASE64Toolkit.encode(enByte);
}

/**
* 使用国密SM4解密字符串
*/
public static String decrypt(String key, String data) throws Exception {
SM4Toolkit toolkit = new SM4Toolkit();
toolkit.SM4Init(key.getBytes(), key.getBytes());
byte[] enByte = toolkit.SM4DecryptData(BASE64Toolkit.decode(data));
return new String(enByte);
}

public static void main(String[] args) throws Exception {
String key = "1234567890123456";
String value = "hello world";

// 加密
String encrypt = encrypt(key, value);
System.out.println("encrypt:" + encrypt);
// 解密
String decrypt = decrypt(key, encrypt);
System.out.println("decrypt:" + decrypt);
}
}
>