decrypt static method

String decrypt(
  1. String cipher,
  2. String privateKey, {
  3. int cipherMode = C1C3C2,
})

解密

Implementation

static String decrypt(String cipher, String privateKey,
    {int cipherMode = C1C3C2}) {
  final c1Hex = cipher.substring(0, 130); // 包含04前缀
  String c2Hex, c3Hex;

  if (cipherMode == C1C3C2) {
    c3Hex = cipher.substring(130, 130 + 64);
    c2Hex = cipher.substring(130 + 64);
  } else {
    c2Hex = cipher.substring(130, cipher.length - 64);
    c3Hex = cipher.substring(cipher.length - 64);
  }

  final c1Point = _ecParam.curve.decodePointHex(c1Hex)!;
  final priv = BigInt.parse(privateKey, radix: 16);
  final p = c1Point.multiply(priv);

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

  // KDF
  final c2Bytes = SMUtils.hexStringToBytes(c2Hex);
  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 < c2Bytes.length; i++) {
    if (offset == t.length) nextT();
    c2Bytes[i] ^= t[offset++] & 0xFF;
  }
  final checkC3 = SM3.hashBytes([...x2, ...c2Bytes, ...y2]);
  if (checkC3.toLowerCase() != c3Hex.toLowerCase()) return '';
  return utf8.decode(c2Bytes);
}