decryptCredentialBundle function
Decrypts an encrypted email authentication/recovery or OAuth credential bundle.
This function takes an encrypted credential bundle, decodes it using Base58Check, and decrypts it using the specified private key. The decryption process involves extracting the encapsulated public key and ciphertext, uncompressing the public key, and performing HPKE decryption.
Parameters:
credentialBundle: The encrypted credential bundle as a Base58Check encoded string.embeddedKey: The private key for decryption as a hexadecimal string.
Returns:
- The decrypted data as a hexadecimal string.
Throws:
- ArgumentError if the credential bundle is invalid or too small.
- Exception if decryption fails.
Implementation
String decryptCredentialBundle({
required String credentialBundle,
required String embeddedKey,
}) {
try {
final bundleBytes = Base58CheckCodec.bitcoin().decode(credentialBundle);
// Base58CheckCodec strips the version byte, so we need to add it back
final versionByte = Uint8List.fromList([bundleBytes.version]);
final bundleBytesPayload =
Uint8List.fromList(versionByte + bundleBytes.payload);
if (bundleBytesPayload.length <= 33) {
throw ArgumentError(
'Bundle size ${bundleBytesPayload.length} is too low. Expecting a compressed public key (33 bytes) and an encrypted credential.',
);
}
final compressedEncappedKeyBuf =
Uint8List.fromList(bundleBytesPayload.sublist(0, 33));
final ciphertextBuf = Uint8List.fromList(bundleBytesPayload.sublist(33));
final encappedKeyBuf = uncompressRawPublicKey(compressedEncappedKeyBuf);
final decryptedData = hpkeDecrypt(
ciphertextBuf: ciphertextBuf,
encappedKeyBuf: encappedKeyBuf,
receiverPriv: embeddedKey,
hpkeInfo: zeroxkeyHpkeInfo,
);
return uint8ArrayToHexString(decryptedData);
} catch (error) {
throw Exception('Error decrypting bundle: $error');
}
}