Skip to content

Instantly share code, notes, and snippets.

Mike Fuller themikefuller

View GitHub Profile
@themikefuller
themikefuller / aes-gcm.js
Created Oct 15, 2018
AES-GCM Encryption and Decryption Examples using Web Crypto (subtle.crypto) JavaScript API
View aes-gcm.js
async function generateKey() {
return await crypto.subtle.generateKey({
"name":"AES-GCM",
"length":256
},true,['encrypt','decrypt']);
}
async function exportKey(key) {
return await crypto.subtle.exportKey('jwk', key);
}
@themikefuller
themikefuller / hexencoding.js
Created Oct 15, 2018
Encoding and decoding strings into hex encoding.
View hexencoding.js
function string2hex(text) {
let encoded = new TextEncoder().encode(text);
let hex = Array.from(encoded).map(val=>{
return ('00' + val.toString(16)).slice(-2);
}).join('');
return hex;
}
function hex2string(hex) {
let byteArray = new Uint8Array(hex.match(/.{0,2}/g).map(val=>{
@themikefuller
themikefuller / base64url.js
Created Oct 15, 2018
Encode and decode byte arrays to and from base64url encoding in JavaScript.
View base64url.js
function base64EncodeURL(byteArray) {
return btoa(Array.from(new Uint8Array(byteArray)).map(val => {
return String.fromCharCode(val);
}).join('')).replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
}
function base64DecodeURL(b64urlstring) {
return new Uint8Array(atob(b64urlstring.replace(/-/g, '+').replace(/_/g, '/')).split('').map(val => {
return val.charCodeAt(0);
}));
@themikefuller
themikefuller / sha.js
Created Oct 15, 2018
SHA-1 and SHA-256 Hash Function in JavaScript using crypto.subtle.digest
View sha.js
async function SHA1(text) {
let data = new TextEncoder().encode(text.toString());
let digest = await crypto.subtle.digest("SHA-1",data);
return Array.from(new Uint8Array(digest)).map(val=>{return ('00' + val.toString(16)).slice(-2)}).join('');
}
async function SHA256(text) {
let data = new TextEncoder().encode(text.toString());
let digest = await crypto.subtle.digest("SHA-256",data);
return Array.from(new Uint8Array(digest)).map(val=>{return ('00' + val.toString(16)).slice(-2)}).join('');
You can’t perform that action at this time.