wrap static method

K4LocalWrap wrap(
  1. K4LocalKey key,
  2. K4LocalKey wrappingKey
)

Implementation

static K4LocalWrap wrap(K4LocalKey key, K4LocalKey wrappingKey) {
  if (key.rawBytes.length != K4LocalKey.keyLength) {
    throw ArgumentError('Key must be exactly ${K4LocalKey.keyLength} bytes');
  }

  final nonce = _randomBytes(Random.secure(), nonceLength);
  final derived = _deriveEncryptionMaterial(wrappingKey.rawBytes, nonce);
  final encryptionKey = derived.sublist(0, 32);
  final xchachaNonce = derived.sublist(32);
  final authKey = _deriveAuthKey(wrappingKey.rawBytes, nonce);

  final cipher = XChaCha20();
  cipher.init(
    true,
    ParametersWithIV<KeyParameter>(
      KeyParameter(Uint8List.fromList(encryptionKey)),
      Uint8List.fromList(xchachaNonce),
    ),
  );
  final ciphertext = cipher.process(key.rawBytes);

  final tag = _calculateTag(nonce, ciphertext, authKey);

  final payload = Uint8List(tagLength + nonceLength + ciphertext.length)
    ..setAll(0, tag)
    ..setAll(tagLength, nonce)
    ..setAll(tagLength + nonceLength, ciphertext);

  return K4LocalWrap(payload);
}