UNPKG

@dedis/kyber

Version:

A typescript implementation of Kyber interfaces

118 lines (117 loc) 3.35 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); // tslint:disable:no-bitwise const bn_js_1 = __importDefault(require("bn.js")); const crypto_browserify_1 = require("crypto-browserify"); const random_1 = require("../../random"); class NistScalar { constructor(curve, red) { this.ref = { arr: new bn_js_1.default(0, 16).toRed(red), curve, red, }; } /** @inheritdoc */ set(a) { this.ref = a.ref; return this; } /** @inheritdoc */ clone() { return new NistScalar(this.ref.curve, this.ref.red).setBytes(Buffer.from(this.ref.arr.fromRed().toArray("be"))); } /** @inheritdoc */ zero() { this.ref.arr = new bn_js_1.default(0, 16).toRed(this.ref.red); return this; } /** @inheritdoc */ add(s1, s2) { this.ref.arr = s1.ref.arr.redAdd(s2.ref.arr); return this; } /** @inheritdoc */ sub(s1, s2) { this.ref.arr = s1.ref.arr.redSub(s2.ref.arr); return this; } /** @inheritdoc */ neg(a) { this.ref.arr = a.ref.arr.redNeg(); return this; } /** @inheritdoc */ one() { this.ref.arr = new bn_js_1.default(1, 16).toRed(this.ref.red); return this; } /** @inheritdoc */ mul(s1, s2) { this.ref.arr = s1.ref.arr.redMul(s2.ref.arr); return this; } /** @inheritdoc */ div(s1, s2) { this.ref.arr = s1.ref.arr.redMul(s2.ref.arr.redInvm()); return this; } /** @inheritdoc */ inv(a) { this.ref.arr = a.ref.arr.redInvm(); return this; } /** @inheritdoc */ setBytes(b) { this.ref.arr = new bn_js_1.default(b, 16, "be").toRed(this.ref.red); return this; } /** @inheritdoc */ bytes() { return Buffer.from(this.ref.arr.fromRed().toArray("be")); } /** @inheritdoc */ pick(callback) { callback = callback || crypto_browserify_1.randomBytes; const bytes = random_1.int(this.ref.curve.curve.n, callback); this.setBytes(bytes); return this; } /** @inheritdoc */ marshalSize() { return this.ref.curve.scalarLen(); } /** @inheritdoc */ marshalBinary() { return Buffer.from(this.ref.arr.fromRed().toArray("be", this.ref.curve.scalarLen())); } /** @inheritdoc */ unmarshalBinary(bytes) { if (bytes.length !== this.marshalSize()) { throw new Error("bytes.length > marshalSize"); } const bnObj = new bn_js_1.default(bytes, 16); if (bnObj.cmp(this.ref.curve.curve.n) > 0) { throw new Error("bytes > q"); } this.setBytes(bytes); } /** @inheritdoc */ equals(s2) { return this.ref.arr.fromRed().cmp(s2.ref.arr.fromRed()) === 0; } /** @inheritdoc */ toString() { const bytes = Buffer.from(this.ref.arr.fromRed().toArray("be")); return Array.from(bytes, (b) => { return ("0" + (b & 0xff).toString(16)).slice(-2); }).join(""); } inspect() { return this.toString(); } } exports.default = NistScalar;