Skip to content

Instantly share code, notes, and snippets.

@themikefuller
Created September 28, 2023 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save themikefuller/d4fbfbd11dfd41f32df04fa07002703e to your computer and use it in GitHub Desktop.
Save themikefuller/d4fbfbd11dfd41f32df04fa07002703e to your computer and use it in GitHub Desktop.
Code pulled from https://github.com/StarbaseAlpha/Cryptic to give encryption example (without library)
async function Example() {
const encode = (byteArray) => {
return btoa(Array.from(new Uint8Array(byteArray)).map(val => {
return String.fromCharCode(val);
}).join('')).replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
const createECDH = async (curve = "P-256") => {
let DH = await crypto.subtle.generateKey({
"name": "ECDH",
"namedCurve": curve
}, true, ['deriveBits']);
let pub = await crypto.subtle.exportKey('spki', DH.publicKey);
let key = await crypto.subtle.exportKey('pkcs8', DH.privateKey);
return {
"pub": encode(pub),
"key": encode(key)
};
};
const decode = (str) => {
return new Uint8Array(atob(str.replace(/\_/g, '/').replace(/\-/g, '+')).split('').map(val => {
return val.charCodeAt(0);
}));
};
const fromText = (string) => {
return new TextEncoder().encode(string);
};
const random = (size) => {
return crypto.getRandomValues(new Uint8Array(size));
};
const pbkdf2 = async (bits, salt, iterations = 1, size = 256, hashAlg = "SHA-256") => {
let key = await crypto.subtle.importKey('raw', bits, {
"name": "PBKDF2"
}, false, ['deriveBits']);
let result = await crypto.subtle.deriveBits({
"name": "PBKDF2",
"salt": salt,
"iterations": iterations,
"hash": hashAlg
}, key, size);
return encode(result);
};
const encrypt = async (plaintext, bits, AD = null) => {
let key = await crypto.subtle.importKey('raw', bits, {
"name": "AES-GCM"
}, false, ['encrypt']);
let iv = random(12);
let msg = fromText(plaintext);
let cipher = await crypto.subtle.encrypt({
"name": "AES-GCM",
"iv": iv,
"additionalData": AD || fromText('')
}, key, msg);
return encode(iv) + '.' + encode(cipher);
};
const passwordEncrypt = async (message, password = "", iterations = 100000) => {
let salt = random(32);
let keyBits = await pbkdf2(fromText(password), salt, iterations, 256);
let encrypted = await encrypt(message, decode(keyBits));
return encode(fromText(iterations.toString())) + '.' + encode(salt) + '.' + encrypted;
};
let keys = await createECDH()
let sealed = await passwordEncrypt(keys.key, "password", 100000);
console.log(keys);
console.log(sealed);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment