翻译【Appcelerator Blog】Arrow Encryption for Data in Transit(传输数据的Arrow加密)

我的原文所在 http://yanmin.in/archive.html

Arrow Encryption for Data in Transit


by Leor Brenman
翻译(卢彦民)
March 02, 2016 @ 6:00am

Appcelerator mobile apps use Secure Sockets Layer (SSL) for encrypting and decrypting all data transmitted and received by the device. However, for certain types of apps, one may wish to add another layer of encryption for added security. This post describes how to programmatically add additional encryption for data in transit between an Appcelerator app and an ArrowDB as illustrated below.

2016.03.02上午6:00

Appcelerator的移动应用程序使用安全套接字层(SSL)来加密和解密设备发送和接收的所有数据。然而,对于某些类型的应用程序,可能希望添加另一加密层来增加安全性。这篇文章介绍了如何以编程方式给在Appcelerator的应用程序和ArrowDB之间传输的数据增加额外的加密,正如下图所示。


Background

背景

The basic idea is to add a pre block to your Arrow model for decrypting data on a POST or PUT from the client app. This will decrypt data sent by the client app. Also, add a post block for encrypting data being sent to the client app on a GET.

其基本思想是给你的Arrow 模型为来自客户端的POST和PUT数据的解密添加一个pre block(解密块),这样将能解密客户端应用程序发送的数据。此外,为了被通过GET发送给客户端应用程序的数据的加密添加一个post block(加密块)

For the purpose of this post, we will use a very simple XOR encryption JavaScript function from Henry Algus which is also the decryption function and is shown below:

对于这篇文章的目的,我们将使用一个来自Henry Algus的非常简单的异或加密JavaScript方法,并且这个函数也是一个解密方法,如下所示:

exports.jsEncode = function(s,k) {
    var enc = "";
    var str = "";
    str = s.toString();
    for (var i = 0; i < s.length; i++) {
        var a = s.charCodeAt(i);
        var b = a ^ k;
        enc = enc + String.fromCharCode(b);
    }
    return enc;
}

Furthermore, since the Appcelerator Platform is a full stack JavaScript platform, this exact same function is used for both encryption and decryption in both the Appcelerator mobile app and the Arrow app.

此外,由于Appcelerator平台是一个完整的堆栈JavaScript平台,所以在Appcelerator移动应用和Arrow应用中的加密和解密中都可使用这一相同的方法。

Note that this XOR encryption should not be used for production apps and is strictly being used for demonstration purposes. In a production app, you may want to look at more secure encryption libraries such as the Appcelerator Premium “Crypto” Module, Securely, crypto-js or sjcl.

注意,这个异或加密不应该用于制作应用程序并且严格用于演示目的。在制作应用程序中,您可能想要看到更安全的加密库,例如Appcelerator Premium“CRypto”模块、Securely、crypto-js或sjcl。

Arrow Model

Arrow 模型

Here is a simple ArrowDB model, database, and a pre (decrypt) and post ((encrypt)) block that illustrates how to encrypt and decrypt data in Arrow:

这里是一个简单的ArrowDB模型、数据库和pre(解密)和post((加密))块,说明了如何在Arrow中加密和解密数据。

database.js

var Arrow = require("arrow");
var Model = Arrow.createModel("database",{
    "fields": {
        "name": {
            "type": "String"
        }
    },
    "connector": "appc.arrowdb",
    "actions": [
        "create",
        "read",
        "update",
        "delete",
        "deleteAll"
    ],
    "before": "decrypt",
    "after": "encrypt",
    "singular": "database",
    "plural": "databases"
});
module.exports = Model;

decrypt.js

var ENC_KEY = '123';
var Arrow = require('arrow');
var Utils = require('../lib/utils');
var PreBlock = Arrow.Block.extend({
    name: 'decrypt',
    description: 'will decrypt data from mobile app',
    action: function (req, resp, next) {
        if((req.method==="POST" || req.method==="PUT")) {
            req.params.name = Utils.jsEncode(req.params.name, ENC_KEY);
        }
        next();
    }
});
module.exports = PreBlock;

