Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created September 17, 2019 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/b8d79aecf4b55168530e6b9a57d10e6a to your computer and use it in GitHub Desktop.
Save NickStrupat/b8d79aecf4b55168530e6b9a57d10e6a to your computer and use it in GitHub Desktop.
Small class for generating public-private key pairs, signing, and verifying signatures
import { sign } from "tweetnacl"
import { decodeUTF8 } from "tweetnacl-util";
export class Crypto {
private constructor() {}
static generateKeys(): CryptoKeyPair {
const naclKeyPair = sign.keyPair();
return new CryptoKeyPair(naclKeyPair.publicKey, naclKeyPair.secretKey);
}
static sign(message: string | Uint8Array, privateKey: Uint8Array): Uint8Array {
const bytes = typeof message == 'string' ? decodeUTF8(message) : message;
const signature = sign.detached(bytes, privateKey);
return signature;
}
static verify(message: string | Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean {
const bytes = typeof message == 'string' ? decodeUTF8(message) : message;
return sign.detached.verify(bytes, signature, publicKey);
}
}
export class CryptoKeyPair {
constructor(
readonly publicKey: Uint8Array,
readonly privateKey: Uint8Array
) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment