Skip to content

Instantly share code, notes, and snippets.

@thecipherBlock
Last active November 18, 2023 11:34
Show Gist options
  • Save thecipherBlock/674eac9cb56e8152eb770624d42c6de3 to your computer and use it in GitHub Desktop.
Save thecipherBlock/674eac9cb56e8152eb770624d42c6de3 to your computer and use it in GitHub Desktop.
Convert 32 bytes secp256k1 publicKey into compressed public key
function determineSignByte(publicKey: string): string {
if(publicKey.length !== 64) {
throw new Error("required `public key` of length 32");
}
const xCoordinate = BigInt("0x" + publicKey);
return xCoordinate % BigInt(2) === BigInt(0) ? "02" : "03";
}
function u8ToHex(arr: Uint8Array): string {
return Array.from(arr)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
}
function convertIntoCompressedPubKey(publicKey: Uint8Array|string): string {
let pubKeyInHex: string = publicKey as string
if(typeof publicKey === "object") {
pubKeyInHex = u8ToHex(publicKey);
}
return determineSignByte(pubKeyInHex)+pubKeyInHex;
}
// Example
convertIntoCompressedPubKey("dc6809580a89f0e723ecb1634f06d329252f45ec47c4cadcbc1836fe9da236c5"); // compressed with negative sign(03....)
convertIntoCompressedPubKey("dc3db8e6db9539f6f5aef7865cbc02022eec4b0eb9e57e950b29c6b52c2858c6"); // Positive with positive sign(02.....)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment