MCPcopy Index your code
hub / github.com/SeanDragon/protools / encrypt

Method encrypt

security/src/main/java/pro/tools/security/sm/SM2.java:203–262  ·  view source on GitHub ↗

公钥加密 @param input 加密原文 @param publicKey 公钥 @return

(String input, ECPoint publicKey)

Source from the content-addressed store, hash-verified

201 * @return
202 */
203 public byte[] encrypt(String input, ECPoint publicKey) {
204
205 byte[] inputBuffer = input.getBytes();
206
207 byte[] C1Buffer;
208 ECPoint kpb;
209 byte[] t;
210 do {
211 /* 1 产生随机数k,k属于[1, n-1] */
212 BigInteger k = random(n);
213
214 /* 2 计算椭圆曲线点C1 = [k]G = (x1, y1) */
215 ECPoint C1 = G.multiply(k);
216 C1Buffer = C1.getEncoded(false);
217
218 /*
219 * 3 计算椭圆曲线点 S = [h]Pb
220 */
221 BigInteger h = ecc_bc_spec.getH();
222 if (h != null) {
223 ECPoint S = publicKey.multiply(h);
224 if (S.isInfinity()) {
225 throw new IllegalStateException();
226 }
227 }
228
229 /* 4 计算 [k]PB = (x2, y2) */
230 kpb = publicKey.multiply(k).normalize();
231
232 /* 5 计算 t = KDF(x2||y2, klen) */
233 byte[] kpbBytes = kpb.getEncoded(false);
234 t = KDF(kpbBytes, inputBuffer.length);
235 // DerivationFunction kdf = new KDF1BytesGenerator(new
236 // ShortenedDigest(new SHA256Digest(), DIGEST_LENGTH));
237 //
238 // t = new byte[inputBuffer.length];
239 // kdf.init(new ISO18033KDFParameters(kpbBytes));
240 // kdf.generateBytes(t, 0, t.length);
241 } while (allZero(t));
242
243 /* 6 计算C2=M^t */
244 byte[] C2 = new byte[inputBuffer.length];
245 for (int i = 0; i < inputBuffer.length; i++) {
246 C2[i] = (byte) (inputBuffer[i] ^ t[i]);
247 }
248
249 /* 7 计算C3 = Hash(x2 || M || y2) */
250 byte[] C3 = sm3hash(kpb.getXCoord().toBigInteger().toByteArray(), inputBuffer,
251 kpb.getYCoord().toBigInteger().toByteArray());
252
253 /* 8 输出密文 C=C1 || C2 || C3 */
254
255 byte[] encryptResult = new byte[C1Buffer.length + C2.length + C3.length];
256
257 System.arraycopy(C1Buffer, 0, encryptResult, 0, C1Buffer.length);
258 System.arraycopy(C2, 0, encryptResult, C1Buffer.length, C2.length);
259 System.arraycopy(C3, 0, encryptResult, C1Buffer.length + C2.length, C3.length);
260

Callers

nothing calls this directly

Calls 5

randomMethod · 0.95
KDFMethod · 0.95
allZeroMethod · 0.95
sm3hashMethod · 0.95
toByteArrayMethod · 0.80

Tested by

no test coverage detected