7 changed files with 179 additions and 25 deletions
@ -0,0 +1,69 @@ |
|||
package org.dromara.common.encrypt.utils; |
|||
|
|||
import org.bouncycastle.crypto.engines.SM4Engine; |
|||
import org.bouncycastle.crypto.params.KeyParameter; |
|||
import org.bouncycastle.util.encoders.Hex; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.security.SecureRandom; |
|||
|
|||
public class SM4Util { |
|||
|
|||
private static final int BLOCK_SIZE = 16; // 块大小
|
|||
|
|||
// 随机生成 SM4 密钥
|
|||
public static String generateKey() { |
|||
byte[] key = new byte[BLOCK_SIZE]; |
|||
new SecureRandom().nextBytes(key); |
|||
return Hex.toHexString(key); |
|||
} |
|||
|
|||
// 加密
|
|||
public static String encrypt(String plainText, String hexKey) throws Exception { |
|||
byte[] input = plainText.getBytes(StandardCharsets.UTF_8); |
|||
byte[] keyBytes = Hex.decode(hexKey); |
|||
// 计算填充长度
|
|||
int paddingLength = BLOCK_SIZE - (input.length % BLOCK_SIZE); |
|||
byte[] paddedInput = new byte[input.length + paddingLength]; |
|||
|
|||
// 复制原始数据
|
|||
System.arraycopy(input, 0, paddedInput, 0, input.length); |
|||
// PKCS7填充
|
|||
for (int i = input.length; i < paddedInput.length; i++) { |
|||
paddedInput[i] = (byte) paddingLength; |
|||
} |
|||
|
|||
SM4Engine sm4 = new SM4Engine(); |
|||
sm4.init(true, new KeyParameter(keyBytes)); |
|||
|
|||
byte[] encrypted = new byte[paddedInput.length]; |
|||
for (int i = 0; i < paddedInput.length; i += BLOCK_SIZE) { |
|||
sm4.processBlock(paddedInput, i, encrypted, i); |
|||
} |
|||
// SM4Engine sm4 = new SM4Engine();
|
|||
// sm4.init(true, new KeyParameter(keyBytes)); // 加密模式
|
|||
//
|
|||
// byte[] encrypted = new byte[input.length];
|
|||
// for (int i = 0; i < input.length; i += BLOCK_SIZE) {
|
|||
// sm4.processBlock(input, i, encrypted, i);
|
|||
// }
|
|||
|
|||
return Hex.toHexString(encrypted); |
|||
} |
|||
|
|||
// 解密
|
|||
public static String decrypt(String cipherText, String hexKey) throws Exception { |
|||
byte[] keyBytes = Hex.decode(hexKey); |
|||
byte[] encrypted = Hex.decode(cipherText); |
|||
|
|||
SM4Engine sm4 = new SM4Engine(); |
|||
sm4.init(false, new KeyParameter(keyBytes)); // 解密模式
|
|||
|
|||
byte[] decrypted = new byte[encrypted.length]; |
|||
for (int i = 0; i < encrypted.length; i += BLOCK_SIZE) { |
|||
sm4.processBlock(encrypted, i, decrypted, i); |
|||
} |
|||
|
|||
return new String(decrypted, StandardCharsets.UTF_8).trim(); |
|||
} |
|||
} |
Loading…
Reference in new issue