digestAuthEmailOtpCode function
Produces the keyed digest persisted for a low-entropy email OTP.
A plain SHA-256 digest does not protect a short numeric OTP from offline enumeration after a database leak. This boundary therefore requires an application secret and domain-separates email OTP material from other HMAC uses. The raw code must only be retained long enough for delivery.
Implementation
String digestAuthEmailOtpCode({required String code, required String secret}) {
final normalized = code.trim();
final key = utf8.encode(secret);
if (normalized.isEmpty || normalized.length > authEmailOtpMaximumLength) {
throw ArgumentError(
'must be non-empty and at most $authEmailOtpMaximumLength characters',
'code',
);
}
if (key.length < authEmailOtpDigestKeyMinimumLength) {
throw ArgumentError(
'must contain at least $authEmailOtpDigestKeyMinimumLength UTF-8 bytes',
'secret',
);
}
return Hmac(
sha256,
key,
).convert(utf8.encode('routed-auth:email-otp:$normalized')).toString();
}