Tuesday, September 19, 2017

How to Engage Users with Voice Interactions: 5 Useful Tips

Voice user interface (VUI) design is booming. Computerised personal assistants such as Apple’s Siri, Amazon’s Alexa, Google Now and Microsoft’s Cortana, are racing each other for the title of best voice assistant on the market.

Since Amazon released its voice assistant device Echo in December 2014, it has sold approximately 8.2 million devices, and uptake of voice search continues to climb. According to MindMeld, 60% of people who use voice search started using it in the last year, and 41% of people started in the last 6 months.

BCC research predicts that the global market for voice recognition technologies will increase from $104.4 billion in 2016 to $184.9 billion in 2021, at an annual growth rate of 12.1%.  

This surge is being driven by technological improvements and deep learning, which enables developers to create systems that have exceptional accuracy for tasks such as image analysis, speech recognition, and language analysis.

Last year, Microsoft announced that its latest speech-recognition system had achieved equivalence with human transcribers in recognising human speech

Voice technology is advancing quickly, and it’s changing the way we interact with our devices.

What does this mean for UX professionals? With companies already struggling to find VUI experts, now is a great time to start developing new skills as this game-changing technology evolves.

If you’re considering upskilling or embarking on a career in VUI, you’ll find your existing UX skill set will stand you in good stead. 

While many common UX design processes still apply – including user research, persona creation, prototyping, user flows, usability testing, and iterative design – voice UIs have a few key differences you to keep in mind.

If you’re about to embark on your first voice user interface design project, here are five essential tips to help you along the way. 

1.  Talking vs typing: make it conversational

It’s crucial to make sure that a voice UI understands natural speech – i.e. it can accept a wide range of different inputs.

We speak differently to how we type, in full sentences or questions, rather than a series of keywords.

Imagine your Sunday morning, you roll over and type in your phone “brunch nearby.” Predictably, a list of results will appear.

However, when we interact with a voice service, you’d be more inclined to articulate your request, “Alexa, can you suggest a good place for brunch nearby?”

Machines must be able to understand and respond to thousands of different commands in order to be successful.

2. Recognition: make it intuitive

No one wants to memorise hundreds of commands to perform specific tasks. Be careful not to design a system that is difficult to use and takes too much time to learn.

UX designer drawing a user flow for a Voice UI app

“Intuitive design, as with graphical user interfaces, is something designers and programmers need to get right.”

It is the machine’s job to remember us and become more efficient with each use. It’s intuitive and retains information from the user’s most recent search history.

Imagine you are asking your device for directions, and this is how the conversation plays out:

“Alexa, can you give me directions to work.”

“Alright, where is your work?”

“You know where I work!”

“I’m sorry, you’ll have to repeat that.”

This, as you can imagine, would create a frustrating experience for the user that is neither successful or satisfying.

If however, the system had retained information about your work address, it would quickly be able to give you a list of directions, most likely a short voice response with a visual component of a map and directions – making the experience a rewarding quick and satisfying exchange.

Intuitive design, as with graphical user interfaces, is something designers and programmers need to get right.

3. Accessibility: consider your user’s needs

Voice interactions rely on two things working successfully: the device understanding the person talking, and the person understanding the device.

This means designers should always consider potential speech impediments, hearing impairments, and any other things that could influence the communication, such as cognitive disorders. Even accent, language, or tone of voice can affect how the device understands them.

This requires you to be smart about where and how to use voice and design it in a way that everybody can use it, no matter how they sound or how they hear.

 4. Environment: consider your user’s surroundings

Speaking into your phone on a loud busy train is an example of why it’s important to consider how different environments affect the kind of interface you’ve designed.

If the main use is for driving, voice is a great choice—a user’s hands and eyes are busy, but their voice and ears are free.

If your app is going to be used somewhere noisy, a visual interface might be better, as the surrounding noise will make voice recognition and hearing more difficult.

The morning commute – a less than ideal time to chat with your phone.

If your app will be used both at home and on public transit, you may want to have the ability to switch between a voice and a visual interface.

5. Feedback: let the user know they are being heard

How do you show people you’re listening during a conversation? Most people nod their heads, smile, repeat things the other person said… all essential cues that show you’re listening.

