非对称加解密

This commit is contained in:
liulu
2024-12-20 15:03:22 +08:00
parent 0ba56c7c25
commit 7fe6482983
23 changed files with 609 additions and 33 deletions
@@ -22,6 +22,7 @@ import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.function.Function;
/**
@@ -101,7 +102,10 @@ public class LoadBalancedSdfApiService implements SdfApiService {
@Override
public EccSignature externalSignECC(byte[] privateKey, byte[] pucData) {
return externalSignWithIdECC(privateKey, pucData, new byte[0]);
Assert.notNull(pucData, "待签名数据不能为空");
Assert.isTrue(pucData.length == 32, "待签名数据长度必须为32字节");
EccPriKey priKey = EccPriKey.fromBytes(privateKey);
return apply(s -> s.getSdfApiAdapter().externalSignECC(s.getSessionHandle(), priKey, pucData));
}
@Override
@@ -136,7 +140,11 @@ public class LoadBalancedSdfApiService implements SdfApiService {
@Override
public boolean externalVerifyECC(byte[] publicKey, byte[] pubData, byte[] signData) {
return externalVerifyWithIdECC(publicKey, pubData, signData, new byte[0]);
Assert.notNull(pubData, "验签原文数据不能为空");
Assert.isTrue(pubData.length == 32, "验签原文数据长度必须为32字节");
EccPubKey eccPublicKey = EccPubKey.fromBytes(publicKey);
EccSignature eccSignature = EccSignature.fromBytes(signData);
return apply(s -> s.getSdfApiAdapter().externalVerifyECC(s.getSessionHandle(), eccPublicKey, pubData, eccSignature));
}
@Override
@@ -169,10 +177,12 @@ public class LoadBalancedSdfApiService implements SdfApiService {
}
@Override
public byte[] hash(byte[] pucData) {
public byte[] hash(byte[] pucData, byte[] pubKey, byte[] userId) {
EccPubKey eccPubKey = pubKey == null || pubKey.length == 0 ? null : EccPubKey.fromBytes(pubKey);
byte[] finalUserId = Objects.nonNull(pubKey) && Objects.isNull(userId) ? CryptoConst.USER_ID : userId;
return apply(s -> {
String newSession = s.getSdfApiAdapter().openSession(s.getDeviceHandle());
s.getSdfApiAdapter().hashInit(newSession, AlgId.SGD_SM3, null, null);
s.getSdfApiAdapter().hashInit(newSession, AlgId.SGD_SM3, eccPubKey, finalUserId);
s.getSdfApiAdapter().hashUpdate(newSession, pucData);
byte[] hash = s.getSdfApiAdapter().hashFinish(newSession);
s.getSdfApiAdapter().closeSession(newSession);
@@ -180,6 +190,11 @@ public class LoadBalancedSdfApiService implements SdfApiService {
});
}
@Override
public byte[] hash(byte[] pucData) {
return hash(pucData, null, null);
}
@Override
public byte[] encryptByTMK(byte[] data) {
byte[] pad = PaddingUtil.PKCS7Padding(data);