Created
September 17, 2019 19:30
-
-
Save NickStrupat/b8d79aecf4b55168530e6b9a57d10e6a to your computer and use it in GitHub Desktop.
Small class for generating public-private key pairs, signing, and verifying signatures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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