It’s important to consider this with your design, so the user knows their device is switched on and is paying attention.

The system should always keep users informed about what is going on, and it’s important to consider how your user will know that the system is awake in a non-invasive way. Will it be a flashing light, a sound effect, or responding with an accurate response? You decide.

Wrapping up

Voice UIs are set to revolutionise the way we interact with technology. This is creating a huge need for specialised talent to successfully lead this shift in human-computer interaction. For UX designers looking to add another bow to their design string, CareerFoundry has just launched a new online course for Voice User Interface Design, built in collaboration with Amazon Alexa.

It’s a big shift as our devices start to talk and listen to us more, but UX designers are in prime position to adapt skill sets to this new technology. 

Do you have any experience designing for voice? Share any tips in the comments, or over in the forums.

The post How to Engage Users with Voice Interactions: 5 Useful Tips appeared first on UX Mastery.


by Georgina Titheridge via UX Mastery

Me

‘Me’ is a free One Page HTML template suited for an individual wanting a minimal, professional online presence. Features include a big background image, logo, bio and social icons. The template also includes functionality for YouTube video backgrounds (demo) and Self-Hosted video backgrounds (demo).

Want to use WordPress? Me is a layout in the FullSingle WordPress Plugin.
by Rob Hope @robhope via One Page Love

Building a React Universal Blog App: A Step-by-Step Guide

When the topic of single page applications (SPAs) comes up, we tend to think of browsers, JavaScript, speed, and invisibility to search engines. This is because an SPA renders a page's content using JavaScript, and since web crawlers don't use a browser to view web pages, they can't view and index the content --- or at least most of them can't.

This is a problem that some developers have tried to solve in various ways:

  1. Adding an escaped fragment version of a website, which requires all pages to be available in static form and adds a lot of extra work (now deprecated).
  2. Using a paid service to un-browserify an SPA into static markup for search engine spiders to crawl.
  3. Trusting that search engines are now advanced enough to read our JavaScript-only content. (I wouldn't just yet.)

Using Node.js on the server and React on the client, we can build our JavaScript app to be universal (or isomorphic). This could offer several benefits from server-side and browser-side rendering, allowing both search engines and humans using browsers to view our SPA content.

In this step-by-step tutorial, I'll show you how to build a React Universal Blog App that will first render markup on the server side to make our content available to search engines. Then, it will let the browser take over in a single page application that is both fast and responsive.

Building a React Universal Blog App

Getting Started

Our universal blog app will make use of the following technologies and tools:

  1. Node.js for package management and server-side rendering
  2. React for UI views
  3. Express for an easy back-end JS server framework
  4. React Router for routing
  5. React Hot Loader for hot loading in development
  6. Flux for data flow
  7. Cosmic JS for content management

To start, run the following commands:

mkdir react-universal-blog
cd react-universal-blog

Now create a package.json file and add the following content:

{
  "name": "react-universal-blog",
  "version": "1.0.0",
  "engines": {
    "node": "4.1.2",
    "npm": "3.5.2"
  },
  "description": "",
  "main": "app-server.js",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-register": "^6.26.0",
    "cosmicjs": "^2.4.0",
    "flux": "^3.1.3",
    "history": "1.13.0",
    "hogan-express": "^0.5.2",
    "html-webpack-plugin": "^2.30.1",
    "path": "^0.12.7",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router": "1.0.1",
    "webpack": "^3.5.6",
    "webpack-dev-server": "^2.7.1"
  },
  "scripts": {
    "webpack-dev-server": "NODE_ENV=development PORT=8080 webpack-dev-server --content-base public/ --hot --inline --devtool inline-source-map --history-api-fallback",
    "development": "cp views/index.html public/index.html && NODE_ENV=development webpack && npm run webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "react-hot-loader": "^1.3.0"
  }
}

In this file, you'll notice that we've added the following:

  1. Babel to package our CommonJS modules and convert our ES6 and React JSX into browser-compatible JavaScript
  2. The Cosmic JS official Node.js client to easily serve our blog content from the Cosmic JS cloud-hosted content API
  3. Flux for app data management (which is a very important element in our React application).
  4. React for UI management on server and browser
  5. React Router for routes on server and browser
  6. webpack for bringing everything together into a bundle.js file.

We've also added a script in our package.json file. When we run npm run development, the script copies the index.html file from our views folder into our public folder. Then, it sets the content base for our webpack-dev-server to public/ and enables hot reloading (on .js file save). Finally, it helps us debug our components at the source and gives us a fallback for pages it can't find (falls back to index.html).

Now let's set up our webpack configuration file by editing the file webpack.config.js:

// webpack.config.js
var webpack = require('webpack')

module.exports = {
  devtool: 'eval',
  entry: './app-client.js',
  output: {
    path: __dirname + '/public/dist',
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  module: {
    loaders: [
      { test: /\.js$/, loaders: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loaders: 'babel-loader', exclude: /node_modules/ }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.COSMIC_BUCKET': JSON.stringify(process.env.COSMIC_BUCKET),
      'process.env.COSMIC_READ_KEY': JSON.stringify(process.env.COSMIC_READ_KEY),
      'process.env.COSMIC_WRITE_KEY': JSON.stringify(process.env.COSMIC_WRITE_KEY)
    })
 ]
};

You'll notice that we've added an entry property with a value of app-client.js. This file serves as our app client entry point, meaning that from this point webpack will bundle our application and output it to /public/dist/bundle.js (as specified in the output property). We also use loaders to let Babel work its magic on our ES6 and JSX code. React Hot Loader is used for hot-loading (no page refresh!) during development.

Before we jump into React-related stuff, let's get the look-and-feel of our blog ready to go. Since I'd like you to focus more on functionality than style in this tutorial, here we'll use a pre-built front-end theme. I've chosen one from Start Bootstrap called Clean Blog. In your terminal run the following commands:

Create a folder called views and inside it an index.html file. Open the HTML file and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title> | </title>
  <!-- Bootstrap Core CSS -->
  <link href="/css/bootstrap.min.css" rel="stylesheet">
  <!-- Custom CSS -->
  <link href="/css/clean-blog.min.css" rel="stylesheet">
  <link href="/css/cosmic-custom.css" rel="stylesheet">
  <!-- Custom Fonts -->
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
  <link href="//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
    <script src="http://ift.tt/1fK4qT1"></script>
    <script src="http://ift.tt/1knl5gY"></script>
  <![endif]-->
</head>
<body class="hidden">
  <div id="app">}</div>
  <script src="/js/jquery.min.js"></script>
  <script src="/js/bootstrap.min.js"></script>
  <script src="/js/clean-blog.min.js"></script>
  <script src="/dist/bundle.js"></script>
</body>
</html>

To get all of the JS and CSS files included in public, you can get them from the GitHub repository. Click here to download the files.

Generally I would use the fantastic React Bootstrap package and refrain from using jQuery. However, for the sake of brevity, we'll keep the theme's pre-built jQuery functionality.

In our index.html file, we'll have our React mount point set up at the div where id="app". The template variable } will be converted into our server-rendered markup and then once the browser kicks in, our React application will take over and mount to the div with id="app". To improve the user experience while our JavaScript loads everything, we add class="hidden" to our body. Then, we remove this class once React has mounted. It might sound a bit complicated, but I'll show you how we'll do this in a minute.

At this point, your app should have the following structure:

package.json
public
  |-css
    |-bootstrap.min.css
    |-cosmic-custom.css
  |-js
    |-jquery.min.js
    |-bootstrap.min.js
    |-clean-blog.min.js
views
  |-index.html
webpack.config.js

Now that we have our static pieces done, let's start building some React Components.

Continue reading %Building a React Universal Blog App: A Step-by-Step Guide%


by Tony Spiro via SitePoint

Build a CRUD App Using React, Redux and FeathersJS

Building a modern project requires splitting the logic into front-end and back-end code. The reason behind this move is to promote code re-usability. For example, we may need to build a native mobile application that accesses the back-end API. Or we may be developing a module that will be part of a large modular platform.

The popular way of building a server-side API is to use a library like Express or Restify. These libraries make creating RESTful routes easy. The problem with these libraries is that we will find ourselves writing a TON of REPEATING CODE. We will also need to write code for authorization and other middleware logic.

To escape this dilemma, we can use a framework like Loopback or Feathersjs to help us generate an API.

