Skip to main content
Version: 7.2.1

Encryption & Cryptography

Encryption is a necessity when it comes to a mobile application that communicates with external API. Sending sensitive information like access token, public/private key or user information might be spoofed if sent via plaintext.

RSA Encryption

API Reference Crypto-RSA

Using Crypto library, it is possible to generate a keypair locally and use it to fit the needs.

Recommended Online RSA Encryption Test Tool credited by devglan.com

Example Client RSA Encryption

note

The components in the example are added from the code for better showcase purposes. To learn more about the subject you can refer to:

Adding Component From Code

As a best practice, Smartface recommends using the WYSIWYG editor in order to add components and styles to your page or library. To learn how to use UI Editor better, please refer to this documentation

UI Editor Basics
/scripts/pages/page1.ts
import PageSampleDesign from "generated/pages/page3";
import { Route, Router } from "@smartface/router";
import Crypto from "@smartface/native/global/crypto";
import Data from "@smartface/native/global/data";
import System from "@smartface/native/device/system";
import Label from "@smartface/native/ui/label";
import Button from "@smartface/native/ui/button";
import TextBox from "@smartface/native/ui/textbox";
import { styleableComponentMixin, styleableContainerComponentMixin } from "@smartface/styling-context";
import FlexLayout from "@smartface/native/ui/flexlayout";

class StyleableButton extends styleableComponentMixin(Button) {}
class StyleableTextBox extends styleableComponentMixin(TextBox) {}
class StyleableLabel extends styleableComponentMixin(Label) {}
class StyleableFlexLayout extends styleableContainerComponentMixin(FlexLayout) {}

const ENCRYPT_KEY_SIZE = 1024;
const ENCRYPT_CIPHER_TYPE = "RSA/ECB/PKCS1Padding";
const PUBLIC_KEY_DEVICE_KEY = "publicKey"; //The key to save to the device database
const PRIVATE_KEY_DEVICE_KEY = "privateKey"; //The key to save to the device database

type KeyPairType = { publicKey: string; privateKey: string };

//You should create new Page from UI-Editor and extend with it.
export default class Sample extends PageSampleDesign {
myLabel: StyleableLabel;
encryptButton: StyleableButton;
decryptButton: StyleableButton;
tbEncrypt: StyleableTextBox;
keyPair: KeyPairType;
private encryptedText = "";
constructor(private router?: Router, private route?: Route) {
super({});
this.myLabel = new StyleableLabel();
this.encryptButton = new StyleableButton();
this.decryptButton = new StyleableButton();
this.tbEncrypt = new StyleableTextBox();
}

generateKeyPair(): KeyPairType {
let privateKey = Data.getStringVariable(PRIVATE_KEY_DEVICE_KEY);
let publicKey = Data.getStringVariable(PUBLIC_KEY_DEVICE_KEY);
if (!privateKey || !publicKey) {
const didGenerate = Crypto.RSA.generateKeyPair({
keySize: ENCRYPT_KEY_SIZE,
});
if (!didGenerate) {
throw new Error("Could not generate keypair");
}
privateKey = didGenerate.privateKey;
publicKey = didGenerate.publicKey;
Data.setStringVariable(PUBLIC_KEY_DEVICE_KEY, publicKey); // Public key doesn't need to be stored securely
Data.setStringVariable(PRIVATE_KEY_DEVICE_KEY, privateKey); // Consider using secure data
}
return {
privateKey: privateKey,
publicKey:
System.OS === System.OSType.IOS ? Crypto.RSA.ios.getExportedPublicKey() : publicKey,
};
}

encrypt(text: string, key: string): string {
const keyBody = {
text: "Smartface Inc.",
secretText: text,
};
return Crypto.RSA.encrypt({
key,
// @ts-ignore
cipherType: ENCRYPT_CIPHER_TYPE,
plainText: JSON.stringify(keyBody),
});
}

decrypt(encryptedText: string, key: string): string {
return Crypto.RSA.decrypt({
encryptedText: encryptedText,
key,
// @ts-ignore
cipherType: ENCRYPT_CIPHER_TYPE,
});
}

initLabel() {
this.myLabel.text = "Decrpyted text will go here";
this.addChild(this.myLabel, "myLabel", ".sf-label");
}

initButtons() {
this.keyPair = this.generateKeyPair();
const buttonWrapper = new StyleableFlexLayout();
this.addChild(buttonWrapper, "buttonWrapper", ".sf-flexlayout", {
heigth: 120,
});
this.encryptButton.text = "Encrypt";
this.encryptButton.onPress = () => {
this.encryptedText = this.encrypt(
this.tbEncrypt.text || "",
this.keyPair.publicKey
);
this.myLabel.text = this.encryptedText;
};
this.decryptButton.text = "Decrypt";
this.decryptButton.onPress = () => {
const decryptedObjectText = this.decrypt(
this.encryptedText,
this.keyPair.privateKey
);
const decrpytedObject = JSON.parse(decryptedObjectText);
this.myLabel.text = decrpytedObject.secretText;
};
buttonWrapper.addChild(this.encryptButton, "encryptButton", ".sf-button");
buttonWrapper.addChild(this.decryptButton, "decryptButton", ".sf-button");
}

initTextBox() {
this.tbEncrypt.hint = "Enter text to encrypt";
this.addChild(this.tbEncrypt, "tbEncrypt", ".sf-textbox");
}

// The page design has been made from the code for better
// showcase purposes. As a best practice, remove this and
// use WYSIWYG editor to style your pages.
centerizeTheChildrenLayout() {
this.dispatch({
type: "updateUserStyle",
userStyle: {
flexProps: {
flexDirection: 'ROW',
justifyContent: 'CENTER',
alignItems: 'CENTER',
flexWrap: 'WRAP'
}
}
})
}

onShow() {
super.onShow();
}

onLoad() {
super.onLoad();
this.centerizeTheChildrenLayout();

this.initTextBox();
this.initLabel();
this.initButtons();
}
}

This code will store your generated public and private key in the device. The private key must be securely store into application.

AES Encryption

API Reference Crypto-AES

Using Crypto library, it is possible to generate a key locally and use it to fit the needs.

Example Client AES Encryption


import Page1Design from 'generated/pages/page1';
import { Route, Router } from '@smartface/router';
import { withDismissAndBackButton } from '@smartface/mixins';
import Crypto from '@smartface/native/global/crypto';

export default class Page1 extends withDismissAndBackButton(Page1Design) {
private disposeables: (() => void)[] = [];
encryptedValues: {encryptedText?: String, iv?: String} = {};
constructor(private router?: Router, private route?: Route) {
super({});
}

/**
* @event onShow
* This event is called when a page appears on the screen (everytime).
*/
onShow() {
super.onShow();
console.log('onShow Page1');
let plainText = "Hello World!";
let keyBase64 = Crypto.AES.generateKey(32);
Crypto.AES.encryptGCMAsync({
plainText: plainText,
key: keyBase64,
onComplete: (encryptedText, iv): void => {
this.encryptedValues = { encryptedText, iv };
console.info("Encryption ", { encryptedText, iv })
},
onFailure: (err) => {
console.error(err);
}
});
setTimeout(() => {
Crypto.AES.decryptGCMAsync({
encryptedText: this.encryptedValues.encryptedText,
key: keyBase64,
iv: this.encryptedValues.iv,
onComplete: (plainText) => {
console.info("decrypted text: ", plainText);
},
onFailure: (err) => {
console.error(err);
}
});
}, 1000)

}

/**
* @event onLoad
* This event is called once when page is created.
*/
onLoad() {
super.onLoad();
console.log('Onload Page1');
}

onHide(): void {
this.dispose();
}

dispose(): void {
this.disposeables.forEach((item) => item());
}

}


caution

AES.generateKey Used to generate secure random key with given size, size could only be one of 16, 24, or 32 bytes.

Native Encryption

When storing sensitive information using Data on your device like in the example code, by default it is stored in plaintext to the device storage and can be retrieved by anyone who peeks into the application files.

Please head into Secure Data (Keystore) documentation to securely encrypt and make tough the extraction of your private key from device. There is no practical need to encrypt public key, since it is... intended to be public.