-
-
Save sakibguy/6088bb14f11ce89f7dcf40ff09e7ef4c to your computer and use it in GitHub Desktop.
Credential obfuscation and encryption to store then on a database
This file contains hidden or 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
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script> | |
<script> | |
// used to obfuscate and encrypt the credentials | |
const saltCredentials = "jf02heg9u64a{%m<83#@;Pxrjg17uyr#@&*%^Y"; | |
// encode credentials before storing | |
function encodeCredentials(crds){ | |
// json object expected e.g. {'api-id':'K0xf56g', 'pwd':'Some.Pa$$w0rd'} | |
const crd = JSON.stringify(crds); | |
const len = crd.length; | |
// this constraint is due to storing the length in one byte | |
if (len > 159) return null; | |
let s = Array.from(saltCredentials); | |
let i = 0, j = 2, step = Math.floor(s.length / len); | |
// make sure the pepper is well salted (at least 3 bytes in between) | |
while(step <= 2){ | |
s = s.concat(s.reverse()); | |
step = Math.floor(s.length / len); | |
} | |
// encode length and step in the first two bytes | |
s.splice(0, 0, String.fromCharCode(96 + len)); | |
s.splice(1, 0, String.fromCharCode(96 + step)); | |
// pepper the salt | |
while( i < len ){ | |
s.splice(j, 0, crd.charAt(i++)); | |
j += step; | |
} | |
// AES encrypt to wrap it up | |
return CryptoJS.AES.encrypt(s.join(''), saltCredentials).toString(); | |
} | |
// decode credentials upon receiving them from store | |
function decodeCredentials(crd){ | |
// decrypt it first | |
const dec = CryptoJS.AES.decrypt(crd, saltCredentials).toString(CryptoJS.enc.Utf8); | |
// extract the creds length and pepper step | |
const len = dec.charCodeAt(0) - 96; | |
const step = dec.charCodeAt(1) - 96; | |
let i = 0, j = 2, d = []; | |
// extract the pepper from the salt | |
while( i < len ){ | |
d[i++] = dec[j]; | |
j += step; | |
} | |
// return the json object | |
return JSON.parse(d.join('')); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment