Skip to content

Commit

Permalink
TKSS-1016: NativeSM2KeyAgreement should be created in constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
johnshajiang committed Dec 27, 2024
1 parent 5e83c54 commit 279ee5c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.openjdk.jmh.annotations.*;

import javax.crypto.KeyAgreement;
import java.security.InvalidKeyException;
import java.util.concurrent.TimeUnit;

import static com.tencent.kona.crypto.CryptoUtils.toBytes;
Expand Down Expand Up @@ -72,11 +71,12 @@ public static class KeyAgreementHolder {
@Param({"KonaCrypto", "KonaCrypto-Native"})
String provider;

SM2KeyAgreementParamSpec paramSpec;
KeyAgreement keyAgreement;

@Setup(Level.Invocation)
@Setup(Level.Trial)
public void setup() throws Exception {
SM2KeyAgreementParamSpec paramSpec = new SM2KeyAgreementParamSpec(
paramSpec = new SM2KeyAgreementParamSpec(
toBytes(ID),
new SM2PrivateKey(toBytes(PRI_KEY)),
new SM2PublicKey(toBytes(PUB_KEY)),
Expand All @@ -85,13 +85,13 @@ public void setup() throws Exception {
true,
16);
keyAgreement = KeyAgreement.getInstance("SM2", provider);
keyAgreement.init(
new SM2PrivateKey(toBytes(TMP_PRI_KEY)), paramSpec);
}
}

@Benchmark
public byte[] generateSecret(KeyAgreementHolder holder) throws InvalidKeyException {
public byte[] generateSecret(KeyAgreementHolder holder) throws Exception {
holder.keyAgreement.init(
new SM2PrivateKey(toBytes(TMP_PRI_KEY)), holder.paramSpec);
holder.keyAgreement.doPhase(new SM2PublicKey(toBytes(PEER_TMP_PUB_KEY)), true);
return holder.keyAgreement.generateSecret();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,12 @@ public final class SM2KeyAgreement extends KeyAgreementSpi {
private SM2KeyAgreementParamSpec paramSpec;
private SM2PublicKey peerEphemeralPublicKey;

private NativeSM2KeyAgreement sm2;
private final NativeSM2KeyAgreement sm2;

public SM2KeyAgreement() {
sm2 = new NativeSM2KeyAgreement();
SWEEPER.register(this, new SweepNativeRef(sm2));
}

@Override
protected void engineInit(Key key, SecureRandom random) {
Expand Down Expand Up @@ -85,10 +90,6 @@ protected void engineInit(Key key, AlgorithmParameterSpec params,
ephemeralPrivateKey = new SM2PrivateKey((ECPrivateKey) key);
paramSpec = (SM2KeyAgreementParamSpec) params;
peerEphemeralPublicKey = null;

sm2 = new NativeSM2KeyAgreement();

SWEEPER.register(this, new SweepNativeRef(sm2));
}

@Override
Expand Down

0 comments on commit 279ee5c

Please sign in to comment.