sign method
Signs data using the private key.
algorithm defaults to 'SHA256'.
Keys whose algorithm signs the message directly — Ed25519, Ed448 and
ML-DSA — reject an external digest, so for those this delegates to
signOneShot instead of failing with OpenSSL's opaque
invalid digest error. Pass allowOneShotFallback as false to get
that error back.
Implementation
Uint8List sign(
EvpPkey key,
Uint8List data, {
String algorithm = 'SHA256',
bool allowOneShotFallback = true,
}) {
if (allowOneShotFallback && keyRequiresOneShotSignature(key)) {
return signOneShot(key, data);
}
final bindings = this.bindings;
final ctx = bindings.EVP_MD_CTX_new();
if (ctx == nullptr) {
throw OpenSslException('Failed to create EVP_MD_CTX');
}
try {
final md = _resolveDigestOrNull(algorithm);
final initResult = bindings.EVP_DigestSignInit(
ctx,
nullptr,
md,
nullptr,
key.handle,
);
SslObject.checkCode(bindings, initResult,
msg: 'EVP_DigestSignInit failed');
final dataPtr = calloc<Uint8>(data.length);
dataPtr.asTypedList(data.length).setAll(0, data);
final updateResult = bindings.EVP_DigestSignUpdate(
ctx,
dataPtr.cast(),
data.length,
);
calloc.free(dataPtr);
SslObject.checkCode(bindings, updateResult,
msg: 'EVP_DigestSignUpdate failed');
final lenPtr = calloc<Size>();
final finalLenResult = bindings.EVP_DigestSignFinal(ctx, nullptr, lenPtr);
SslObject.checkCode(bindings, finalLenResult,
msg: 'EVP_DigestSignFinal (length) failed');
final sigLen = lenPtr.value;
final sigPtr = calloc<Uint8>(sigLen);
final finalResult =
bindings.EVP_DigestSignFinal(ctx, sigPtr.cast(), lenPtr);
if (finalResult <= 0) {
calloc.free(lenPtr);
calloc.free(sigPtr);
throw OpenSslException('EVP_DigestSignFinal failed');
}
final signature = Uint8List.fromList(sigPtr.asTypedList(lenPtr.value));
calloc.free(lenPtr);
calloc.free(sigPtr);
return signature;
} finally {
bindings.EVP_MD_CTX_free(ctx);
}
}