At the time of writing, Loopback has more GitHub stars and downloads than Feathers. Loopback is a great library for generating RESTful CRUD endpoints in a short period of time. However, it does have a slight learning curve and the documentation is not easy to get along with. It has stringent framework requirements. For example, all models must inherit one of its built-in model class. If you need real-time capabilities in Loopback, be prepared to do some additional coding to make it work.

FeathersJS, on the other hand, is much easier to get started with and has realtime support built-in. Quite recently the Auk version was released (because Feathers is so modular, they use bird names for version names) which introduced a vast number of changes and improvements in a number of areas. According to a post they published on their blog, they are now the 4th most popular real-time web framework. It has excellent documentation and they have covered pretty much any area we can think of on building a real-time API.

What makes Feathers amazing is its simplicity. The entire framework is modular and we only need to install the features we need. Feathers itself is a thin wrapper built on top of express where they've added new features namely services and hooks. Feathers also allows us to effortlessly send and receive data over web sockets.

Prerequisites

Before you get started with the tutorial, you'll need to have a solid foundation in the following topics:

On your machine, you will need to have installed recent versions of:

  • NodeJS 6+
  • Mongodb 3.4+
  • Yarn package manager (optional)
  • Chrome browser

If you have never written a database API in JavaScript before, I would recommend first taking a look at this tutorial on creating RESTful APIs.

Scaffold the App

We are going to build a CRUD contact manager application using React, Redux, Feathers and MongoDB. You can take a look at the completed project here.

In this tutorial, I'll show you how to build the application from the bottom up. We'll kick-start our project using the create-react-app tool.

# scaffold a new react project
create-react-app react-contact-manager
cd react-contact-manager

# delete unnecessary files
rm src/logo.svg src/App.css

Use your favorite code editor and remove all the content in index.css. Open App.js and rewrite the code like this:

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        <h1>Contact Manager</h1>
      </div>
    );
  }
}

export default App;

Make sure to run yarn start to ensure the project is running as expected. Check the console tab to ensure that our project is running cleanly with no warnings or errors. If everything is running smoothly, use Ctrl+C to stop the server.

Build the API Server with Feathers

Let's proceed with generating the back-end API for our CRUD project using the feathers-cli tool.

# Install Feathers command-line tool
npm install -g feathers-cli

# Create directory for the back-end code
mkdir backend
cd backend

# Generate a feathers back-end API server
feathers generate app

? Project name | backend
? Description | contacts API server
? What folder should the source files live in? | src
? Which package manager are you using (has to be installed globally)? | Yarn
? What type of API are you making? | REST, Realtime via Socket.io

# Generate RESTful routes for Contact Model
feathers generate service

? What kind of service is it? | Mongoose
? What is the name of the service? | contact
? Which path should the service be registered on? | /contacts
? What is the database connection string? | mongodb://localhost:27017/backend


# Install email field type
yarn add mongoose-type-email

# Install the nodemon package
yarn add nodemon --dev

Open backend/package.json and update the start script to use nodemon so that the API server will restart automatically whenever we make changes.

// backend/package.json

....
"scripts": {
    ...
    "start": "nodemon src/",
    ...
  },
...

Let's open backend/config/default.json. This is where we can configure MongoDB connection parameters and other settings. I've also increased the default paginate value to 50, since in this tutorial we won't write front-end logic to deal with pagination.

{
  "host": "localhost",
  "port": 3030,
  "public": "../public/",
  "paginate": {
    "default": 50,
    "max": 50
  },
  "mongodb": "mongodb://localhost:27017/backend"
}

Open backend/src/models/contact.model.js and update the code as follows:

// backend/src/models/contact.model.js

require('mongoose-type-email');

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const contact = new mongooseClient.Schema({
    name : {
      first: {
        type: String,
        required: [true, 'First Name is required']
      },
      last: {
        type: String,
        required: false
      }
    },
    email : {
      type: mongooseClient.SchemaTypes.Email,
      required: [true, 'Email is required']
    },
    phone : {
      type: String,
      required: [true, 'Phone is required'],
      validate: {
        validator: function(v) {
          return /^\+(?:[0-9] ?){6,14}[0-9]$/.test(v);
        },
        message: '{VALUE} is not a valid international phone number!'
      }
    },
    createdAt: { type: Date, 'default': Date.now },
    updatedAt: { type: Date, 'default': Date.now }
  });

  return mongooseClient.model('contact', contact);
};

