sign method
Implementation
String sign({required List<int> key, JwtSupportedAlgorithm? alg}) {
alg ??= header.alg;
if (alg == null) {
throw BuError(
DefaultErrorType.invalidArgument,
"Unknown signing algorithm.",
);
}
final signingInput = serialize();
final signInputBytes = StringUtils.encode(signingInput);
List<int>? signature;
switch (alg) {
case JwtSupportedAlgorithm.eddsa:
final signingKey = BaseEd25519PrivateKey.fromBytes(
bytes: key.sublist(0, Ed25519KeysConst.privKeyByteLen),
type: CryptoKeyType.ed25519,
);
final signer = ED25519Signer(signingKey);
try {
signature = signer.sign(signInputBytes).encoded;
} finally {
signingKey.sk.zero();
}
break;
case JwtSupportedAlgorithm.hs256:
signature = QuickCrypto.hmacsha256Hash(key, signInputBytes);
break;
case JwtSupportedAlgorithm.hs384:
signature = QuickCrypto.hmacSha384Hash(key, signInputBytes);
break;
case JwtSupportedAlgorithm.hs512:
signature = QuickCrypto.hmacSha512Hash(key, signInputBytes);
break;
case JwtSupportedAlgorithm.es256:
final signingKey = Secp256r1PrivateKey.fromBytes(key);
final signer = Secp256r1Signer(signingKey);
try {
signature =
signer.sign(QuickCrypto.sha256Hash(signInputBytes)).encoded;
} finally {
signingKey.dispose();
}
break;
case JwtSupportedAlgorithm.es384:
final signingKey = Secp256r1PrivateKey.fromBytes(key);
final signer = Secp256r1Signer(signingKey);
try {
signature =
signer.sign(QuickCrypto.sha384Hash(signInputBytes)).encoded;
} finally {
signingKey.dispose();
}
break;
case JwtSupportedAlgorithm.es512:
final signingKey = Secp256r1PrivateKey.fromBytes(key);
final signer = Secp256r1Signer(signingKey);
try {
signature =
signer.sign(QuickCrypto.sha512Hash(signInputBytes)).encoded;
} finally {
signingKey.dispose();
}
break;
case JwtSupportedAlgorithm.es256k:
final signingKey = Secp256k1PrivateKey.fromBytes(key);
final signer = Secp256k1Signer(signingKey);
try {
signature =
signer.sign(QuickCrypto.sha256Hash(signInputBytes)).encoded;
} finally {
signingKey.dispose();
}
break;
}
final encodedSignature = StringUtils.decode(
signature,
b64NoPadding: true,
encoding: StringEncoding.base64UrlSafe,
);
return '$signingInput.$encodedSignature';
}