非对称加解密

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
@@ -90,7 +90,10 @@ public class SingleSdfApiService implements SdfApiService, InitializingBean {
@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 sdfApiAdapter.externalSignECC(sessionHandle, priKey, pucData);
}
@Override
@@ -123,7 +126,11 @@ public class SingleSdfApiService implements SdfApiService, InitializingBean {
@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 sdfApiAdapter.externalVerifyECC(sessionHandle, eccPublicKey, pubData, eccSignature);
}
@Override
@@ -154,6 +161,19 @@ public class SingleSdfApiService implements SdfApiService, InitializingBean {
return BCSM3Utils.hmac(key, srcData);
}
@Override
public byte[] hash(byte[] pucData, byte[] pubKey, byte[] userId) {
checkStatus();
EccPubKey eccPubKey = pubKey == null || pubKey.length == 0 ? null : EccPubKey.fromBytes(pubKey);
byte[] finalUserId = Objects.nonNull(pubKey) && Objects.isNull(userId) ? CryptoConst.USER_ID : userId;
String newSession = sdfApiAdapter.openSession(deviceHandle);
sdfApiAdapter.hashInit(newSession, AlgId.SGD_SM3, eccPubKey, finalUserId);
sdfApiAdapter.hashUpdate(newSession, pucData);
byte[] hash = sdfApiAdapter.hashFinish(newSession);
sdfApiAdapter.closeSession(newSession);
return hash;
}
@Override
public byte[] hash(byte[] pucData) {
checkStatus();
@@ -130,11 +130,11 @@ public class SdfApiServiceTest {
@Test
public void testSm3() {
byte[] sdfHash = sdfService.hash(plain.getBytes());
byte[] sdfHash = sdfService.hash(plain.getBytes(), null, null);
log.info("sdf hash: {}", CodecUtils.encodeHex(sdfHash));
Assertions.assertEquals(32, sdfHash.length);
byte[] bcHash = bcService.hash(plain.getBytes());
byte[] bcHash = bcService.hash(plain.getBytes(),null, null);
log.info("bc hash: {}", CodecUtils.encodeHex(bcHash));
Assertions.assertEquals(32, bcHash.length);