Skip to content

Instantly share code, notes, and snippets.

@mikroskeem
Created November 13, 2023 10:05
Show Gist options
  • Save mikroskeem/0f330f570e8f5e95d4e983470667c19a to your computer and use it in GitHub Desktop.
Save mikroskeem/0f330f570e8f5e95d4e983470667c19a to your computer and use it in GitHub Desktop.
ed25519 signing with Vault Transit engine
{
"imports": {
"$std/": "https://deno.land/std@0.206.0/",
"vault/": "https://raw.githubusercontent.com/restake/deno-hashicorp-vault/67b015694251a9f030bc419296c93e8900ebff84/",
"@noble/ed25519": "https://deno.land/x/ed25519@2.0.0/mod.ts"
},
"fmt": {
"indentWidth": 4,
"lineWidth": 140
}
}
import { VAULT_AUTH_TYPE, VaultClient, VaultCredentials, VaultTokenCredentials } from "vault/mod.ts";
import { z } from "vault/deps.ts";
import * as ed from "@noble/ed25519";
import { decodeBase64, encodeBase64 } from "$std/encoding/base64.ts";
// vault server -dev -dev-no-store-token -dev-root-token-id=foobarbaz123
const creds: VaultCredentials = {
address: "http://127.0.0.1:8200",
namespace: undefined,
authentication: <VaultTokenCredentials> {
[VAULT_AUTH_TYPE]: "token",
mountpoint: "auth/token",
token: "foobarbaz123",
},
};
const vault = new VaultClient(creds);
await vault.login();
addEventListener("unload", () => {
vault.logout();
});
const transit = `transit`;
const keyName = `testing`;
await vault.write(undefined, `sys/mounts/${transit}`, { type: "transit" });
const { data: { keys } } = await vault.write(
z.any(),
`${transit}/keys/${keyName}`,
{
exportable: true,
type: "ed25519",
},
);
// Grab newly generated public key
const publicKeyBase64: string = Object.values<any>(keys)[0].public_key;
const publicKey = decodeBase64(publicKeyBase64);
console.log(publicKeyBase64);
// Create a sample message
const message = new TextEncoder().encode("foo bar baz");
// Vault requires input to be base64 encoded, but luckily it will decode it before signing
const messageB64 = encodeBase64(message);
const { data: { signature } } = await vault.write(
z.any(),
`${transit}/sign/${keyName}`,
{
input: messageB64,
},
);
// Extract raw signature from the data
const signatureDataBase64 = signature.split(":", 3)[2];
const signatureData = decodeBase64(signatureDataBase64);
// Verify signature outside Vault
console.log(
"verified =",
await ed.verifyAsync(signatureData, message, publicKey),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment