Skip to content

Commit d10b2f6

Browse files
committed
Reshaped SM9Engine to the SM2Engine API pattern (Mode constructor, init/processBlock, ParametersWithRandom), fixed the non-terminating retry loop when stream-mode encrypting an empty message, and classified Cipher.SM9 as pke in generateCbom.
1 parent ba19435 commit d10b2f6

4 files changed

Lines changed: 203 additions & 28 deletions

File tree

‎core/src/main/java/org/bouncycastle/crypto/engines/SM9Engine.java‎

Lines changed: 145 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
import java.math.BigInteger;
44
import java.security.SecureRandom;
55

6+
import org.bouncycastle.crypto.CipherParameters;
67
import org.bouncycastle.crypto.CryptoServicesRegistrar;
78
import org.bouncycastle.crypto.InvalidCipherTextException;
89
import org.bouncycastle.crypto.digests.SM3Digest;
910
import org.bouncycastle.crypto.digests.SM9Sm3;
1011
import org.bouncycastle.crypto.paddings.PKCS7Padding;
1112
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
1213
import org.bouncycastle.crypto.params.KeyParameter;
14+
import org.bouncycastle.crypto.params.ParametersWithRandom;
1315
import org.bouncycastle.crypto.params.SM9EncMasterPublicKeyParameters;
1416
import org.bouncycastle.crypto.params.SM9EncPrivateKeyParameters;
1517
import org.bouncycastle.crypto.params.SM9EncPublicKeyParameters;
@@ -24,35 +26,158 @@
2426
/**
2527
* The SM9 public key encryption algorithm (GM/T 0044.4-2016, clause 7). Two
2628
* data-encapsulation methods are supported: a KDF-based stream cipher
27-
* ({@link #MODE_STREAM}) and SM4 in ECB mode with PKCS#7 padding
28-
* ({@link #MODE_SM4}). The ciphertext is C = C1 || C3 || C2, where C1 is the
29+
* ({@link Mode#STREAM}) and SM4 in ECB mode with PKCS#7 padding
30+
* ({@link Mode#SM4}). The ciphertext is C = C1 || C3 || C2, where C1 is the
2931
* G1 point [r]Q_B encoded as x||y, C3 = MAC(K2, C2), and C2 is the encapsulated
3032
* message.
33+
* <p>
34+
* Usage follows the {@link SM2Engine} pattern: construct with the desired mode,
35+
* {@code init(true, new ParametersWithRandom(recipientKey, random))} to encrypt or
36+
* {@code init(false, userKey)} to decrypt, then {@link #processBlock(byte[], int, int)}.
3137
*/
3238
public class SM9Engine
3339
{
34-
/** KDF-based stream cipher encapsulation (GM/T 0044.4-2016, method a). */
35-
public static final int MODE_STREAM = 0;
36-
/** SM4/ECB/PKCS#7 block cipher encapsulation (method b). */
37-
public static final int MODE_SM4 = 1;
40+
/**
41+
* The GM/T 0044.4-2016 data-encapsulation method. (A constants class rather than
42+
* an enum so the single source also compiles for the legacy pre-Java-5
43+
* distributions.)
44+
*/
45+
public static final class Mode
46+
{
47+
/** KDF-based stream cipher (XOR) encapsulation (method a). */
48+
public static final Mode STREAM = new Mode();
49+
/** SM4/ECB/PKCS#7 block cipher encapsulation (method b). */
50+
public static final Mode SM4 = new Mode();
51+
52+
private Mode()
53+
{
54+
}
55+
}
3856

3957
private static final int K2_LEN = 32; // K2_len = 256 bits
4058

41-
public byte[] encrypt(int mode, SM9EncPublicKeyParameters recipient, byte[] message, SecureRandom random)
59+
private final Mode mode;
60+
61+
private boolean forEncryption;
62+
private SM9EncPublicKeyParameters recipient;
63+
private SM9EncPrivateKeyParameters userKey;
64+
private SecureRandom random;
65+
66+
/**
67+
* Base constructor: SM4 data encapsulation ({@link Mode#SM4}).
68+
*/
69+
public SM9Engine()
70+
{
71+
this(Mode.SM4);
72+
}
73+
74+
public SM9Engine(Mode mode)
75+
{
76+
if (mode == null)
77+
{
78+
throw new IllegalArgumentException("mode cannot be null");
79+
}
80+
this.mode = mode;
81+
}
82+
83+
/**
84+
* Initialise the engine. For encryption pass the recipient's
85+
* {@link SM9EncPublicKeyParameters}, optionally wrapped in a
86+
* {@link ParametersWithRandom}; for decryption pass the user's
87+
* {@link SM9EncPrivateKeyParameters}.
88+
*/
89+
public void init(boolean forEncryption, CipherParameters param)
90+
{
91+
this.forEncryption = forEncryption;
92+
93+
if (forEncryption)
94+
{
95+
SecureRandom provided = null;
96+
CipherParameters key = param;
97+
if (param instanceof ParametersWithRandom)
98+
{
99+
ParametersWithRandom rParam = (ParametersWithRandom)param;
100+
provided = rParam.getRandom();
101+
key = rParam.getParameters();
102+
}
103+
if (!(key instanceof SM9EncPublicKeyParameters))
104+
{
105+
throw new IllegalArgumentException("SM9 encryption requires an SM9EncPublicKeyParameters recipient key");
106+
}
107+
this.recipient = (SM9EncPublicKeyParameters)key;
108+
this.userKey = null;
109+
this.random = CryptoServicesRegistrar.getSecureRandom(provided);
110+
}
111+
else
112+
{
113+
if (!(param instanceof SM9EncPrivateKeyParameters))
114+
{
115+
throw new IllegalArgumentException("SM9 decryption requires an SM9EncPrivateKeyParameters user key");
116+
}
117+
this.userKey = (SM9EncPrivateKeyParameters)param;
118+
this.recipient = null;
119+
this.random = null;
120+
}
121+
}
122+
123+
/**
124+
* Return an upper bound for the output produced by {@link #processBlock} on
125+
* {@code inputLen} input bytes (exact for encryption and stream-mode decryption,
126+
* an upper bound for SM4-mode decryption, whose padding length is unknown until
127+
* removed).
128+
*/
129+
public int getOutputSize(int inputLen)
130+
{
131+
if (forEncryption)
132+
{
133+
return 96 + ((mode == Mode.SM4) ? (((inputLen >> 4) + 1) << 4) : inputLen);
134+
}
135+
return Math.max(0, inputLen - 96);
136+
}
137+
138+
public byte[] processBlock(byte[] in, int inOff, int inLen)
42139
throws InvalidCipherTextException
43140
{
141+
byte[] data = new byte[inLen];
142+
System.arraycopy(in, inOff, data, 0, inLen);
143+
144+
if (forEncryption)
145+
{
146+
if (recipient == null)
147+
{
148+
throw new IllegalStateException("SM9 engine not initialised for encryption");
149+
}
150+
return encrypt(data);
151+
}
152+
if (userKey == null)
153+
{
154+
throw new IllegalStateException("SM9 engine not initialised for decryption");
155+
}
156+
return decrypt(data);
157+
}
158+
159+
private byte[] encrypt(byte[] message)
160+
throws InvalidCipherTextException
161+
{
162+
if (mode == Mode.STREAM && message.length == 0)
163+
{
164+
// K1_len is the message length, so an empty message has no K1 to test
165+
// against zero and the retry loop would never terminate; the SM4 mode
166+
// handles empty input (one padding block).
167+
throw new InvalidCipherTextException("SM9 stream mode cannot encrypt an empty message");
168+
}
169+
44170
SM9EncMasterPublicKeyParameters master = recipient.getMasterPublicKey();
45171
byte[] id = recipient.getIdentity();
46172
ECPoint qb = master.recipientPoint(id);
47173
Fp12 g = master.pairingWithP2();
48-
SecureRandom rand = CryptoServicesRegistrar.getSecureRandom(random);
49174
BigInteger n = SM9Curve.N;
50175

51-
int k1Len = (mode == MODE_SM4) ? 16 : message.length;
176+
int k1Len = (mode == Mode.SM4) ? 16 : message.length;
52177

53178
for (;;)
54179
{
55-
BigInteger r = BigIntegers.createRandomInRange(ECConstants.ONE, n.subtract(ECConstants.ONE), rand);
180+
BigInteger r = BigIntegers.createRandomInRange(ECConstants.ONE, n.subtract(ECConstants.ONE), random);
56181
ECPoint c1 = SM9Curve.multiplySecure(qb, r).normalize();
57182
Fp12 w = g.powSecure(r);
58183
byte[] c1b = SM9Curve.g1ToBytes(c1);
@@ -63,19 +188,23 @@ public byte[] encrypt(int mode, SM9EncPublicKeyParameters recipient, byte[] mess
63188
continue;
64189
}
65190
byte[] k2 = Arrays.copyOfRange(k, k1Len, k1Len + K2_LEN);
66-
byte[] c2 = (mode == MODE_SM4) ? sm4(true, k1, message) : xor(message, k1);
191+
byte[] c2 = (mode == Mode.SM4) ? sm4(true, k1, message) : xor(message, k1);
67192
byte[] c3 = mac(k2, c2);
68193
return Arrays.concatenate(c1b, c3, c2);
69194
}
70195
}
71196

72-
public byte[] decrypt(int mode, SM9EncPrivateKeyParameters key, byte[] ciphertext)
197+
private byte[] decrypt(byte[] ciphertext)
73198
throws InvalidCipherTextException
74199
{
75200
if (ciphertext.length < 64 + 32)
76201
{
77202
throw new InvalidCipherTextException("SM9 ciphertext too short");
78203
}
204+
if (mode == Mode.STREAM && ciphertext.length == 64 + 32)
205+
{
206+
throw new InvalidCipherTextException("SM9 stream-mode ciphertext has an empty C2");
207+
}
79208
ECPoint c1 = SM9Curve.g1FromBytes(ciphertext, 0);
80209
if (c1.isInfinity() || !c1.isValid())
81210
{
@@ -85,9 +214,9 @@ public byte[] decrypt(int mode, SM9EncPrivateKeyParameters key, byte[] ciphertex
85214
byte[] c3 = Arrays.copyOfRange(ciphertext, 64, 96);
86215
byte[] c2 = Arrays.copyOfRange(ciphertext, 96, ciphertext.length);
87216

88-
Fp12 w = SM9Pairing.pairing(c1, key.getPrivatePoint());
89-
int k1Len = (mode == MODE_SM4) ? 16 : c2.length;
90-
byte[] k = SM9Sm3.kdf(Arrays.concatenate(c1b, SM9Pairing.toBytes(w), key.getIdentity()), (k1Len + K2_LEN) * 8);
217+
Fp12 w = SM9Pairing.pairing(c1, userKey.getPrivatePoint());
218+
int k1Len = (mode == Mode.SM4) ? 16 : c2.length;
219+
byte[] k = SM9Sm3.kdf(Arrays.concatenate(c1b, SM9Pairing.toBytes(w), userKey.getIdentity()), (k1Len + K2_LEN) * 8);
91220
byte[] k1 = Arrays.copyOfRange(k, 0, k1Len);
92221
if (Arrays.areAllZeroes(k1, 0, k1Len))
93222
{
@@ -99,7 +228,7 @@ public byte[] decrypt(int mode, SM9EncPrivateKeyParameters key, byte[] ciphertex
99228
{
100229
throw new InvalidCipherTextException("SM9 MAC check failed");
101230
}
102-
return (mode == MODE_SM4) ? sm4(false, k1, c2) : xor(c2, k1);
231+
return (mode == Mode.SM4) ? sm4(false, k1, c2) : xor(c2, k1);
103232
}
104233

105234
private static byte[] xor(byte[] in, byte[] pad)

‎gradle/cbom.gradle‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ ext.cbomClassify = { String type, String alg ->
6363
{
6464
return ['kem', ['encapsulate', 'decapsulate']]
6565
}
66-
if (hasAny(['RSA', 'ELGAMAL', 'IES', 'SM2']))
66+
if (hasAny(['RSA', 'ELGAMAL', 'IES', 'SM2', 'SM9']))
6767
{
6868
return ['pke', ['encrypt', 'decrypt']]
6969
}
@@ -504,9 +504,9 @@ tasks.register('generateCbom') {
504504
}
505505
if (a.startsWith('SM9'))
506506
{
507-
// SM9 (GM/T 0044) identity-based crypto: the SM9-ENC master keypair exists
508-
// to serve the SM9-KEM encapsulation (Part 4), which registers its own
509-
// asset — revisit if an SM9 PKE cipher or SM9 signature is added
507+
// SM9 (GM/T 0044) identity-based crypto: the SM9-ENC master keypair
508+
// serves the SM9-KEM encapsulation and the Cipher.SM9 encryption (Part 4),
509+
// each of which registers its own asset — revisit if SM9 signing is added
510510
return 'kem'
511511
}
512512
return 'unknown'

‎prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/sm9/CipherSpi.java‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import org.bouncycastle.asn1.gm.SM9Cipher;
2121
import org.bouncycastle.crypto.CryptoServicesRegistrar;
2222
import org.bouncycastle.crypto.InvalidCipherTextException;
23+
import org.bouncycastle.crypto.params.ParametersWithRandom;
2324
import org.bouncycastle.crypto.params.SM9EncPrivateKeyParameters;
2425
import org.bouncycastle.crypto.params.SM9EncPublicKeyParameters;
2526
import org.bouncycastle.crypto.engines.SM9Engine;
@@ -44,11 +45,10 @@
4445
public class CipherSpi
4546
extends javax.crypto.CipherSpi
4647
{
47-
private final SM9Engine engine = new SM9Engine();
4848
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
4949

5050
private int state = -1;
51-
private int mode = SM9Engine.MODE_SM4;
51+
private SM9Engine.Mode mode = SM9Engine.Mode.SM4;
5252
private SM9EncPublicKeyParameters recipient;
5353
private SM9EncPrivateKeyParameters userKey;
5454
private SecureRandom random;
@@ -59,11 +59,11 @@ protected void engineSetMode(String modeName)
5959
String m = modeName == null ? "" : Strings.toUpperCase(modeName);
6060
if (m.equals("SM4") || m.equals("ECB") || m.equals(""))
6161
{
62-
mode = SM9Engine.MODE_SM4;
62+
mode = SM9Engine.Mode.SM4;
6363
}
6464
else if (m.equals("XOR") || m.equals("STREAM") || m.equals("KDF"))
6565
{
66-
mode = SM9Engine.MODE_STREAM;
66+
mode = SM9Engine.Mode.STREAM;
6767
}
6868
else
6969
{
@@ -190,25 +190,32 @@ protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
190190
{
191191
if (state == Cipher.ENCRYPT_MODE)
192192
{
193-
byte[] raw = engine.encrypt(mode, recipient, data, random); // C1(64) || C3(32) || C2
193+
SM9Engine engine = new SM9Engine(mode);
194+
engine.init(true, new ParametersWithRandom(recipient, random));
195+
byte[] raw = engine.processBlock(data, 0, data.length); // C1(64) || C3(32) || C2
194196
byte[] c1 = new byte[65];
195197
c1[0] = 0x04;
196198
System.arraycopy(raw, 0, c1, 1, 64);
197199
byte[] c3 = Arrays.copyOfRange(raw, 64, 96);
198200
byte[] c2 = Arrays.copyOfRange(raw, 96, raw.length);
199-
return new SM9Cipher(mode, c1, c3, c2).getEncoded();
201+
int enType = (mode == SM9Engine.Mode.SM4) ? SM9Cipher.EN_TYPE_SM4 : SM9Cipher.EN_TYPE_STREAM;
202+
return new SM9Cipher(enType, c1, c3, c2).getEncoded();
200203
}
201204
else
202205
{
203206
SM9Cipher c = SM9Cipher.getInstance(data);
204207
byte[] c1 = c.getC1(); // 0x04 || x || y
205208
byte[] raw = Arrays.concatenate(Arrays.copyOfRange(c1, 1, 65), c.getC3(), c.getC2());
206-
return engine.decrypt(c.getEnType(), userKey, raw);
209+
SM9Engine engine = new SM9Engine(
210+
(c.getEnType() == SM9Cipher.EN_TYPE_SM4) ? SM9Engine.Mode.SM4 : SM9Engine.Mode.STREAM);
211+
engine.init(false, userKey);
212+
return engine.processBlock(raw, 0, raw.length);
207213
}
208214
}
209215
catch (InvalidCipherTextException e)
210216
{
211-
throw SecurityExceptions.badPaddingException("SM9 decryption failed: " + e.getMessage(), e);
217+
throw SecurityExceptions.badPaddingException(
218+
(state == Cipher.ENCRYPT_MODE ? "SM9 encryption failed: " : "SM9 decryption failed: ") + e.getMessage(), e);
212219
}
213220
catch (IOException e)
214221
{

‎prov/src/test/java/org/bouncycastle/jce/provider/test/SM9CipherTest.java‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import java.security.spec.PKCS8EncodedKeySpec;
1414
import java.security.spec.X509EncodedKeySpec;
1515

16+
import javax.crypto.BadPaddingException;
1617
import javax.crypto.Cipher;
1718
import javax.crypto.KeyGenerator;
1819

@@ -77,6 +78,44 @@ public void performTest()
7778
decX.init(Cipher.DECRYPT_MODE, bobKey);
7879
isTrue("SM9 Cipher stream-mode round-trip", Arrays.areEqual(decX.doFinal(ctX), plaintext));
7980

81+
// empty plaintext: SM4 mode round-trips (one padding block); the stream mode
82+
// has no K1 for an empty message and must reject it rather than loop retrying
83+
Cipher encEmpty = Cipher.getInstance("SM9", "BC");
84+
encEmpty.init(Cipher.ENCRYPT_MODE, bobPublic);
85+
byte[] ctEmpty = encEmpty.doFinal(new byte[0]);
86+
Cipher decEmpty = Cipher.getInstance("SM9", "BC");
87+
decEmpty.init(Cipher.DECRYPT_MODE, bobKey);
88+
isTrue("SM9 Cipher SM4-mode empty plaintext round-trip", decEmpty.doFinal(ctEmpty).length == 0);
89+
90+
try
91+
{
92+
Cipher encXEmpty = Cipher.getInstance("SM9/XOR/NoPadding", "BC");
93+
encXEmpty.init(Cipher.ENCRYPT_MODE, bobPublic);
94+
encXEmpty.doFinal(new byte[0]);
95+
fail("SM9 stream mode encrypted an empty plaintext");
96+
}
97+
catch (BadPaddingException e)
98+
{
99+
// expected - no K1 to derive for an empty message
100+
}
101+
102+
// a tampered C3 (MAC) must be rejected
103+
SM9Cipher parsed = SM9Cipher.getInstance(ct);
104+
byte[] brokenC3 = Arrays.clone(parsed.getC3());
105+
brokenC3[0] ^= 1;
106+
byte[] tampered = new SM9Cipher(parsed.getEnType(), parsed.getC1(), brokenC3, parsed.getC2()).getEncoded();
107+
try
108+
{
109+
Cipher decBad = Cipher.getInstance("SM9", "BC");
110+
decBad.init(Cipher.DECRYPT_MODE, bobKey);
111+
decBad.doFinal(tampered);
112+
fail("SM9 decryption accepted a tampered C3");
113+
}
114+
catch (BadPaddingException e)
115+
{
116+
// expected - MAC check failed
117+
}
118+
80119
// guards: a master public key is not a recipient key, and no spec is accepted
81120
try
82121
{

0 commit comments

Comments
 (0)