Skip to content

Instantly share code, notes, and snippets.

@zapalote
Created May 1, 2021 14:33
Show Gist options
  • Save zapalote/febebd36d333cad2e86d3002366e0f9c to your computer and use it in GitHub Desktop.
Save zapalote/febebd36d333cad2e86d3002366e0f9c to your computer and use it in GitHub Desktop.
Obfuscate and encrypt API credentials before storing
// 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment