deriveSecret function

Secret deriveSecret(
  1. dynamic sharedKey, {
  2. bool isSharedKey = true,
})

Implementation

Secret deriveSecret(dynamic sharedKey, {bool isSharedKey = true}) {
  if (sharedKey is! Uint8List && sharedKey is! String) {
    throw "'sharedKey' must be a string or Uint8List";
  }

  if (sharedKey is String) {
    if (isSharedKey && !isHex(sharedKey)) {
      throw const FormatException("'sharedKey' must be an hexadecimal string");
    }

    if (isSharedKey) {
      sharedKey = Uint8List.fromList(hexToUint8List(sharedKey));
    } else {
      throw "'sharedKey' must be an hexadecimal string";
    }
  }

  final sha256 = Digest('SHA-256');
  final pseudoRandomKey = sha256.process(sharedKey);

  var hmac = crypto.Hmac(crypto.sha256, pseudoRandomKey);
  var digest = hmac.convert(utf8.encode('0'));
  final iv = Uint8List.fromList(digest.bytes.sublist(0, 32));

  hmac = crypto.Hmac(crypto.sha256, iv);
  digest = hmac.convert(utf8.encode('1'));
  final aesKey = Uint8List.fromList(digest.bytes.sublist(0, 32));

  return Secret(iv: iv, aesKey: aesKey);
}