@gleif-it/did-webs-ts
Version:
did-webs typescript library
27 lines (26 loc) • 1.1 kB
JavaScript
import * as R from 'remeda';
import { isValidEd25519Cesr } from '../validators/isValidEd25519Cesr.js';
import { isValidSecp256k1Cesr } from '../validators/isValidSecp256k1Cesr.js';
import { base64UrlToBytes } from '../conversions/base64UrlToBytes.js';
import { bytesToBase64Url } from '../conversions/bytesToBase64Url.js';
const ps = (N) => (3 - (N % 3)) % 3;
const padBytes = (bytes) => {
const padding = ps(bytes.length);
const paddedBytes = new Uint8Array(bytes.length + padding);
paddedBytes.set(bytes, padding); // padding is the offset, this will leave the initialized zeros at the beginning
return paddedBytes;
};
const encodeWith = (code) => (rawB64) => {
if (code[0] === '1') {
return `${code}${rawB64}`;
}
else {
return `${code}${rawB64.slice(code.length)}`;
}
};
export const encodeKey = (code, decodedKey) => {
const key = R.pipe(decodedKey, base64UrlToBytes, padBytes, bytesToBase64Url, encodeWith(code));
if (isValidEd25519Cesr(key) || isValidSecp256k1Cesr(key))
return key;
throw new Error("Can't encode key");
};