33import java .math .BigInteger ;
44import java .security .SecureRandom ;
55
6+ import org .bouncycastle .crypto .CipherParameters ;
67import org .bouncycastle .crypto .CryptoServicesRegistrar ;
78import org .bouncycastle .crypto .InvalidCipherTextException ;
89import org .bouncycastle .crypto .digests .SM3Digest ;
910import org .bouncycastle .crypto .digests .SM9Sm3 ;
1011import org .bouncycastle .crypto .paddings .PKCS7Padding ;
1112import org .bouncycastle .crypto .paddings .PaddedBufferedBlockCipher ;
1213import org .bouncycastle .crypto .params .KeyParameter ;
14+ import org .bouncycastle .crypto .params .ParametersWithRandom ;
1315import org .bouncycastle .crypto .params .SM9EncMasterPublicKeyParameters ;
1416import org .bouncycastle .crypto .params .SM9EncPrivateKeyParameters ;
1517import org .bouncycastle .crypto .params .SM9EncPublicKeyParameters ;
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 */
3238public 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 )
0 commit comments