如何在React Native中加密领域

时间:2018-07-18 15:58:33

标签: javascript react-native encryption realm realm-mobile-platform

我正在尝试在登录后使用应用程序的PIN用户集在React本机应用程序上加密Realm。

用户登录到应用程序,然后设置一个PIN,该用户将用于以下与应用程序的交互。我想将此PIN用作加密密钥。

我看过有关 https://realm.io/docs/javascript/latest/#encryption Key Generation/Storage for react-native apps to encrypt realm db

有一个想法,我需要在打开数据库时添加加密密钥,但是如何将密钥传递给数据库选项。如果您可以提出更好的方法,那将非常有用。

这是我的流程,

ConfirmPIN.js

 import { insertUser, deleteUser } from '../../../databases/schemas';

 savePin = (userPIN) => {   
    const newUser = {
      id: 1,
      userName: 'Here goes the user name',
      pin: userPIN
    }
    deleteUser(1).then().catch((error) => {
      console.log(error);
    });
    insertUser(newUser).then().catch((error) => {
      alert(error);
    }); 
  }

schemas.js

export const userSchema = {
    name: USER_SCHEMA,
    primaryKey: 'id',
    properties: {
        id: 'int',
        userName: 'string',
        pin: 'string'
    }
}

const databaseOptions = {
    path: 'retailApp.realm',
    schema: [ userSchema, appDataSchema],
    schemaVersion: 0 //optional
    //SHOULD I BE ADDING THE KEY HERE? IF SO HOW CAN I PASS THE KEY SET BY THE 
    //USER
}

export const insertUser = user => new Promise ((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        realm.write(() => {
            realm.create(USER_SCHEMA, user);
            resolve(user);
        });
    }).catch((error) => reject(error));
});

export const deleteUser = userID => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        realm.write(() => {
            let userToDelete = realm.objectForPrimaryKey(USER_SCHEMA, userID);
            realm.delete(userToDelete);
            resolve();
        });
    }).catch((error) => reject(error));
});

securityUtils.js

将base64编码为KEY的代码(尚未测试其工作方式)

export const getBase64Encodedpin = pin => {
    var utf8 = require('utf8');
    var binaryToBase64 = require('binaryToBase64');

    var text = pin;
    var bytes = utf8.encode(text);
    var base64Encoded = binaryToBase64(bytes);
    return base64Encoded;
} 

我希望能够在打开数据库时将此密钥传递给schemas.js,您能建议我如何做到这一点。

谢谢 R

1 个答案:

答案 0 :(得分:0)

在此处从安全位置检索您的密钥或创建如下所示的密钥...

var key = new Int8Array(64);

在架构中添加加密密钥

export const userSchema = {
        name: USER_SCHEMA,
        primaryKey: 'id',
        properties: {
            id: 'int',
            userName: 'string',
            pin: 'string'
        },
       encryptionKey: key, // add Your Pin/key Here
    }

在databaseOptions中添加key

const databaseOptions = {
    path: 'retailApp.realm',
    schema: [ userSchema, appDataSchema],
    schemaVersion: 0, //optional
    encryptionKey: key, // add Your Pin/key Here
}   

搜索后我实现了这个,