lengthChecks function

void lengthChecks(
  1. String jwt
)

Validates that jwt fits within the size limits enforced by the zkLogin circuit.

Throws a FormatException if jwt is not a three-segment JWS, if its header is longer than MAX_HEADER_LEN_B64, or if the SHA-2 padded unsigned JWT would exceed MAX_PADDED_UNSIGNED_JWT_LEN.

Implementation

void lengthChecks(String jwt) {
  final parts = jwt.split('.');
  if (parts.length == 5) {
    throw const FormatException(
      'Only JWTs using Compact JWS serialization can be decoded',
    );
  }
  if (parts.length != 3) {
    throw const FormatException(
      'Invalid JWT: expected three dot-separated segments',
    );
  }
  final header = parts[0];
  final payload = parts[1];
  // Is the header small enough?
  if (header.length > MAX_HEADER_LEN_B64) {
    throw const FormatException('Header is too long');
  }

  // Is the combined length of (header, payload, SHA2 padding) small enough?
  // unsigned_jwt = header + '.' + payload;
  final l = (header.length + 1 + payload.length) * 8;
  final k = (512 + 448 - ((l % 512) + 1)) % 512;

  // The SHA2 padding is a 1 followed by K zeros, followed by the length of the
  // message.
  final paddedUnsignedJwtLen = (l + 1 + k + 64) ~/ 8;

  // The padded unsigned JWT must be less than the max padded length.
  if (paddedUnsignedJwtLen > MAX_PADDED_UNSIGNED_JWT_LEN) {
    throw const FormatException('JWT is too long');
  }
}