Update with our own SimpleSigner

This commit is contained in:
Matthew Aaron Raymer
2023-01-06 17:30:41 +08:00
parent 39c931cde9
commit 150b35c4c7
2 changed files with 100 additions and 32 deletions

View File

@@ -5,8 +5,44 @@ import { entropyToMnemonic } from "ethereum-cryptography/bip39";
import { wordlist } from "ethereum-cryptography/bip39/wordlists/english";
import { HDNode } from "@ethersproject/hdnode";
import * as didJwt from "did-jwt";
import { Signer } from "did-jwt";
import * as u8a from "uint8arrays";
export function hexToBytes(s: string): Uint8Array {
const input = s.startsWith("0x") ? s.substring(2) : s;
return u8a.fromString(input.toLowerCase(), "base16");
}
export function fromJose(signature: string): {
r: string;
s: string;
recoveryParam?: number;
} {
const signatureBytes: Uint8Array = base64ToBytes(signature);
if (signatureBytes.length < 64 || signatureBytes.length > 65) {
throw new TypeError(
`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`
);
}
const r = bytesToHex(signatureBytes.slice(0, 32));
const s = bytesToHex(signatureBytes.slice(32, 64));
const recoveryParam =
signatureBytes.length === 65 ? signatureBytes[64] : undefined;
return { r, s, recoveryParam };
}
export function bytesToHex(b: Uint8Array): string {
return u8a.toString(b, "base16");
}
export function base64ToBytes(s: string): Uint8Array {
const inputBase64Url = s
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
return u8a.fromString(inputBase64Url, "base64url");
}
/**
*
*
@@ -111,3 +147,23 @@ export const sign = async (privateKeyHex: string) => {
return signer;
};
/**
* The SimpleSigner returns a configured function for signing data.
*
* @example
* const signer = SimpleSigner(process.env.PRIVATE_KEY)
* signer(data, (err, signature) => {
* ...
* })
*
* @param {String} hexPrivateKey a hex encoded private key
* @return {Function} a configured signer function
*/
export const SimpleSigner = async (hexPrivateKey: string): Promise<Signer> => {
const signer = didJwt.ES256KSigner(hexToBytes(hexPrivateKey), true);
return async (data) => {
const signature = (await signer(data)) as string;
return fromJose(signature);
};
};