Skip to content

Instantly share code, notes, and snippets.

@zapalote
Last active October 4, 2021 11:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zapalote/7deff5056e16e9e373b380db8c3d0f68 to your computer and use it in GitHub Desktop.
Save zapalote/7deff5056e16e9e373b380db8c3d0f68 to your computer and use it in GitHub Desktop.
Credential obfuscation and encryption to store then on a database
<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