开发者

encrypting an object in javascript

var Obj = {};
Obj.ID = e.row.ID;
Obj.firstName = e.row.firstName;
Obj.lastName = e.row.lastName;

This is my object, and i save this object in a file. now before saving into file, i want to encrypt it and save and while reading i want to decrypt and read.

var newFile = FileSystemPath;
newFile.write(JSON.stringify(object));
  1. Should i encrypt开发者_如何学编程 the object before stringifying it or after it.
  2. What are the ways to encrypt an object in javascript. Any examples would be great.


You can't really encrypt objects, but you can encrypt strings, so you should probably first do a object serialization (JSON.stringify) and then encrypt it with a symmetric encryption algorithm so you would be able to decode the object later.
I can't really provide a good example, because javascript will always have serious security problems (being a client-side programming language), and even if you try a rather complex algorithm (such as AES) it will still be vulnerable, because the user can just see your source code, thus see your encription/decription algorithms.
If you just want to alter the string a bit so it can't be deciphered on the first look, you can simply use some built-in javascript methods (such as encodeURI/decodeURI) or you can do some character replacements or even use salts.

Here's a sample demo of how you can "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);

Of course, this is just an example and you should modify it in order to encrypt more complex objects, where you need to encrypt functions, or where the object has circular references.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