}
export class Tools {
+ static #encoder: TextEncoder = new TextEncoder()
+ static #normalize (input: string | ArrayBuffer | Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {
+ return (typeof input === 'string')
+ ? hex.toBytes(input)
+ : input instanceof ArrayBuffer
+ ? new Uint8Array(input.slice())
+ : input
+ }
/**
* Converts a decimal amount of nano from one unit divider to another.
*
* Concatenates and signs an arbitrary set of strings with a secret key using
* nano25519. The input data can be up to 32 KiB in total.
*
- * @param {string} secretKey - 64-byte hexadecimal secret key
+ * @param {(string | ArrayBuffer | Uint8Array<ArrayBuffer>)} secretKey - 64-byte secret key
* @param {...string[]} input - Data to be concatenated and then signed
* @returns {string} 64-byte hexadecimal signature
*/
- static sign (secretKey: string, ...input: string[]): string {
+ static sign (secretKey: string | ArrayBuffer | Uint8Array<ArrayBuffer>, ...input: string[]): string {
+ const k = this.#normalize(secretKey)
try {
- const signature = nano25519_sign(input.join(''), secretKey)
- return signature
+ const signature = nano25519_sign(this.#encoder.encode(input.join('')), k)
+ return bytes.toHex(signature)
} catch (err) {
throw new Error(`Failed to sign message`, { cause: err })
+ } finally {
+ k.fill(0)
}
}
/**
* Verifies the signature of arbitrary strings using a public key.
*
- * @param {string} publicKey - 64-character hexadecimal public key
- * @param {string} signature - 128-character hexadcimal signature
+ * @param {(string | ArrayBuffer | Uint8Array<ArrayBuffer>)} publicKey - 32-byte hexadecimal public key
+ * @param {(string | ArrayBuffer | Uint8Array<ArrayBuffer>)} signature - 128-character hexadcimal signature
* @param {...string} input - Data to be verified
* @returns {boolean} True if the data was signed by the public key's matching private key
*/
- static verify (publicKey: string, signature: string, ...input: string[]): boolean {
+ static verify (publicKey: string | ArrayBuffer | Uint8Array<ArrayBuffer>, signature: string | ArrayBuffer | Uint8Array<ArrayBuffer>, ...input: string[]): boolean {
+ const k = this.#normalize(publicKey)
+ const s = this.#normalize(signature)
try {
- return nano25519_verify(signature, input.join(''), publicKey)
+ return nano25519_verify(s, this.#encoder.encode(input.join('')), k)
} catch (err) {
throw new Error('Failed to verify signature', { cause: err })
}