encrypt.js

var ENC_KEY = '123';
var Arrow = require('arrow');
var Utils = require('../lib/utils');
var PostBlock = Arrow.Block.extend({
    name: 'encrypt',
    description: 'will encrypt data to mobile app',
    action: function (req, resp, next) {
        if(req.method==="GET") {
            var body = JSON.parse(resp.body);
            var data = body[body.key];
            var dataLen = data.length;
            if(dataLen){ //findAll
                data.forEach(function (_row, _index) {
                    _row.name = Utils.jsEncode(data[_index].name, ENC_KEY);
                });
            } else { //findOne
                if(data.name) {
                        data.name = Utils.jsEncode(data.name, ENC_KEY);
                }
            }
            resp.success(body[body.key], next);
        } else {
                next();
        }
    }
});
module.exports = PostBlock;

In the example above, a key of ‘123’ is used to encrypt and decrypt the data.
在上面的示例中,一个“123”的key是用来加密和解密数据的。

Mobile App

手机应用程序

The mobile app should encrypt the data prior to POSTing data using the jsEncode function with the same key that is used in the Arrow app (e.g. ‘123’). The example below illustrates encrypting the value of a TextField with an Alloy id of “nameTF” prior to POSTing the data in an Appcelerator mobile app.

移动应用程序应该在发送数据之前使用jsEncode函数以及和Arrow 应用相同的key(例如“123”)来加密数据。下面的例子演示了Appcelerator手机应用中在发送数据之前加密Alloy id 为“nameTF”的文本字段的值的方法。

var ENC_KEY = '123';
var xhr = Ti.Network.createHTTPClient({
    onload: function onLoad() {
        Ti.API.info("Loaded: " + this.status + ": " + this.responseText);
    },
    onerror: function onError() {
        Ti.API.info("Errored: " + this.status + ": " + this.responseText);
    }
});
xhr.open("POST","http://127.0.0.1:8080/api/database");
var authstr = 'Basic ' + Ti.Utils.base64encode('TCDiEh3jpghZ2rQ7ckSr1NhGo2AZURwG:');
xhr.setRequestHeader("Authorization", authstr);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify({
    "name": jsEncode($.nameTF.value, ENC_KEY)
}));

After a GET is called, the encrypted data received by the Appcelerator mobile app must be decrypted as illustrated below. In the example below, the received data is used to populate a TableView with an Alloy id of “TV”.

在一GET被请求后,Appcelerator移动应用接收到的加密的数据接必须解密,如下图所示。在下面的示例中,接收的数据被用于填充一个Alloy id为 “TV”的TableView的。

var ENC_KEY = '123';
var xhr = Ti.Network.createHTTPClient({
    onload: function onLoad() {
        Ti.API.info("Loaded: " + this.status + ": " + this.responseText);
        var body = JSON.parse(this.responseText);
        var data = body[body.key];
        var rows = [];
        if(data.length>0) {
          _.each(data, function(item) {
              rows.push(Alloy.createController('row', {
              name: jsEncode(item.name, ENC_KEY)
            }).getView());
          });
        }
        $.TV.setData(rows);
    },
    onerror: function onError() {
        Ti.API.info("Errored: " + this.status + ": " + this.responseText);
    }
});
xhr.open("GET","http://127.0.0.1:8080/api/database");
var authstr = 'Basic ' + Ti.Utils.base64encode('TCDiEh3jpghZ2rQ7ckSr1NhGo2AZURwG:');
xhr.setRequestHeader("Authorization", authstr);
xhr.send();

Viewing Data in ArrowDB

在ArrowDB中查看数据

Recall that we are only encrypting the data in transit. The data in the ArrowDB is unencrypted. However, since we have added an encryption post block to the model for all GET operations, when we try to view the ArrowDB data in the Arrow console, we will see encrypted data as shown below:

