base64To32ByteKey function

Uint8List base64To32ByteKey(
  1. String base64Key
)

Converts a Base64-encoded string to a 32-byte key.

This function decodes the given Base64 string into bytes and ensures that the resulting byte array is exactly 32 bytes long. If the decoded byte array is already 32 bytes, it is returned as is. If it is longer than 32 bytes, it is truncated to 32 bytes. If it is shorter than 32 bytes, it is padded with zeros to reach the required length.

  • Parameter base64Key: The Base64-encoded string representing the key.
  • Returns: A 32-byte Uint8List representing the key.

Implementation

Uint8List base64To32ByteKey(String base64Key) {
  final keyBytes = base64Decode(base64Key);
  if (keyBytes.length == 32) {
    return keyBytes; // Already 32 bytes
  } else if (keyBytes.length > 32) {
    return keyBytes.sublist(0, 32); // Truncate to 32 bytes
  } else {
    final paddedKey = Uint8List(32)
      ..setRange(0, keyBytes.length, keyBytes); // Pad with zeros
    return paddedKey;
  }
}