computeSharedSecret method
Computes shared secret (ECDH) between privateKey and peerPublicKey.
Implementation
Uint8List computeSharedSecret(EvpPkey privateKey, EvpPkey peerPublicKey) {
// 1. Create context from the private key
// EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e)
final ctx = bindings.EVP_PKEY_CTX_new(privateKey.handle, nullptr);
if (ctx == nullptr) throw OpenSslException('Failed to create EVP_PKEY_CTX');
try {
// 2. Init derive
if (bindings.EVP_PKEY_derive_init(ctx) <= 0) {
throw OpenSslException('EVP_PKEY_derive_init failed');
}
// 3. Set peer
if (bindings.EVP_PKEY_derive_set_peer(ctx, peerPublicKey.handle) <= 0) {
throw OpenSslException('EVP_PKEY_derive_set_peer failed');
}
// 4. Determine buffer length
final lenPtr = calloc<Size>(); // size_t*
if (bindings.EVP_PKEY_derive(ctx, nullptr, lenPtr) <= 0) {
calloc.free(lenPtr);
throw OpenSslException('EVP_PKEY_derive (length) failed');
}
// 5. Derive
final len = lenPtr.value;
final secretPtr = calloc<Uint8>(len);
try {
if (bindings.EVP_PKEY_derive(ctx, secretPtr.cast(), lenPtr) <= 0) {
throw OpenSslException('EVP_PKEY_derive failed');
}
return Uint8List.fromList(secretPtr.asTypedList(len));
} finally {
calloc.free(secretPtr);
calloc.free(lenPtr);
}
} finally {
bindings.EVP_PKEY_CTX_free(ctx);
}
}