actions-test/src/sys/crypto.ts

57 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-02-28 14:44:10 +01:00
import crypto from "crypto";
export const sha256 = (d: any) => crypto.createHash('sha256').update(String(d)).digest('base64');
export const encode = (data: any, type: BufferEncoding = "binary") => {
return new Uint8Array(Buffer.from(data, type));
};
export const decode = (data: any, type: BufferEncoding = "binary") => {
return Buffer.from(data).toString(type);
};
export const generateSigningKey = async () => {
var keyPair = await crypto.webcrypto.subtle.generateKey(
{ name: "RSA-PSS", modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
true,
["sign", "verify"]
);
return {
privateKey: decode(new Uint8Array(await crypto.webcrypto.subtle.exportKey("pkcs8", keyPair.privateKey)), "base64"),
publicKey: decode(new Uint8Array(await crypto.webcrypto.subtle.exportKey("spki", keyPair.publicKey)), "base64")
};
};
export const sign = async (message: string, privateKey: string) => {
var rawdata = encode(message);
var rawkey = await crypto.webcrypto.subtle.importKey("pkcs8", encode(privateKey, "base64"), { name: "RSA-PSS", hash: "SHA-256" }, true, ["sign"]);
var step = await crypto.webcrypto.subtle.sign(
{
name: "RSA-PSS",
saltLength: 32,
},
rawkey,
rawdata
);
return decode(new Uint8Array(step), "base64");
};
export const verify = async (message: string, signature: string, publicKey: string) => {
var rawdata = encode(message);
var rawsig = encode(signature, "base64");
var rawkey = await crypto.webcrypto.subtle.importKey("spki", encode(publicKey, "base64"), { name: "RSA-PSS", hash: "SHA-256" }, true, ["verify"]);
var step = await crypto.webcrypto.subtle.verify(
{
name: "RSA-PSS",
saltLength: 32,
},
rawkey,
rawsig,
rawdata
);
return step//; ? "valid" : "invalid";
}