Refactoring in SM2Signer
@@ -104,27 +104,18 @@ public boolean verifySignature(byte[] signature)
{
try
{
- ASN1Sequence s = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(signature));
- if (s.size() != 2)
+ BigInteger[] rs = derDecode(signature);
+ if (rs != null)
{
- return false;
+ return verifySignature(rs[0], rs[1]);
}
- if (!Arrays.constantTimeAreEqual(signature, s.getEncoded(ASN1Encoding.DER)))
- {
- return false;
- }
-
- return verifySignature(ASN1Integer.getInstance(s.getObjectAt(0)).getValue(),
- ASN1Integer.getInstance(s.getObjectAt(1)).getValue());
}
catch (IOException e)
{
- Arrays.constantTimeAreEqual(signature, signature);
+ }
- // TODO: maybe introduce arithmetic delay?
return false;
}
- }
public void reset()
{
@@ -175,15 +166,9 @@ public void reset()
while (s.equals(ZERO));
// A7
-
- ASN1EncodableVector v = new ASN1EncodableVector();
-
- v.add(new ASN1Integer(r));
- v.add(new ASN1Integer(s));
-
try
{
- return new DERSequence(v).getEncoded(ASN1Encoding.DER);
+ return derEncode(r, s);
}
catch (IOException ex)
{
@@ -208,8 +193,6 @@ private boolean verifySignature(BigInteger r, BigInteger s)
return false;
}
- ECPoint q = ((ECPublicKeyParameters)ecKey).getQ();
-
// B3
byte[] eHash = digestDoFinal();
@@ -224,6 +207,7 @@ private boolean verifySignature(BigInteger r, BigInteger s)
}
// B6
+ ECPoint q = ((ECPublicKeyParameters)ecKey).getQ();
ECPoint x1y1 = ECAlgorithms.sumOfTwoMultiplies(ecParams.getG(), s, q, t).normalize();
if (x1y1.isInfinity())
{
@@ -280,4 +264,35 @@ protected BigInteger calculateE(byte[] message)
{
return new BigInteger(1, message);
}
+
+ protected BigInteger[] derDecode(byte[] encoding)
+ throws IOException
+ {
+ ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoding));
+ if (seq.size() != 2)
+ {
+ return null;
+ }
+
+ BigInteger r = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
+ BigInteger s = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue();
+
+ byte[] expectedEncoding = derEncode(r, s);
+ if (!Arrays.constantTimeAreEqual(expectedEncoding, encoding))
+ {
+ return null;
+ }
+
+ return new BigInteger[]{ r, s };
+ }
+
+ protected byte[] derEncode(BigInteger r, BigInteger s)
+ throws IOException
+ {
+
+ ASN1EncodableVector v = new ASN1EncodableVector();
+ v.add(new ASN1Integer(r));
+ v.add(new ASN1Integer(s));
+ return new DERSequence(v).getEncoded(ASN1Encoding.DER);
+ }
}
