Saving, Encrypting and Showing Images using Cloudant

Overview

This blog post is based on Saving and Retrieving Images using Cloudant with HTTP Adapters that I made a while ago using cloudant to store a base64 encoded image. Instead of saving the encoded image I will encrypt it using WL.SecurityUtils class provided in MobileFirst Foundation. WL.SecurityUtils is a small utility class that provides encryption and decryption of data using the Stanford Javascript Crypto Library (SJCL). In addition, I will not be covering the database creation or the Cordova plugin integration you can find that in the previous blog.

Encryption

To encrypt data you can use the WL.SecurityUtils.encrypt method. This method requires the key and the text that you wish to encrypt. It is recommended that you secure your key so that no one else can use it. In this blog I am hardcoding the key for simplicity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function sendRequest(res){
	var def = $.Deferred();
	name = generateName();
	 WL.SecurityUtils.encrypt({
	      key: key,
	      text: res
	 })
	 .then(function (res) {
		var payload = {
					"_id" : name,
					"ct": res.ct,
					"iv": res.iv,
					"v" : res.v,
					"src" : "objc"
			};
			$.ajax({
		        url: 'https://ibmdemo.cloudant.com/demo',
		        data : JSON.stringify(payload),
		        contentType : "application/json",
		           headers : {"Authorization" : "Basic " + btoa("ibmdemo:password123")},
		        dataType : "json",
		        type : "POST",
		        success : function(response) {
		     		WL.Logger.info(response);
		     		def.resolve(response);
		        },
		        error : function(response) {
		     	   WL.Logger.error(response);
		     	   def.reject(response);
		        }
		    });
	 })
	 .fail(function (err) {
		 def.reject(err);
	 });
	return def.promise();
}

The response from WL.SecurityUtils.encrypt are as follows : CT, IV, and V. CT is the cipher text or the encrypted text. IV is the initialization vector which is unique to the encrypted data. V is the version number which is generally 1. If you have an astute eye you may have noticed that I included a property called src before sending the payload to Cloudant. We will be using src later when decrypted the text.

Decrypting

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    function retrieveImageFromCloudant(){
	var config = {
			db : "demo",
			attachment : name,
			auth : btoa("ibmdemo:password123")
	};
	 WL.Client.invokeProcedure({
		adapter: 'cloudant',
		procedure: 'getImage',
		parameters: [config],
		compressResponse : true
	})
		.then(function (res) {
              var responseJSON = JSON.parse(res.responseText);
              var data = JSON.parse(responseJSON.text);
			var img =document.getElementById('img');
			WL.SecurityUtils.decrypt({
				key : key,
				ct : data.ct,
				iv : data.iv,
				src : data.src,
				v : res.iv
			})
			.then(function (res) {
					img.setAttribute("src", "data:image/png;base64,"+res);
			})
			.fail(function (err) {
				WL.Logger.error("Failed to decrypt image");
			});
		})
		.fail(function (err) {
			WL.Logger.error("Failed to read image");
		});
}

To decrypt the data you can use WL.SecurityUtils.decrypt. This requires the key, ct, iv, src, and v. I have already discussed what are the key, ct, and v but not the src. The src takes of the three options -- objc, java, and js. Java is for Android, objc is for iOS and js is for web. In this example I will be using objc. The response you will get is the decrypted text which in this case the base64 encoded string of the image.

Conclusion

Hopefully, this blog post will show you how easy it is to use encryption and decryption.

WLSecurityUtilsSampleApp

Resources

IBM Knowledge Center Docs for WL.SecurityUtils

Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on May 01, 2016