Skip to content

Commit 49eb0d5

Browse files
committed
SM2 user ID length checks
1 parent bfb80ae commit 49eb0d5

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

core/src/main/java/org/bouncycastle/crypto/agreement/SM2KeyExchange.java

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,7 @@ public void init(
5252
if (privParam instanceof ParametersWithID)
5353
{
5454
baseParam = (SM2KeyExchangePrivateParameters)((ParametersWithID)privParam).getParameters();
55-
userID = ((ParametersWithID)privParam).getID();
56-
57-
if (userID.length >= 8192)
58-
{
59-
// The length in bits must be expressible in two bytes
60-
throw new IllegalArgumentException("SM2 user ID must be less than 2^16 bits long");
61-
}
55+
userID = checkUserID(((ParametersWithID)privParam).getID());
6256
}
6357
else
6458
{
@@ -86,7 +80,7 @@ public byte[] calculateKey(int kLen, CipherParameters pubParam)
8680
if (pubParam instanceof ParametersWithID)
8781
{
8882
otherPub = (SM2KeyExchangePublicParameters)((ParametersWithID)pubParam).getParameters();
89-
otherUserID = ((ParametersWithID)pubParam).getID();
83+
otherUserID = checkUserID(((ParametersWithID)pubParam).getID());
9084
}
9185
else
9286
{
@@ -120,7 +114,7 @@ public byte[][] calculateKeyWithConfirmation(int kLen, byte[] confirmationTag, C
120114
if (pubParam instanceof ParametersWithID)
121115
{
122116
otherPub = (SM2KeyExchangePublicParameters)((ParametersWithID)pubParam).getParameters();
123-
otherUserID = ((ParametersWithID)pubParam).getID();
117+
otherUserID = checkUserID(((ParametersWithID)pubParam).getID());
124118
}
125119
else
126120
{
@@ -301,4 +295,15 @@ private byte[] digestDoFinal()
301295
digest.doFinal(result, 0);
302296
return result;
303297
}
298+
299+
private static byte[] checkUserID(byte[] userID)
300+
{
301+
// The length in bits must be expressible in two bytes
302+
if (userID.length >= 8192)
303+
{
304+
throw new IllegalArgumentException("SM2 user ID must be less than 2^16 bits long");
305+
}
306+
307+
return userID;
308+
}
304309
}

core/src/main/java/org/bouncycastle/crypto/signers/SM2Signer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,9 @@ public void init(boolean forSigning, CipherParameters param)
7979
baseParam = ((ParametersWithID)param).getParameters();
8080
userID = ((ParametersWithID)param).getID();
8181

82+
// The length in bits must be expressible in two bytes
8283
if (userID.length >= 8192)
8384
{
84-
// The length in bits must be expressible in two bytes
8585
throw new IllegalArgumentException("SM2 user ID must be less than 2^16 bits long");
8686
}
8787
}

0 commit comments

Comments
 (0)