In addition to generating the contact service, Feathers has also generated a test case for us. We need to fix the service name first for it to pass:

// backend/test/services/contact.test.js

const assert = require('assert');
const app = require('../../src/app');

describe('\'contact\' service', () => {
  it('registered the service', () => {
    const service = app.service('contacts'); // change contact to contacts

    assert.ok(service, 'Registered the service');
  });
});

Open a new terminal and inside the backend directory, execute yarn test. You should have all the tests running successfully. Go ahead and execute yarn start to start the backend server. Once the server has finished starting it should print the line: 'Feathers application started on localhost:3030'.

Launch your browser and access the url: http://localhost:3030/contacts. You should expect to receive the following JSON response:

{"total":0,"limit":50,"skip":0,"data":[]}

Now let's use Postman to confirm all CRUD restful routes are working. You can launch Postman using this button:

Run in Postman

If you are new to Postman, check out this tutorial. When you hit the SEND button, you should get your data back as the response along with three additional fields which are _id, createdAt and updatedAt.

Use the following JSON data to make a POST request using Postman. Paste this in the body and set content-type to application/json.

{
  "name": {
    "first": "Tony",
    "last": "Stark"
  },
  "phone": "+18138683770",
  "email": "tony@starkenterprises.com"
}

Build the UI

Let's start by installing the necessary front-end dependencies. We'll use semantic-ui css/semantic-ui react to style our pages and react-router-dom to handle route navigation.

Important: Make sure you are installing outside the backend directory

// Install semantic-ui
yarn add semantic-ui-css semantic-ui-react

// Install react-router
yarn add react-router-dom

Update the project structure by adding the following directories and files:

|-- react-contact-manager
    |-- backend
    |-- node_modules
    |-- public
    |-- src
        |-- App.js
        |-- App.test.js
        |-- index.css
        |-- index.js
        |-- components
        |   |-- contact-form.js #(new)
        |   |-- contact-list.js #(new)
        |-- pages
            |-- contact-form-page.js #(new)
            |-- contact-list-page.js #(new)

Let's quickly populate the JS files with some placeholder code.

For the component contact-list.js, we'll write it in this syntax since it will be a purely presentational component.

// src/components/contact-list.js

import React from 'react';

export default function ContactList(){
  return (
    <div>
      <p>No contacts here</p>
    </div>
  )
}

For the top-level containers, I use pages. Let's provide some code for the contact-list-page.js

// src/pages/contact-list-page.js

import React, { Component} from 'react';
import ContactList from '../components/contact-list';

class ContactListPage extends Component {
  render() {
    return (
      <div>
        <h1>List of Contacts</h1>
        <ContactList/>
      </div>
    )
  }
}

export default ContactListPage;

For the contact-form component, it needs to be smart, since it is required to manage its own state, specifically form fields. For now, we'll place this placeholder code.

// src/components/contact-form.js
import React, { Component } from 'react';

class ContactForm extends Component {
  render() {
    return (
      <div>
        <p>Form under construction</p>
      </div>
    )
  }
}

export default ContactForm;

Populate the contact-form-page with this code:

// src/pages/contact-form-page.js

import React, { Component} from 'react';
import ContactForm from '../components/contact-form';

class ContactFormPage extends Component {
  render() {
    return (
      <div>
        <ContactForm/>
      </div>
    )
  }
}

export default ContactFormPage;

Now, let's create the navigation menu and define the routes for our App. App.js is often referred to as the 'layout template' for the Single Page Application.

Continue reading %Build a CRUD App Using React, Redux and FeathersJS%


by Michael Wanyoike via SitePoint

Creating Digital Signatures With Swift

The main purpose of a digital signature is to verify the integrity of some information. For a simple example, let's say you had a file that was transferred over the network and you want to check that the entire file was transferred correctly. In that case, you would use a checksum.

“A checksum is a small-sized datum derived from a block of digital data for the purpose of detecting errors which may have been introduced during its transmission or storage” — Wikipedia

