10 min read

(For more resources related to this topic, see here.)

Security, privacy, and safeguards for intellectual property are at the front of the minds of those of us building Titanium Enterprise apps. Titanium allows you to combine the underlying platform tools and third-party JavaScript libraries to help meet your security requirements.

This article provides a series of approaches on how to leverage JavaScript, Titanium modules, and the underlying platform to enable you to create a layered security approach to assist you in meeting your organization’s overall secure development goals. Each recipe is designed to provide building blocks to help you implement your industry’s existing security and privacy standards.

Implementing iOS data protection in Titanium

Starting with iOS 4, Apple introduced the ability for apps to use the data protection feature to add an additional level of security for data stored on disk. Data protection uses the built-in hardware encryption to encrypt files stored on the device. This feature is available when the user’s device is locked and protected with a passcode lock. During this time, all files are protected and inaccessible until the user explicitly unlocks the device.

When the device is locked, no app can access protected files. This even applies to the app that created the file.

Getting ready

This recipe uses the securely native module for enhanced security functionality. This module and other code assets can be downloaded from the source provided by the book. Installing these in your project is straightforward. Simply copy the modules folder into your project as shown in the following screenshot:

After copying the mentioned folder, you will need to click on your tiapp.xml file in Titanium Studio and add a reference to the bencoding.securely module as shown in the following screenshot:

Enabling data protection

This recipe requires your iOS device to have data protection enabled. You will need a device as the simulator does not support data protection. The following steps cover how to enable this feature on your device:

  1. Go to Settings | General | Passcode .
  2. Follow the prompts to set up a passcode.
  3. After adding a passcode, scroll to the bottom of the screen and verify that the text Data protection is enabled is visible as shown in the following screenshot:

iOS device browser

A third-party iOS device browser is needed to verify that data protection for the example recipe app has successfully been enabled. This recipe discusses how to verify data protection using the popular iExplorer app. An evaluation version of the iExplorer app can be used to follow along with this recipe. For more information and to download iExplorer, please visit http://www.macroplant.com/iexplorer.

How to do it…

To enable iOS data protection, the DataProtectionClass and com.apple.developer.default-data-protection keys need to be added to your tiapp.xml as demonstrated in the following code snippet:

  1. First, add the ios configuration node if your project does not already contain this element.

    <ios> <plist> <dict>

    
    
  2. Then at the top of the dict node, add the following highlighted keys.

    <key>DataProtectionClass</key> <string>NSFileProtectionComplete</string> <key>com.apple.developer. default-data-protection</key> <string>NSFileProtectionComplete</string> </dict> </plist> </ios>

    
    

     

  3. After saving the updates to your tiapp.xml, you must clean your Titanium project in order to have the updates take effect. This can be done in Titanium Studio by selecting Project | Clean .

Creating the namespace and imports

Once you have added the securely module and added the tiapp.xml updates to your project, you need to create your application namespace in the app.js file and use require to import the module into your code as the following code snippet demonstrates:

//Create our application namespace var my = { secure : require(‘bencoding.securely’) };


Creating the recipe UI

