encrypt static method

String encrypt(
  1. String msg,
  2. String publicKey, {
  3. int cipherMode = C1C3C2,
})

加密 (C1 保留 04 前缀)

Implementation

static String encrypt(String msg, String publicKey,
    {int cipherMode = C1C3C2}) {
  final msgBytes = utf8.encode(msg);
  final pubPoint = _ecParam.curve.decodePointHex(publicKey)!;
  final k = _randomK();
  final c1Point = _ecParam.G!.multiply(k);
  final c1 = '04' +
      leftPad(c1Point.getX().toBigInteger().toRadixString(16), 64) +
      leftPad(c1Point.getY().toBigInteger().toRadixString(16), 64);

  final p = pubPoint.multiply(k);
  final x2 = SMUtils.hexStringToBytes(
      leftPad(p.getX().toBigInteger().toRadixString(16), 64));
  final y2 = SMUtils.hexStringToBytes(
      leftPad(p.getY().toBigInteger().toRadixString(16), 64));

  // KDF
  int ct = 1;
  int offset = 0;
  List<int> t = [];
  final z = [...x2, ...y2];
  void nextT() {
    t = SMUtils.hexStringToBytes(SM3.hashBytes([
      ...z,
      (ct >> 24) & 0xFF,
      (ct >> 16) & 0xFF,
      (ct >> 8) & 0xFF,
      ct & 0xFF
    ]));
    ct++;
    offset = 0;
  }

  nextT();
  for (int i = 0; i < msgBytes.length; i++) {
    if (offset == t.length) nextT();
    msgBytes[i] ^= t[offset++] & 0xFF;
  }
  final c2 = SMUtils.bytesToHexString(msgBytes);

  final c3 = SM3.hashBytes([...x2, ...utf8.encode(msg), ...y2]);
  return cipherMode == C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
}