wrap static method

K4SecretWrap wrap(
  1. K4SecretKey key,
  2. K4LocalKey wrappingKey
)

Implementation

static K4SecretWrap wrap(K4SecretKey key, K4LocalKey wrappingKey) {
  if (key.rawBytes.length != K4SecretKey.keyLength) {
    throw ArgumentError('Key must be exactly ${K4SecretKey.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 K4SecretWrap(payload);
}