anproto -- authenticated non-networked protocol or another proto sha256 blobs signed with ed25519 keypairs anproto.com
ed25519 social protocols
at main 2.0 kB view raw
1// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. 2// This module is browser compatible. 3 4const base64abc = [ 5 "A", 6 "B", 7 "C", 8 "D", 9 "E", 10 "F", 11 "G", 12 "H", 13 "I", 14 "J", 15 "K", 16 "L", 17 "M", 18 "N", 19 "O", 20 "P", 21 "Q", 22 "R", 23 "S", 24 "T", 25 "U", 26 "V", 27 "W", 28 "X", 29 "Y", 30 "Z", 31 "a", 32 "b", 33 "c", 34 "d", 35 "e", 36 "f", 37 "g", 38 "h", 39 "i", 40 "j", 41 "k", 42 "l", 43 "m", 44 "n", 45 "o", 46 "p", 47 "q", 48 "r", 49 "s", 50 "t", 51 "u", 52 "v", 53 "w", 54 "x", 55 "y", 56 "z", 57 "0", 58 "1", 59 "2", 60 "3", 61 "4", 62 "5", 63 "6", 64 "7", 65 "8", 66 "9", 67 "+", 68 "/", 69]; 70 71/** 72 * CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727 73 * Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation 74 * @param data 75 */ 76export function encode(data) { 77 const uint8 = typeof data === "string" 78 ? new TextEncoder().encode(data) 79 : data instanceof Uint8Array 80 ? data 81 : new Uint8Array(data); 82 let result = "", 83 i; 84 const l = uint8.length; 85 for (i = 2; i < l; i += 3) { 86 result += base64abc[uint8[i - 2] >> 2]; 87 result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)]; 88 result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)]; 89 result += base64abc[uint8[i] & 0x3f]; 90 } 91 if (i === l + 1) { 92 // 1 octet yet to write 93 result += base64abc[uint8[i - 2] >> 2]; 94 result += base64abc[(uint8[i - 2] & 0x03) << 4]; 95 result += "=="; 96 } 97 if (i === l) { 98 // 2 octets yet to write 99 result += base64abc[uint8[i - 2] >> 2]; 100 result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)]; 101 result += base64abc[(uint8[i - 1] & 0x0f) << 2]; 102 result += "="; 103 } 104 return result; 105} 106 107/** 108 * Decodes a given RFC4648 base64 encoded string 109 * @param b64 110 */ 111export function decode(b64) { 112 const binString = atob(b64); 113 const size = binString.length; 114 const bytes = new Uint8Array(size); 115 for (let i = 0; i < size; i++) { 116 bytes[i] = binString.charCodeAt(i); 117 } 118 return bytes; 119}