How do we derive that checksum? The best option is to use a hash. A hash function will take a variable amount of data and will output a signature of fixed length. For example, we could publish a file along with its hash online. When someone downloads the file, they can then run the same hash function on their version of the file and compare the result. If the hashes are the same then the copied or downloaded file is the same as the original. 

A hash is also a one-way function. Given the resulting output, there is no computationally feasible way to reverse that hash to reveal what the original input was. SHA, Secure Hash Algorithm, is a well-known standard that refers to a group of hash functions that have this property and certain others, which make them useful for digital signatures.

About SHA

SHA has undergone many iterations since it was first published. The first and second iterations, SHA-0 and SHA-1, are now known to have major weaknesses. They are no longer approved for security implementations: they generally shouldn't be used for applications relying on security. However, the SHA-2 family includes versions called SHA-256 and SHA-512, and these are considered secure. "256" and "512" simply refer to the resulting number of bits produced. For this tutorial, we are going to use SHA-512.

Note: Another older popular hash algorithm was MD5. It was also found to have significant flaws.

Using SHA is great for checking if data was accidentally corrupted, but this doesn't prevent a malicious user from tampering with the data. Given that a hash output is of a fixed size, all an attacker needs to do is figure out which algorithm was used given the output size, alter the data, and recompute the hash. What we need is some secret information added to the mix when hashing the data so that the attacker cannot recompute the hash without knowledge of the secret. This is called a Hash Message Authentication Code (HMAC).

HMAC

HMAC can authenticate a piece of information or message to make sure that it originated from the correct sender and that the information has not been altered. A common scenario is when you are talking to a server with a back-end API for your app. It may be important to authenticate to ensure that only your app is allowed to talk to the API. The API would have access control to a specific resource, such as a /register_user endpoint. The client would need to sign its request to the /register_user endpoint in order to successfully use it.

When signing a request, it is common practice to take selected parts of the request, such as POST parameters and the URL, and join them together into a string. Taking agreed-upon elements and putting them in a particular order is called canonicalization. In HMAC, the joined string is hashed along with the secret key to produce the signature. Instead of calling it a hash, we use the term signature in the same way that a person's signature in real life is used to verify identity or integrity. The signature is added back to the client's request as a request header (usually also named “Signature”). A signature is sometimes called a message digest, but the two terms can be used interchangeably.

Over on the API side, the server repeats the process of joining the strings and creating a signature. If the signatures match, it proves that the app must have possession of the secret. This proves the identity of the app. Since specific parameters of the request were also part of the string to be signed, it also guarantees the integrity of the request. It prevents an attacker from performing a man-in-the-middle attack, for example, and altering the request parameters to their liking.

In this code, the CCHmac function takes a parameter for the type of hash function to be used, along with two byte-strings and their lengths—the message and a secret key. For the best security, use at least a 256-bit (32 byte) key generated from a cryptographically secure random number generator. To verify everything is working correctly on the other side, run the example and then input the secret key and message on this remote server and verify that the output is the same.

You can also add a timestamp header to the request and signing string to make the request more unique. This can help the API weed out replay attacks. For example, the API could drop the request if the timestamp is 10 minutes stale.

While it's good to stick to using SHA versions that are secure, it turns out that many of the vulnerabilities of the insecure SHA versions do not apply to HMAC. For this reason, you may see SHA1 being used in production code. However, from a public relations standpoint, it may look bad if you have to explain why, cryptographically speaking, it is okay to use SHA1 in this context. Many of the weaknesses of SHA1 are due to what are called collision attacks. Code auditors or security researchers may expect your code to be collision resistant, regardless of the context. Also, if you write modular code where you can swap out the signing function for a different one in the future, you might forget to update the insecure hash functions. Therefore, we will still stick to SHA-512 as our algorithm of choice.

The HMAC CPU operations are fast, but one disadvantage is the problem of key exchange. How do we let each other know what the secret key is without it being intercepted? For example, maybe your API will need to dynamically add or remove multiple apps or platforms from a whitelist. In this scenario, apps would be required to register, and the secret would need to be passed to the app upon successful registration. You could send the key over HTTPS and use SSL pinning, but even then there is always a worry that somehow the key is stolen during the exchange. The solution to the problem of key exchange is to generate a key that doesn't ever need to leave the device in the first place. This can be accomplished using Public Key Cryptography, and a very popular and accepted standard is RSA.

