mima-kit
Version:
mima-kit is a cryptographic suite implemented in TypeScript. The goal is to provide an easy-to-use cryptographic library. mima-kit 是一个使用 TypeScript 实现的密码学套件。目标是提供一个简单易用的密码学库。
64 lines (63 loc) • 2.15 kB
JavaScript
import { KitError } from './utils';
// * Coordinate Systems
export function CoordinateSystem(field) {
const { mul, inv, mod, squ } = field;
const toAffine = (P) => {
if (!P || P.isInfinity)
return { type: 'affine', isInfinity: true, x: 0n, y: 0n };
if (P.type === 'affine')
return P;
if (P.z === 0n)
return { type: 'affine', isInfinity: true, x: 0n, y: 0n };
if (P.z === 1n)
return { type: 'affine', isInfinity: false, x: mod(P.x), y: mod(P.y) };
if (P.type !== 'jacobian' && P.type !== 'ld')
throw new KitError('Invalid point type');
let x = 0n;
let y = 0n;
const z_inv = inv(P.z);
const z_inv2 = squ(z_inv);
if (P.type === 'jacobian') {
const z_inv3 = mul(z_inv2, z_inv);
x = mul(P.x, z_inv2);
y = mul(P.y, z_inv3);
}
else if (P.type === 'ld') {
x = mul(P.x, z_inv);
y = mul(P.y, z_inv2); // y = Y / Z^2
}
return { type: 'affine', isInfinity: false, x, y };
};
function toJacobian(P, Z = 1n) {
if (!P || P.isInfinity || Z === 0n)
return { type: 'jacobian', isInfinity: true, x: 1n, y: 1n, z: 0n };
if (P.type === 'jacobian')
return P;
let { x, y } = P;
if (Z === 1n)
return { type: 'jacobian', isInfinity: false, x, y, z: Z };
const ZZ = squ(Z);
const ZZZ = mul(ZZ, Z);
x = mul(x, ZZ);
y = mul(y, ZZZ);
return { type: 'jacobian', isInfinity: false, x, y, z: Z };
}
function toLD(P, Z = 1n) {
if (!P || P.isInfinity)
return { type: 'ld', isInfinity: true, x: 1n, y: 1n, z: 0n };
if (P.type === 'ld')
return P;
let { x, y } = P;
if (Z === 1n)
return { type: 'ld', isInfinity: false, x, y, z: Z };
const ZZ = squ(Z);
x = mul(x, Z);
y = mul(y, ZZ);
return { type: 'ld', isInfinity: false, x, y, z: Z };
}
return {
toAffine,
toJacobian,
toLD,
};
}