在javascript中加密对象 [英] encrypting an object in javascript

查看:128
本文介绍了在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. 我应该在对象之前或之后对对象进行加密。

  2. 在javascript中加密对象的方法有哪些。任何示例
    都会很棒。


推荐答案

你无法真正加密对象,但你可以加密字符串,所以你应该首先做一个对象序列化( JSON.stringify )然后用对称加密算法加密它,这样你就可以解码这个对象以后。

我真的不能提供一个很好的例子,因为javascript总会有严重的安全问题(作为客户端编程语言),即使你尝试了一个相当复杂的算法(如如 AES )它仍然容易受到攻击,因为用户只能看到您的源代码,因此请参阅你的编码/解密算法。

如果你只是想稍微改变字符串以便在第一眼看就无法解密,你可以简单地使用一些内置的javascript方法(例如encodeURI / decodeURI)或者你可以做一些字符repl acements甚至使用 salts

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 encript(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 decript(o, salt) {
    o = decodeURI(o);
    if(salt && o.indexOf(salt) != 0)
        throw new Error('object cannot be decripted');
    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 encripted = encript(obj, salt);
var decripted = decript(encripted, salt);

当然,这只是一个例子,您应该修改它以便识别更复杂的对象,你需要ecnript函数,或者对象有循环引用的地方。

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

这篇关于在javascript中加密对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