40 lines
1.2 KiB
JavaScript
40 lines
1.2 KiB
JavaScript
import * as blst from "@chainsafe/blst";
|
|
import { bytesToHex, hexToBytes, isZeroUint8Array, randomBytes } from "../helpers/index.js";
|
|
import { SECRET_KEY_LENGTH } from "../constants.js";
|
|
import { PublicKey } from "./publicKey.js";
|
|
import { Signature } from "./signature.js";
|
|
import { ZeroSecretKeyError } from "../errors.js";
|
|
export class SecretKey {
|
|
constructor(value) {
|
|
this.value = value;
|
|
}
|
|
static fromBytes(bytes) {
|
|
// draft-irtf-cfrg-bls-signature-04 does not allow SK == 0
|
|
if (isZeroUint8Array(bytes)) {
|
|
throw new ZeroSecretKeyError();
|
|
}
|
|
const sk = blst.SecretKey.fromBytes(bytes);
|
|
return new SecretKey(sk);
|
|
}
|
|
static fromHex(hex) {
|
|
return this.fromBytes(hexToBytes(hex));
|
|
}
|
|
static fromKeygen(entropy) {
|
|
const sk = blst.SecretKey.fromKeygen(entropy || randomBytes(SECRET_KEY_LENGTH));
|
|
return new SecretKey(sk);
|
|
}
|
|
sign(message) {
|
|
return new Signature(this.value.sign(message).value);
|
|
}
|
|
toPublicKey() {
|
|
const pk = this.value.toPublicKey();
|
|
return new PublicKey(pk.value);
|
|
}
|
|
toBytes() {
|
|
return this.value.toBytes();
|
|
}
|
|
toHex() {
|
|
return bytesToHex(this.toBytes());
|
|
}
|
|
}
|