The following steps outline how to create the UI used in this recipe:

  1. First, a Ti.UI.Window is created to attach all UI elements.

    var win = Ti.UI.createWindow({ backgroundColor: ‘#fff’, title: ‘Data Protection Example’, barColor:’#000′,layout:’vertical’ });

    
    
  2. Next, a Ti.UI.Button is added to the Ti.UI.Window. This will be used to trigger our example.

    var button1 = Ti.UI.createButton({ title:’Create Test File’, top:25, height:45, left:5, right:5 }); win.add(button1);

    
    

Creating a file to verify data protection

To verify if data protection is enabled in the app, the recipe creates a time-stamped file in the Ti.Filesystem.applicationDataDirectory directory. Using an iOS device browser, we can verify if the test file is protected when the device is locked. The following steps describe how the recipe creates this test file:

  1. The click event for button1 creates a time-stamped file that allows us to verify if data protection has been correctly enabled for the app.

    button1.addEventListener(‘click’,function(e){

    
    
  2. Next the isProtectedDataAvailable method is called on securely. This provides a Boolean result indicating that data protection allows the app to read from or write to the filesystem.

    if(!my.secure.isProtectedDataAvailable()){ alert(‘Protected data is not yet available.’); return; }

    
    
  3. To ensure there is a unique identifier in the file, a token is created using the current date and time. This token is then added to the following message template:

    var timeToken = String.formatDate(new Date(),”medium”) + String.formatTime(new Date()); var msg = “When device is locked you will not be able”; msg += ” to read this file. Your time token is “; msg += timeToken;

    
    
  4. The message created in step 3 is then written to the test.txt file located in the Ti.Filesystem.applicationDataDirectory directory. If the file already exists, it is removed so that the latest message will be available for testing.

    var testfile = Ti.Filesystem.getFile( Ti.Filesystem.applicationDataDirectory, ‘test.txt’); if(testfile.exists()){ testfile.deleteFile(); } testfile.write(msg); testfile = null;

    
    
  5. Once the test.txt file is written to the device, a message is displayed to the user notifying them to lock their device and use an iOS device browser to confirm data protection is enabled.

    var alertMsg = “Please lock your device.”; alertMsg+= “Then open an iOS Device Browser.”; alertMsg+= “The time token you are looking for is “; alertMsg+= timeToken; alert(alertMsg);

    
    

How it works…

After the DataProtectionClass and com.apple.developer.default-data-protection keys have been added to your tiapp.xml, the iOS device handles protecting your files when the device is locked. The following steps discuss how to test that this recipe has correctly implemented data protection:

  1. The first step in the validation process is to build and deploy the recipe app to your iOS device.
  2. Once the app has been loaded onto your device, open the app and press the Create Test File button.

  3. Once you have received an alert message indicating the test file has been created, press the home button and lock your device.
  4. Plug your device into a computer with iExplorer installed.
  5. Open iExplorer and navigate so that you can view the apps on your device.
  6. Select the DataProtection app as marked with the red box in the following screenshot. Then right-click on the test.txt file located in the Documents folder and select Quick Look as marked with the green box in the following screenshot:

  7. After Quick Look is selected, iExplorer will try to open the test.txt file. Since it is protected, it cannot be opened and Quick Look will show the progress indicator until a timeout has been reached.

  8. You can then unlock your device and repeat the preceding steps to open the file in Quick Look .

AES encryption using JavaScript

The Advanced Encryption Standard ( AES ) is a specification for the encryption of electronic data established by the U.S. NIST in 2001. This encryption algorithm is used for securing sensitive, but unclassified material by U.S. Government agencies. AES has been widely adopted by enterprise and has become a de facto encryption standard for many commercially sensitive transactions.

This recipe discusses how AES can be implemented in JavaScript and incorporated into your Titanium Enterprise app.

Getting ready

This recipe uses the Ti.SlowAES CommonJS module as a wrapper around the SlowAES open source project. Installing these in your project is straightforward. Simply copy the SlowAES folder into the Resources folder of your project as shown in the following screenshot:

How to do it…

Once you have added the SlowAES folder to your project, next you need to create your application namespace in the app.js file and use require to import the module into your code as the following code snippet demonstrates:

//Create our application namespace var my = { mod : require(‘SlowAES/Ti.SlowAES’) };


Creating the recipe UI

This recipe demonstrates the usage of the Ti.SlowAES CommonJS module through a sample app using two Ti.UI.TextField controls for input.

  1. First, a Ti.UI.Window is created to attach all UI elements.

    var win = Ti.UI.createWindow({ backgroundColor: ‘#fff’, title: ‘AES Crypto Example’, barColor:’#000′,layout:’vertical’,fullscreen:false });

    
    

  2. Next, a Ti.UI.TextField control is added to the Ti.UI.Window to gather the secret from the user.

    var txtSecret = Ti.UI.createTextField({ value:’DoNotTell’,hintText:’Enter Secret’, height:45, left:5, right:5, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtSecret);

    
    
  3. Another Ti.UI.TextField is added to the Ti.UI.Window to gather the string to encrypt from the user.

    var txtToEncrypt = Ti.UI.createTextField({ value:’some information we want to encrypt’, hintText:’Enter information to encrypt’, height:45, left:5, right:5, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtToEncrypt);

    
    
  4. Next a Ti.UI.Label is added to the Ti.UI.Window. This Ti.UI.Label will be used to display the encrypted value to the user.

    var encryptedLabel = Ti.UI.createLabel({ top:10, height:65, left:5, right:5,color:’#000′, textAlign:’left’,font:{fontSize:14} }); win.add(encryptedLabel);

    
    
  5. Finally a Ti.UI.Button is added to the Ti.UI.Window. This Ti.UI.Button will be used later in the recipe to perform the encryption test.

    var btnEncrypt = Ti.UI.createButton({ title:’Run Encryption Test’, top:25, height:45, left:5, right:5 }); win.add(btnEncrypt);

    
    

Encrypting and decrypting values

This section demonstrates how to use the Ti.SlowAES module to use the secret entered in the txtSecret, Ti.UI.TextField to encrypt the contents of the txtToEncrypt, Ti.UI.TextField. Once completed, the encrypted value is then decrypted and compared against the original input. The results are displayed to the user in an alert message as shown in the following screenshots:

The encryption test is performed when the click event for the btnEncrypt control is fired as shown in the following code snippet:

btnEncrypt.addEventListener(‘click’,function(x){


  1. The first step in the encryption process is to create a new instance of the SlowAES module as shown in this code snippet.

    var crypto = new my.mod();

    
    
  2. Next using the encrypt function, the secret provided in the txtSecret control is used to encrypt the value in the txtToEncrypt control. The encrypted results are then returned to the encryptedValue as demonstrated in the following statement:

    var encryptedValue = crypto.encrypt(txtToEncrypt.value,txtSecret.value);

    
    
  3. The encryptedLabel.text property is then updated to display the encrypted value to the user.

    encryptedLabel.text = ‘Encrypted:’ + encryptedValue;

    
    
  4. Next, the decrypt method is used to demonstrate how to decrypt the string value encrypted earlier. This method requires the encrypted string value and the secret as shown in the following snippet:

    var decryptedValue = crypto.decrypt(encryptedValue,txtSecret.value);

    
    
  5. Finally, the original input value is compared against the decrypted value to ensure our encryption test was successful. The results of this test are then displayed to the user through a message alert and the Titanium Studio console.

    alert((txtToEncrypt.value ===decryptedValue) ? ‘Encryption Test successfully ran check console for details.’: ‘Test failed, please check console for details.’); });

    
    

LEAVE A REPLY

Please enter your comment!
Please enter your name here