1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 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, curve: string) {
if (curve === "P-256") {
const point = p256.ProjectivePoint.fromHex(bytes);
return pointToBytes(point, p256.CURVE.Fp);
}
if (curve === "secp256k1") {
const point = secp256k1.ProjectivePoint.fromHex(bytes);
return pointToBytes(point, secp256k1.CURVE.Fp);
}
throw new TypeError("error: unsupported key type");
}
function pointToBytes<T>(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.at(-1) & 1);
compressed.set(x, 1);
return compressed;
}