Basic Security Approaches

Exclusive offer: get 50% off this eBook here
Appcelerator Titanium Business Application Development Cookbook

Appcelerator Titanium Business Application Development Cookbook — Save 50%

Quickly and efficiently create business grade Titanium Enterprise apps, using hands-on recipes with this book and ebook

$29.99    $15.00
by Benjamin Bahrenburg | September 2013 | Cookbooks Enterprise Articles

Basic Security Approaches, provides recipes on best practices for login management, storing credentials, and use of third party JavaScript encryption libraries.

In this article by Benjamin Bahrenburg the author of book Appcelerator Titanium Business Application Development Cookbook,will cover:

  • Implementing iOS data protection in Titanium
  • AES encryption using JavaScript
  • Basic authentication using Ti.Network.HTTPClient
  • Implementing a cross-platform passcode screen
  • Working with protected ZIP files on iOS

(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.'); });

Appcelerator Titanium Business Application Development Cookbook Quickly and efficiently create business grade Titanium Enterprise apps, using hands-on recipes with this book and ebook
Published: June 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Basic authentication using Ti.Network.HTTPClient

Most enterprise sites or services provide access to content through basic access authentication. Basic authentication is a method for a HTTP user agent to provide a username and password when making a request. It is important to remember that basic authentication base64 encodes your credentials, not encrypts them. For this reason, it is advised that HTTPS is used when creating network connections.

Titanium provides full support for basic authentication using the SDK's Ti.Network functionality. This recipe describes how to use the Ti.Network.HTTPClient proxy to connect to a website using basic authentication headers.

Getting ready

This recipe uses the Ti.BA CommonJS module as an assist to Titanium's native Ti.Network.HTTPClient. This module and other code assets can be downloaded from the source provided by the book. Installing this module in your project is straightforward. Simply copy the Ti.BA.js file into Resources folder of your project as shown in the following screenshot:

How to do it...

Once you have added the Ti.BA.js file 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 = { mod : require('Ti.BA') };

Creating the recipe UI

This recipe uses a simple UI to illustrate how to establish a basic authenticated network connection. The code snippets in this section walkthrough how to construct the basic authentication testing app shown in the following screenshots:

Now perform the following steps:

  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 the txtUsername Ti.UI.TextField is added to the Ti.UI.Window. The default value is set to test since it is the default for the browserspy.dk test site used to create our mock test connection.

    var txtUsername = Ti.UI.createTextField({ value:'test',hintText:'Enter username', height:45, left:5, right:5, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtUsername);

  3. The txtPassword Ti.UI.TextField is then added to the Ti.UI.Window. The default value is set to test since it is the default for the browserspy.dk test site used to create our mock test connection.

    var txtPassword = Ti.UI.createTextField({ value:'test',hintText:'Enter password', passwordMask:true,height:45, left:5, right:5, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtPassword);

  4. Next the txtUrl Ti.UI.TextField is added to the Ti.UI.Window. The default value is set to "http://browserspy.dk/password-ok". The value for txtUrl can be updated to any service requiring basic authentication. For demonstration purposes, the recipe uses the browserspy.dk test site.

    var txtUrl = Ti.UI.createTextField({ value:'http://browserspy.dk/password-ok.php', hintText:'Enter Url', height:45, left:5, right:5, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtUrl);

  5. Finally the btnConnect Ti.UI.Button is added to the Ti.UI.Window. Later in this recipe, the btnConnect control will be used to initialize the authenticated network connection.

    var btnConnect = Ti.UI.createButton({ title:'Connect', top:25, height:45, left:5, right:5 }); win.add(btnConnect);

Creating a service connection

With the sample UI now in place, the next step in the recipe is to perform a secure network connection using basic authentication. The following snippets are used to create a network connection and display the results shown in the following screenshots:

A basic authenticated test network connection is performed when the click event for the btnConnect control is fired as shown in the following code snippet:

btnConnect.addEventListener('click',function(x){

  1. First, the Ti.Network.online property is checked to ensure the device has a network connection. If no network connection is available, the user is alerted and the function is exit.

    if(!Ti.Network.online){ alert('Network connection is required'); return; }

  2. Next the onDone function is created. This function is used as a callback for the results of the authentication network connection.

    function onDone(d){

  3. When in the onDone function, the first action performed is to check the results provided in the d.success property. If this property is true, the network connection was successfully completed. Otherwise, the d.error message is printed to the console and the user is notified.

    if(d.success){ Ti.API.info('Results = ' + JSON.stringify(d.results)); alert('Authenticated successfully'); }else{ Ti.API.info('error = ' + JSON.stringify(d.error)); alert('Authenticated Failed'); } };

  4. The credentials object is then created. This contains the username and password to be used when creating our authenticated connection. Please note these values should be in plain text as demonstrated in taking the values directly from the Ti.UI.TextField controls on the screen.

    var credentials = { username:txtUsername.value, password:txtPassword.value };

  5. The Ti.BA module allows you to configure all of the Ti.Network.HTTPClient options along with controlling and specifying the service's output format. The following snippet demonstrates how to configure the request to set the timeout to 9 seconds, and specify the responseText be the returned response.

    var options = {format:'text', timeout:9000};

  6. Finally a new instance of the Ti.BA module is created and the following are provided:
    • Method : The GET or POST action is performed. In the case of this sample, the POST method is provided.
    • URL : The URL the module uses to connect.
    • Credentials : The credentials object contains the username and password that will be used to create the basic authenticated connection.
    • Callback : This parameter requires a callback method to be provided. In this sample, the onDone method is provided to the module and will return the connection response.
    • Options : These are the configuration options for the Ti.Network.HTTPClient and result type to be returned. If none is provided, the module's default values are returned.

      var basicAuth = new my.mod('POST',txtUrl.value,credentials, onDone,options); });

Appcelerator Titanium Business Application Development Cookbook Quickly and efficiently create business grade Titanium Enterprise apps, using hands-on recipes with this book and ebook
Published: June 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Implementing a cross-platform passcode screen

Password and passcode screens are common verification instruments for enterprise apps. These screens provide interaction patterns that help solve both authentication and confirmation scenarios.

This recipe demonstrates how to implement a cross-platform passcode screen similar to those seen on iOS and in the Android networking screens.

Getting ready

This recipe uses the Ti.Passcode CommonJS module to implement a cross-platform passcode screen. Installing this module in your project is straightforward. Simply copy the Ti.Passcode.js file into the Resources folder of your project as shown in the following screenshot:

How to do it...

Once you have added the Ti.Passcode.js file to your project, you need to create your application namespaces in the app.js file and use require to import the module into your code as the following code demonstrates:

//Create our application namespace var my = { mod : require('Ti.Passcode') };

Creating the recipe UI

This recipe uses Ti.UI.Windows to present information to the user. The code used to create the first Ti.UI.Window is discussed in this section. This section details how to launch the Ti.Passcode module and provides a code to have it verified.

Now perform the following steps:

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

    var win = Ti.UI.createWindow({ backgroundColor: '#fff', title: 'Passcode Example', layout:'vertical',fullscreen:false, exitOnClose:true });

  2. Next the txtPasscode Ti.UI.TextField is added to the Ti.UI.Window. This control is used to collect the passcode that the Ti.Passcode module will verify against.

    var txtPasscode = Ti.UI.createTextField({ value:'1234',hintText:'Enter Passcode', height:45, left:5, right:5, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtPasscode);

  3. Finally the bntRunPasscode Ti.UI.Button is added to the Ti.UI.Window. This button will be used later in the recipe to launch the passcode screen.

    var btnRunPasscode = Ti.UI.createButton({ title:'Open Passcode Screen', top:25, height:45, left:5, right:5 }); win.add(btnRunPasscode);

Launching the passcode screen

The second Ti.UI.Window in this recipe is created by the Ti.Passcode module. This Ti.UI.Window is responsible for the presentation and verification of the application passcode. This section describes how to configure, create, and confirm your app passcode using this module's display element shown in the following screenshot:

The passcode verification screen is launched when the user taps the btnRunPasscode Ti.UI.Button and triggers the click event to be fired. The following code snippet discusses the actions performed after the click event is fired:

btnRunPasscode.addEventListener('click',function(x){

  1. The first code block in the click event of the btnRunPasscode button is to create our configuration and other variables. The options object contains all of the settings needed to configure the Ti.Passcode window.

    var codeWindow = null, options = {

  2. The window configuration element allows for all of the standard Ti.UI.Window properties to be used. The following snippet shows how to set the backgroudnColor and navBarHidden properties on the passcode window.

    window:{ backgroundColor:'#ccc', navBarHidden:true },

  3. The view configuration element allows for the configuration of a majority of the components displayed in the Ti.Passcode window. The following snippet demonstrates how to set the passcode title property and code for displaying the error message:

    view:{ title:'Enter application passcode', errorColor:'yellow' } };

    Please review the Ti.Passcode module for a complete list of the configuration properties available.

  4. Next the onCompleted callback function is defined. This function will be used as the callback method provided to the Ti.Passcode module. The passcode verification results will be provided as a dictionary to the d input parameters.

    function onCompleted(d){

  5. The d argument is an object with the verification results. The d.success property provides an indicator if the entered passcode matches the passcode provided on launch. The following code snippet alerts the user if they have entered the correct passcode or if they need to try the process again.

    if(d.success){ alert('Passcode entered is correct'); codeWindow.close(); }else{ Alert('Invalid passcode, please try again'); } };

  6. The next step in this section of the recipe is to create a new instance of the passcode module. The following snippet demonstrates how to do this:

    var passcode = new my.mod();

  7. The createWindow method is then called on the new passcode instance. This method provides the passcode to verify from the txtPasscode control, and also provides the callback and options objects created earlier. This method then returns a Ti.UI.Window. Once the passcode has been entered, the callback method onCompleted will send the verification results.

    var codeWindow = passcode.createWindow(txtPasscode.value, onCompleted,options);

  8. The Ti.UI.Window returned by the createWindow method is then opened with a modal flag. The passcode Ti.UI.Window will remain open until closed by the onCompleted callback method as discussed earlier.

    codeWindow.open({modal:true}); });

The following screenshots illustrate how this section of the code looks on the device after the user has successfully entered his/her passcode.

Working with protected ZIP files on iOS

Protected zip files are a common way to exchange, store, and transmit enterprise data. ZIP files are often used to bundle several files together for transmission or storage. As an extra layer of security, all such files should always be protected with a strong password.

The following recipe discusses how to create and unzip protected compressed files on iOS.

Getting ready

This recipe uses the bencoding.zip native module to work with protected zip files. Installing this module in your project is straightforward. Simply copy the modules folder into the root of your project, and then copy the data folder into the Resources directory of your project as shown in the following screenshot:

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

How to do it...

Once you have added the modules and data folders to your project, you need to create your application namespaces 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 = { zip : require('bencoding.zip') };

Creating the recipe UI

This recipe uses a simple UI to illustrate how to create (zip) and unzip protected ZIP files. The code discussed in this section walks through how to construct the recipe's UI shown in the following screenshot:

The following steps outline how to create the recipe's UI:

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

    var win = Ti.UI.createWindow({ backgroundColor: '#fff', title: 'Protected Zip Example', barColor:'#000',layout:'vertical' });

  2. Next add the txtPassword Ti.UI.TextField control. This control will be used to provide the password to create protected ZIP files or to unzip them. The default is set to foo123. This is also the password for the included sample file.

    var txtPassword = Ti.UI.createTextField({ value:'foo123',hintText:'Enter Password', height:45, left:5, right:5, passwordMask:true, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED }); win.add(txtPassword);

  3. Then the btnZip Ti.UI.Button is added to the Ti.UI.Window. This button will be used to demonstrate how to create a protected ZIP file later in the discussion of this recipe.

    var btnZip = Ti.UI.createButton({ title:'Zip with Password', top:25, height:45, left:5, right:5 }); win.add(btnZip);

  4. Next the btnUnzip Ti.UI.Button is added to the Ti.UI.Window. This button will be used to demonstrate how to unzip a protected ZIP file later in the discussion of this recipe.

    var btnUnzip = Ti.UI.createButton({ title:'Unzip with Password', top:25, height:45, left:5, right:5 }); win.add(btnUnzip);

Creating a password-protected ZIP file

This section of this recipe demonstrates how to create a protected ZIP file. The following screenshot shows this recipe in action, creating a protected ZIP file and alerting the user of the output file path:

The created ZIP file is executed when the user clicks on the btnZip Ti.UI.Button and triggers the click event to be fired. The following code snippet discusses the actions performed after the click event is fired:

btnZip.addEventListener('click',function(x){

  1. The first step in the zip process is to create the onZipCompleted callback method. When the zip process is completed, the module will send the results to this callback method:

    function onZipCompleted(d){

  2. The d method parameter provides the results from the module. The first step in processing the module results is to check the d.success property to see if the zip process was successful. If so, the user is alerted of the path of the completed ZIP file. Otherwise, the user is alerted to the error generated in creating the file.

    if(d.success){ alert('Protected zip created at: ' + d.zip); }else{ alert('failed due to: ' + d.message); } };

  3. Next the writeToZip and inputDirectory variables are created. The writeToZip variable contains the path to the taxforms.ZIP output file in the app's Documents directory. The inputDirectory creates a reference to the Resources/data created during the Getting ready section of this recipe.

    var writeToZip = Ti.Filesystem.applicationDataDirectory + '/taxforms.zip'; var inputDirectory = Ti.Filesystem.resourcesDirectory + 'data/';

  4. Finally the zip method is called and this method provides the parameters built earlier in the click event handler. Once completed, the zip method provides results to the provided onZipCompleted callback method.

    my.zip.zip({ zip: writeToZip, password:txtPassword.value, files: [inputDirectory + 'w2.pdf', inputDirectory + 'w4.pdf'], completed:onZipCompleted }); });

    The files parameter provides an array of files using the inputDirectory variable. In this example, the files included are the w2.pdf and w4.pdf files included in the Resources/data folder created during the Getting ready section of this recipe.

Unzipping a protected ZIP file

This section of the current recipe demonstrates how to unzip a protected ZIP file. The following screenshot shows this recipe in action, unzipping the contents of a protected file into the app's Documents directory:

The unzip example is executed when the user taps on the btnUnzip Ti.UI.Button and triggers the click event to be fired. The following code snippet discusses the actions performed after the click event is fired.

btnUnzip.addEventListener('click',function(x){

  1. The first step in the unzip process is to create the onUnzipCompleted callback method. When the unzip process is completed, the module will send the results to this callback method.

    function onUnzipCompleted(e){

  2. The d method parameter provides the results from the module. The first step in processing the module results is to check the d.success property to see if the unzip process was successful. If so, the user is alerted of the directory path of the unzipped file. Otherwise, the user is alerted to the error generating the file.

    if(e.success){ alert('Unzipped to ' + e.outputDirectory); }else{ alert('failed due to: ' + e.message); } };

  3. The outputDirectory and zipFileName variables are created next. The outputDirectory variable contains the path to the output directory in the app's Documents directory. The zipFileName creates a reference to the Resources/data/taxform.zip file created during the Getting ready section of this recipe.

    var outputDirectory = Ti.Filesystem.applicationDataDirectory; var zipFileName = Ti.Filesystem.resourcesDirectory + 'data/taxforms.zip';

  4. Finally, the unzip method is called and this method provides the parameters built earlier in the click event handler. Once completed, the unzip method provides results to the provided onUnzipCompleted callback method.

    my.zip.unzip({ outputDirectory:outputDirectory, zip:zipFileName, overwrite:true, completed:onUnzipCompleted }); });

    All files contained within the zipFileName ZIP file will be unzipped to the root of the directory provided in the outputDirectory parameter.

Summary

Thus in this article we have learned about various basic security approaches.

Resources for Article :


Further resources on this subject:


About the Author :


Benjamin Bahrenburg

Benjamin Bahrenburg is a developer, blogger, speaker, and consultant. Ben specializes in building enterprise solutions using mobile technologies, geolocation services, and domain-specific languages. Over the last decade, he has provided mobility solutions for numerous Fortune 100 organizations.

Ben is passionate about cross-platform development, particularly the use of Titanium mobile for mobile app development. He was an early adopter of the Titanium mobile SDK and has built apps since the earliest previews of Appcelerator's mobile platform. Ben is an active member of the mobile development community and holds a Titanium certification in addition to being part of the Appcelerator Titan evangelist group. A strong advocate and contributor to the Titanium module ecosystem, Ben has published numerous open source modules used in thousands of published apps.

An active blogger at bencoding.com, he frequently posts tutorials on mobile development and enterprise coding topics.

Books From Packt


Appcelerator Titanium Application Development by Example Beginner's Guide
Appcelerator Titanium Application Development by Example Beginner's Guide

Appcelerator Titanium: Patterns and Best Practices
Appcelerator Titanium: Patterns and Best Practices

Augmented Reality using Appcelerator Titanium Starter [Instant]
Augmented Reality using Appcelerator Titanium Starter [Instant]

 Appcelerator Titanium Smartphone App Development Cookbook
Appcelerator Titanium Smartphone App Development Cookbook

Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7
Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7

Microsoft SharePoint 2013 Disaster Recovery Guide
Microsoft SharePoint 2013 Disaster Recovery Guide

Microsoft Dynamics CRM 2011 New Features
Microsoft Dynamics CRM 2011 New Features

Learning Search-driven Application Development with SharePoint 2013
Learning Search-driven Application Development with SharePoint 2013


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
g
H
e
q
F
v
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software