RSA

RSA stands for Rivest-Shamir-Adleman (the authors of the cryptosystem). It involves taking advantage of the difficulty of factoring the product of two very large prime numbers. RSA can be used for encryption or authentication, although for this example we are going to be using it just for authentication. RSA generates two keys, a public and a private, which we can accomplish using the SecKeyGeneratePair function. When used for authentication, the private key is used to create the signature, while the public key verifies the signature. Given a public key, it is computationally unfeasible to derive the private key.

The next example demonstrates what Apple and all the popular gaming console companies use when distributing their software. Let's say your company creates and delivers a file periodically that users will drag into the file sharing portion of your app in iTunes. You want to make sure the files you send out are never tampered with before being parsed in the app. Your company will hold onto and guard the private key which it uses to sign the files. In the bundle of the app is a copy of the public key used to verify the file. Given that the private key is never transmitted or included in the app, there is no way for a malicious user to be able to sign their own versions of the files (apart from breaking into the company and stealing the private key).

We will use SecKeyRawSign to sign the file. It would be slow to sign the entire contents of the file using RSA, so the hash of the file is signed instead. Additionally, the data passed to RSA should also be hashed before signing because of some security weaknesses.

In this code, we used the CC_SHA512 function to specify SHA-512 again. (RSA, unlike HMAC, becomes insecure if the underlying hash function is insecure.) We are also using 4096 as the key size, which is set by the kSecAttrKeySizeInBits parameter. 2048 is the minimum recommended size. This is to prevent a powerful network of computer systems cracking the RSA key (by cracking I mean factoring the RSA key—also known as factorization of a public modulus). The RSA group has estimated that 2048-bit keys could become crackable some time before 2030. If you want your data to be safe beyond that time then it's a good idea to choose a higher key size like 4096.

The generated keys are in the form of SecKey objects. An issue with Apple's implementation of SecKey is that it does not include all of the essential information that makes up a public key, so it's not a valid DER-encoded X.509 certificate. Adding the missing information back into the format for an iOS or OS X app, even server-side platforms such as PHP, requires some work and involves working in a format known as ASN.1. Fortunately, this was fixed in iOS 10 with new SecKey functions for generating, exporting, and importing keys. 

The code below shows you the other side of the communication—the class that accepts a public key via SecKeyCreateWithData to verify files using the SecKeyRawVerify function.

You could try this out and verify that it works using a simple test like the following:

There is one downside to RSA—key generation is slow! The time to generate the keys is dependent on the size of the key. On newer devices a 4096 bit key takes only a few seconds, but if you run this code on an iPod Touch 4th generation, it may take about a minute. This is fine if you are just generating the keys a few times on a computer, but what happens when we need to generate keys frequently on a mobile device? We can't just lower the key size because that downgrades the security. 

So what's the solution? Well, Elliptic Curve Cryptography (ECC) is an up-and-coming approach—a new set of algorithms based on elliptic curves over finite fields. ECC keys are much smaller in size and faster to generate than RSA keys. A key of only 256-bits offers a very strong level of security! To take advantage of ECC, we don't need to change a lot of code. We can sign our data using the same SecKeyRawSign function and then adjust the parameters to use Elliptic Curve Digital Signature Algorithm (ECDSA).

Tip: For more RSA implementation ideas, you can check out the SwiftyRSA helper library, which is focused on encryption as well as signing messages.

ECDSA

Imagine the following scenario: a chat app lets users send private messages to each other, but you want to make sure that an adversary has not changed the message on its way to the other user. Let's see how you could secure their communication with cryptography. 

First, each user generates a keypair of public and private keys on their mobile device. Their private keys are stored in memory and never leave the device, while the public keys are transmitted to each other. As before, the private key is used for signing the data being sent out, while the public key is used for verifying. If an attacker were to capture a public key during transit, all that could be done is to verify the integrity of the original message from the sender. An attacker can't alter a message because they don't have the private key needed to reconstruct the signature.