回想一下,我们只是在运输途中加密了数据。ArrowDB中的数据是未加密的。然而,由于我们为所有的GET操作添加了一个加密块,当我们试图在Arrow控制台中查看ArrowDB的数据时,我们将看到加密了的数据,如下所示:

So, how do we view/access the unencrypted data?

那么,我们如何查看/访问未加密的数据?

One way is to use the Appcelerator Dashboard, select the Arrow app and navigate to the ArrowDB, and view the data in the Manage Data -> Custom Object section as shown below:


一种方法是使用Appcelerator仪表板,选择ArrowDB应用并导航到ArrowDB,然后在Mamage Data ->Custom Objext 部分中查看数据,如下所示:


Another technique for programmatically receiving unencrypted data is to modify the post block to look for a specific header and value and then send the data unencrypted. This code is provided here.

另一种以编程方式接收加密数据的技术是修改post块来寻找特定的header和value,然后把不加密的发送数据。代码如下。

An example curl command using this technique is shown below:

一个使用curl命令的技术例子如下所示:

$ curl -u TCDiEh3jpghZ2rQ7ckSr1NhGo2AZURwG: "http://127.0.0.1:8080/api/database" -H "admin-secret:admin-secret"

Results in the following reply:
结果如下:

{
    "success": true,
    "request-id": "b2a5d659-516d-49ba-a33e-629de4bab195",
    "key": "databases",
    "databases": [
        {
            "id": "564357e0dc26a0090d2f5b82",
            "name": "Leor"
        },
        {
            "id": "563d79043d24bb09100b7f6c",
            "name": "Lillian"
        },
        {
            "id": "563d78c8dc26a0090d0adfb3",
            "name": "Kim"
        },
        {
            "id": "563d78afdc26a009050af1b3",
            "name": "Nate"
        }
    ]
}

Compare this to using the curl command without the header:

比较一下没有header的curl命令的使用:

$ curl -u TCDiEh3jpghZ2rQ7ckSr1NhGo2AZURwG: "http://127.0.0.1:8080/api/database"

which returns the following encrypted data:
它返回的是以下加密的数据:

{
    "success": true,
    "request-id": "bf8cbf08-d2f2-4a24-a9a5-a37c0841535c",
    "key": "databases",
    "databases": [
        {
            "id": "564357e0dc26a0090d2f5b82",
            "name": "7\u001e\u0014\t"
        },
        {
            "id": "563d79043d24bb09100b7f6c",
            "name": "7\u0012\u0017\u0017\u0012\u001a\u0015"
        },
        {
            "id": "563d78c8dc26a0090d0adfb3",
            "name": "0\u0012\u0016"
        },
        {
            "id": "563d78afdc26a009050af1b3",
            "name": "5\u001a\u000f\u001e"
        }
    ]
}

Summary

总结

This post demonstrates how easy Arrow makes it to encrypt data in transit. Code for this post can be found here.
这篇文章演示了Arrow在传输途中加密数据是多么的容易。这篇文章的代码可以在这里找到。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 1、今天打开手机看到狮子会狮姐,还有微信群里其他队长们发来的信息有些烦躁。催要上周组织活动的两篇新闻报道,这些早在...
    王小红_家庭教育阅读 178评论 0 0
  • 其实,大多情况下,没有你想象的那么严重:“你的抑郁症是矫情,你的拖延症是懒,你的强迫症是闲的发慌,你的失眠是根本不...
    love四小姐阅读 99评论 0 0
  • 安妮宝贝说:我喜欢寂寞的人,因为他们是善良的。 季倒倒越来越喜欢对我说起过去,不知道现在的你身边有没有这样的一个人...
    夏末涩阅读 407评论 0 1
  • 我执着的这份等待,不是因为喜欢,而是你说过的,我全都当真。 1 我从裤兜里掏出三块钱递给凌然,“拿着,立正,挺胸收...
    MinePoppy阅读 294评论 0 0