Encrypting objects directly is not feasible, but you can encrypt strings instead. To achieve this, you should serialize the object using JSON.stringify
and then apply a symmetric encryption algorithm. This way, you can decrypt the object later on.
Providing a concrete example is challenging due to security risks inherent in JavaScript as a client-side language. Even with a sophisticated algorithm like AES, vulnerabilities remain as users can access your source code and decryption process.
If your goal is to obfuscate the string rather than create a completely secure encryption, JavaScript methods like encodeURI/decodeURI or character replacements, as well as using salts, can be used.
Check out this demo showcasing a basic way to "encrypt" an object:
function encrypt(o, salt) {
o = JSON.stringify(o).split('');
for(var i = 0, l = o.length; i < l; i++)
if(o[i] == '{')
o[i] = '}';
else if(o[i] == '}')
o[i] = '{';
return encodeURI(salt + o.join(''));
}
function decrypt(o, salt) {
o = decodeURI(o);
if(salt && o.indexOf(salt) != 0)
throw new Error('object cannot be decrypted');
o = o.substring(salt.length).split('');
for(var i = 0, l = o.length; i < l; i++)
if(o[i] == '{')
o[i] = '}';
else if(o[i] == '}')
o[i] = '{';
return JSON.parse(o.join(''));
}
var obj = {
key : 'value',
3 : 1
};
var salt = "some string here";
var encrypted = encrypt(obj, salt);
var decrypted = decrypt(encripted, salt);
Keep in mind that this code snippet is a simplistic example. Adjustments may be needed for more complex objects, especially those containing functions or circular references.