Skip to content

Commit

Permalink
SM2: Add test vectors for SHA256, disable SHA1
Browse files Browse the repository at this point in the history
- other standard hashes commented out until test data available.
  • Loading branch information
peterdettman committed May 23, 2019
1 parent 4691dad commit 38663bf
Show file tree
Hide file tree
Showing 7 changed files with 316 additions and 134 deletions.
19 changes: 12 additions & 7 deletions core/src/main/java/org/bouncycastle/crypto/signers/SM2Signer.java
Expand Up @@ -7,7 +7,6 @@
import org.bouncycastle.crypto.CryptoServicesRegistrar;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.Signer;
import org.bouncycastle.crypto.digests.GeneralDigest;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyParameters;
Expand All @@ -30,7 +29,7 @@ public class SM2Signer
implements Signer, ECConstants
{
private final DSAKCalculator kCalculator = new RandomDSAKCalculator();
private final GeneralDigest digest;
private final Digest digest;
private final DSAEncoding encoding;

private ECDomainParameters ecParams;
Expand All @@ -43,7 +42,7 @@ public SM2Signer()
this(StandardDSAEncoding.INSTANCE, new SM3Digest());
}

public SM2Signer(GeneralDigest digest)
public SM2Signer(Digest digest)
{
this(StandardDSAEncoding.INSTANCE, digest);
}
Expand All @@ -54,7 +53,7 @@ public SM2Signer(DSAEncoding encoding)
this.digest = new SM3Digest();
}

public SM2Signer(DSAEncoding encoding, GeneralDigest digest)
public SM2Signer(DSAEncoding encoding, Digest digest)
{
this.encoding = encoding;
this.digest = digest;
Expand All @@ -69,6 +68,11 @@ public void init(boolean forSigning, CipherParameters param)
{
baseParam = ((ParametersWithID)param).getParameters();
userID = ((ParametersWithID)param).getID();

if (userID.length >= 8192)
{
throw new IllegalArgumentException("SM2 user ID must be less than 2^16 bits long");
}
}
else
{
Expand Down Expand Up @@ -148,7 +152,7 @@ public byte[] generateSignature()
byte[] eHash = digestDoFinal();

BigInteger n = ecParams.getN();
BigInteger e = calculateE(eHash);
BigInteger e = calculateE(n, eHash);
BigInteger d = ((ECPrivateKeyParameters)ecKey).getD();

BigInteger r, s;
Expand Down Expand Up @@ -212,7 +216,7 @@ private boolean verifySignature(BigInteger r, BigInteger s)
byte[] eHash = digestDoFinal();

// B4
BigInteger e = calculateE(eHash);
BigInteger e = calculateE(n, eHash);

// B5
BigInteger t = r.add(s).mod(n);
Expand Down Expand Up @@ -284,8 +288,9 @@ protected ECMultiplier createBasePointMultiplier()
return new FixedPointCombMultiplier();
}

protected BigInteger calculateE(byte[] message)
protected BigInteger calculateE(BigInteger n, byte[] message)
{
// TODO Should hashes larger than the order be truncated as with ECDSA?
return new BigInteger(1, message);
}
}

0 comments on commit 38663bf

Please sign in to comment.