getPublicKey function
Derives the public key from a private key using the P-256 curve.
privateKey: The private key as aUint8Listor a hexadecimal string.isCompressed: Specifies whether to return a compressed or uncompressed public key. Defaults to true.
Returns:
- The public key as a
Uint8Listin the specified format.
Implementation
Uint8List getPublicKey(dynamic privateKey, {bool isCompressed = true}) {
Uint8List privKeyBytes;
if (privateKey is String) {
if (privateKey.length != 64) {
throw ArgumentError('Private key must be a 32-byte hexadecimal string.');
}
privKeyBytes = Uint8List.fromList(List<int>.generate(privateKey.length ~/ 2,
(i) => int.parse(privateKey.substring(i * 2, i * 2 + 2), radix: 16)));
} else if (privateKey is Uint8List) {
if (privateKey.length != 32) {
throw ArgumentError('Private key must be exactly 32 bytes.');
}
privKeyBytes = privateKey;
} else {
throw ArgumentError(
'Private key must be a Uint8List or a hexadecimal string.');
}
final domain = ECDomainParameters('secp256r1');
final privateKeyValue = BigInt.parse(
privKeyBytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(),
radix: 16);
final privateKeyParam = ECPrivateKey(privateKeyValue, domain);
final publicKeyPoint = domain.G * privateKeyParam.d;
if (publicKeyPoint == null) {
throw StateError('Failed to compute public key.');
}
if (isCompressed) {
return Uint8List.fromList(publicKeyPoint.getEncoded(true));
} else {
return Uint8List.fromList(publicKeyPoint.getEncoded(false));
}
}