Last active
April 30, 2023 03:20
-
-
Save allenhwkim/d09fffab9959fdfc44ea3ddee822cd76 to your computer and use it in GitHub Desktop.
NodeJS Compress / Encrypt / Base64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as crypto from 'crypto'; | |
import * as zlib from 'zlib'; | |
const assert = require('assert'); | |
const encrypt = (val, password='p@55w07d') => { | |
const key = password.repeat(16).substring(0, 32); | |
const iv = key.substring(0, 16).split('').reverse().join(''); | |
let cipher = crypto.createCipheriv('aes-256-cbc', key, iv); | |
let encrypted = cipher.update(val, 'utf8', 'base64'); | |
return (encrypted + cipher.final('base64')).replace(/[=]+/,''); | |
}; | |
const decrypt = (encrypted, password='p@55w07d') => { | |
const key = password.repeat(16).substring(0, 32); | |
const iv = key.substring(0, 16).split('').reverse().join(''); | |
let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); | |
let decrypted = decipher.update(encrypted, 'base64', 'utf8'); | |
return (decrypted + decipher.final('utf8')); | |
}; | |
const fromBase64 = (base64) => { | |
return Buffer.from(base64, 'base64').toString('ascii'); | |
}; | |
const toBase64 = (string) => { | |
return Buffer.from(string).toString('base64').replace(/[=]+/,'');; | |
}; | |
const compress = (string) => { | |
return zlib.brotliCompressSync(string).toString('base64').replace(/[=]+/,'');; | |
} | |
const decompress = (base64) => { | |
return zlib.brotliDecompressSync(Buffer.from(base64, 'base64')).toString(); | |
} | |
var token = 'eyJ0eXAiOiJKV1QiLCJraWQiOiI0aUNLRkIwUlhJeHl0b3IxcjNUb0JkUmlldnM9IiwiYWxnIjoiUlMyNTYifQ'; | |
var encrypted = encrypt(token) | |
var compressed = compress(encrypted) | |
var decompressed = decompress(compressed) | |
var decrypted = decrypt(decompressed); | |
assert.equal(token, decrypted); | |
assert(encrypt('Hello World') === 'FTGJzypffFrKHr6+UKlY7g'); | |
assert(decrypt('FTGJzypffFrKHr6+UKlY7g') === 'Hello World'); | |
assert(toBase64('Hello World') === 'SGVsbG8gV29ybGQ'); | |
assert(fromBase64('SGVsbG8gV29ybGQ') === 'Hello World'); | |
assert(compress('Hello World') === 'CwWASGVsbG8gV29ybGQD'); | |
assert(decompress('CwWASGVsbG8gV29ybGQD') === 'Hello World'); | |
export { compress, decompress, fromBase64, toBase64, encrypt, decrypt}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment