A music player that connects to your cloud/distributed storage.
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

at df22eb08f006cc55f4e454a905fb314660883ed9 120 lines 2.1 kB view raw
1// 2// Cryptography 3// \ (•◡•) / 4// 5// Data encryption & decryption. 6 7 8const crypto = (self.crypto || self.msCrypto) 9const extractable = false 10 11 12export function keyFromPassphrase(passphrase) { 13 return crypto.subtle.importKey( 14 "raw", 15 stringToArrayBuffer(passphrase), 16 { 17 name: "PBKDF2" 18 }, 19 false, 20 [ "deriveKey" ] 21 22 ).then(baseKey => crypto.subtle.deriveKey( 23 { 24 name: "PBKDF2", 25 salt: stringToArrayBuffer("diffuse"), 26 iterations: 10000, 27 hash: "SHA-512" 28 }, 29 baseKey, 30 { 31 name: "AES-GCM", 32 length: 256 33 }, 34 extractable, 35 [ "encrypt", "decrypt" ] 36 37 )) 38} 39 40 41export function encrypt(key, string) { 42 let iv = crypto.getRandomValues(new Uint8Array(12)) 43 44 return crypto.subtle.encrypt( 45 { 46 name: "AES-GCM", 47 iv: iv, 48 tagLength: 128 49 }, 50 key, 51 stringToArrayBuffer(string) 52 53 ).then(buf => { 54 const iv_b64 = arrayBufferToBase64(iv) 55 const buf_b64 = arrayBufferToBase64(buf) 56 return iv_b64 + buf_b64 57 58 }) 59} 60 61 62export function decrypt(key, string) { 63 const iv_b64 = string.substring(0, 16) 64 const buf_b64 = string.substring(16) 65 66 const iv = base64ToArrayBuffer(iv_b64) 67 const buf = base64ToArrayBuffer(buf_b64) 68 69 return crypto.subtle.decrypt( 70 { 71 name: "AES-GCM", 72 iv: iv, 73 tagLength: 128 74 }, 75 key, 76 buf 77 78 ).then( 79 arrayBufferToString 80 81 ) 82} 83 84 85 86// Buffers 87// ------- 88 89function arrayBufferToBase64(buffer) { 90 const uint8 = new Uint8Array(buffer) 91 let string = "" 92 93 for (let i = 0; i < uint8.byteLength; i++) { 94 string = string + String.fromCharCode( uint8[i] ) 95 } 96 97 return self.btoa(string) 98} 99 100 101function arrayBufferToString(buffer) { 102 return new TextDecoder("UTF-8").decode(buffer) 103} 104 105 106function base64ToArrayBuffer(base64) { 107 const string = self.atob(base64) 108 const bytes = new Uint8Array(string.length) 109 110 for (let i = 0; i < string.length; i++) { 111 bytes[i] = string.charCodeAt(i) 112 } 113 114 return bytes.buffer 115} 116 117 118function stringToArrayBuffer(string) { 119 return new TextEncoder("UTF-8").encode(string).buffer 120}