SecretBox class

Output of encrypting bytes with a Cipher.

This class holds:

  • nonce ("initialization vector", "IV", "salt")
  • cipherText
  • mac (message authentication code)

Concatenating fields

You can use concatenation and SecretBox.fromConcatenation to concatenate the fields into a single byte array:

import 'package:cryptography/cryptography.dart';

void main() async {
  final aesGcm = AesGcm.with256bits();
  final secretKey = await aesGcm.newSecretKey();
  final secretBox = await aesGcm.encrypt(
    [1,2,3],
    secretKey: secretKey,
  );

  // Returns nonce + cipherText + mac
  final bytes = secretBox.concatenation();
  print('Encrypted: $bytes');

  // Splits the bytes into nonce, ciphertext, and MAC.
  final newSecretBox = SecretBox.fromConcatenation(
    bytes,
    nonceLength: aesGcm.nonceLength,
    macLength: aesGcm.macAlgorithm.macLength,
    copy: false, // Don't copy the bytes unless necessary.
  );

  final clearText = await aesGcm.decrypt(
    newSecretBox,
    secretKey: secretKey,
  );
  print('Decrypted: $clearText');
}

Constructors

SecretBox(List<int> cipherText, {required List<int> nonce, required Mac mac})

Properties

cipherText List<int>
Encrypted data.
final
hashCode int
The hash code for this object.
no setteroverride
mac Mac
Message authentication code (MAC) calculated by the encrypting party.
final
nonce List<int>
Nonce ("initialization vector", "IV", "salt") is a non-secret sequence of bytes required by most Cipher algorithms.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

checkMac({required MacAlgorithm macAlgorithm, required SecretKey secretKey, required List<int> aad}) Future<void>
Checks that the secret box has correct MAC.
concatenation({bool nonce = true, bool mac = true}) Uint8List
Returns a concatenation of nonce, cipherText and mac.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
override

Operators

operator ==(Object other) bool
The equality operator.
override

Static Methods

fromConcatenation(List<int> data, {required int nonceLength, required int macLength, bool copy = true}) SecretBox
Constructs a SecretBox from a concatenation of nonce, cipherText and mac.