There is another pro to using ECDSA on iOS. We can make use of the fact that currently, elliptic curve keys are the only ones that can be stored in the secure enclave of the device. All other keys are stored in the keychain which encrypts its items to the default storage area of the device. On devices that have one, the secure enclave sits separate from the processor, and key storage is implemented in hardware without direct software access. The secure enclave can store a private key and operate on it to produce output that is sent to your app without ever exposing the actual private key by loading it into memory!

I will add support for creating the ECDSA private key on the secure enclave by adding the kSecAttrTokenIDSecureEnclave option for the kSecAttrTokenID parameter. We can start this example with a User object that will generate a keypair upon initialization.

Next, we will create some helper and example functions. As an example, the class will allow a user to initiate a conversation and send a message. Of course, in your app, you would configure this to include your specific networking setup.

Next, we will do the actual signing and verification. ECDSA, unlike RSA, does not need to be hashed prior to signing. However, if you wanted to have a function where the algorithm can be easily swapped without making many changes, then it's perfectly fine to continue to hash the data before signing.

This verifies the message, as well as the “identify” of a specific user since only that user has possession of their private key. 

This doesn't mean that we're connecting the key with who the user is in real life—the problem of matching a public key to a specific user is another domain. While the solutions are out of the scope of this tutorial, popular secure chat apps such as Signal and Telegram allow users to verify a fingerprint or number via a secondary communication channel. Similarly, Pidgin offers a question and answer scheme whereby you ask a question that only the user should know. These solutions open a whole world of debate on what the best approach should be.

However, our cryptographic solution does verify that the message can only have been sent by someone who is in possession of a specific private key.

Let's run a simple test of our example:

OAuth and SSO

Often when working with third-party services, you will notice other high-level terms used for authentication, such as OAuth and SSO. While this tutorial is about creating a signature, I will briefly explain what the other terms mean.

OAuth is a protocol for authentication and authorization. It acts as an intermediary to use someone's account for third-party services and aims to solve the problem of selectively authorizing access to your data. If you log in to service X via Facebook, a screen asks you, for example, if service X is allowed to access your Facebook photos. It accomplishes this by providing a token without revealing the user's password.

Single sign-on, or SSO, describes the flow where an authenticated user can use their same login credentials to access multiple services. An example of this is how your Gmail account works to log in to YouTube. If you had several different services at your company, you may not want to create separate user accounts for all of the different services.

Conclusion

In this tutorial, you saw how to create signatures using the most popular standards. Now that we have covered all the main concepts, let's recap!

  • Use HMAC when you need speed and are sure that the secret key can be exchanged securely.
  • If the keys have to travel across a network, it's better to use RSA or ECDSA.
  • RSA is still the most popular standard. Its verification step is quite fast. Use RSA if the rest of your team is already familiar with or using the standard.
  • If you need to constantly generate keys on a slow device, however, use ECDSA. While the ECDSA verification is a tad slower than RSA verification, that doesn't compare to the many seconds saved over RSA for key generation.

So that's it for digital signatures in Swift. If you have any questions, feel free to drop me a line in the comments section, and in the meantime check out some of our other tutorials on data security and app development in Swift!

  • iOS SDK
    Securing iOS Data at Rest: Protecting the User's Data
    Collin Stuart
  • iOS SDK
    Securing iOS Data at Rest: The Keychain
    Collin Stuart
  • Swift
    What's New in Swift 4
    Patrick Balestra
  • iOS SDK
    Faster Logins With Password AutoFill in iOS 11
    Patrick Balestra


by Collin Stuart via Envato Tuts+ Code

Embedded VS. Non-Embedded Signing with HelloSign

In less than 3 minutes, we teach you about the difference between embedded signing and non-embedded signing for legally binding documents. Working with non-embedded signature requests not only provides you convenience, but it also grants you security, notifications, and templates. All of these and more are covered in our video.

Continue reading %Embedded VS. Non-Embedded Signing with HelloSign%


by Angela Molina via SitePoint

10 Must Haves for a Highly Successful Video Marketing Campaign [Infographic]

Are you excited about starting your own video marketing campaign but aren’t exactly sure what’s essential and what’s not? This infographic illustrates the fundamental elements to incorporate when creating an effective and impactful marketing strategy.

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World