Back

Version 21

4/15/2024
// SPDX-License-Identifier: 0BSD
import type { IField } from "npm:@noble/curves/abstract/modular";
import type { ProjPointType } from "npm:@noble/curves/abstract/weierstrass";
import { p256 } from "npm:@noble/curves/p256";
import { secp256k1 } from "npm:@noble/curves/secp256k1";

export function decompressPoint(bytes: Uint8Array, keyType: string) {
if (keyType === "P-256") {
const point = p256.ProjectivePoint.fromHex(bytes);
return pointToBytes(point, p256.CURVE.Fp);
}
if (keyType === "secp256k1") {
const point = secp256k1.ProjectivePoint.fromHex(bytes);
return pointToBytes(point, secp256k1.CURVE.Fp);
}
throw new TypeError("error: unsupported key type");
}

function pointToBytes<T extends number | bigint>(point: ProjPointType<T>, Fp: IField<T>) {
const x = Fp.toBytes(point.x);
const y = Fp.toBytes(point.y);
return { x, y };
}

// @see: https://stackoverflow.com/questions/17171542/algorithm-for-elliptic-curve-point-compression
export function compressPoint({ x, y }: { x: Uint8Array; y: Uint8Array }) {
const compressed = new Uint8Array(x.length + 1);
compressed[0] = 2 + (y[y.length - 1] & 1);
compressed.set(x, 1);
return compressed;
}
Updated: April 15, 2024