úterý 17. března 2015

Working with SQLite and Visual Studio 2013

SQLite is nice project to store low amount of data in applications. Babel windows desktop project uses it to store client data on client computer. SQLite is lightweight database with excellent portability link

Advantage of this solution is that we have SQL available. Selection, projection, insertions, transactions etc. are ready to use. Of course there is gap between objects and relational database. SQLite is relational so we need to use some ORM framework which provides an easy access to database from code. Babel windows desktop client uses sqlite-net. This library allows Code-First approach.

Code-First creates database schema by defining model as classes in code, which will be used as entities. Standard data anotations on properties in these entity classes can define constraints for columns:

public class Stock
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [MaxLength(8)]
    public string Symbol { get; set; }
}


When there is database, there is also need to solve migrations. If we release new version of program, we also might need to update database schema. Sqllite-net ORM doesn't provide migrations. This must be done by our code. We use SQLite Expert To write and debug migration SQL script. It is Free for personal and commercial use! This standalone program is not integrated to visual studio and allows us to see data in database, export DDL for table, run custom SQL commands on live database. This great tool miss just one functionality, but very important to write context for unit test especially for testing database schema migrations. This function is to export insert scripts for data, which ale already in database.

For that we use Visual Studio extension SQLite Toolbox. This extension will adds panel, where we can connect to database and use its functions. To export mentioned insert scripts navigate to SQL Server Compact Toolbx panel -> Right click on database connection -> Script Database -> Script database data -> check tables which are relevant -> select file to save SQL script


Warning!
SQLite Toolbox generates wrong names for named constraints and indexes in DDL scripts. So be careful using this export. Next DDL exports are from same database
SQLite Toolbox export:
CREATE INDEX [Address_ContactId_Address] ON [Address] ([ContactId] ASC);

SQLite Expert export:
CREATE INDEX "Address_ContactId" on "Address"("ContactId");

středa 4. března 2015

XMPP in .NET

Project Babel is based on XMPP protocol, so there is need for suitable comunication layer. Our solution contains two projects, which are participated in this comunication.
First project is classic windows desktop project, which has pretty much everything, what we wish for.
Second project is PCL (Portable class library) which can be compiled for silverlight, windows phone and even Windows RT. The bigger part of entire solution logic is situated in this PCL project, the better for us developers, because we can simply use this implementation on more platforms.

First approach to build this communication layer was to use some third party library, which can be added to PCL. There is one! A MatriX XMPP SDKThis is very nice library, which comes with binaries, that are compiled for all mentioned platforms and it even supports Xamarin. Everything is cool until it comes to a pricing. It is quite expensive one. So we tried to find another way.

A person with nick smiley22 wrote an opensource solution for XMPP protocol. It is called a S22.Xmpp. There are source codes on github so it looks pretty well. Last commit to this project is 27 Dec 2013 so it is more than year old. It can be both a very good sign of stable library which has implemented all features of XMPP and a bad sign of dead unfinished project without community. 

S22.Xmpp miss anonymous authentication and it has dependencies on classes, that are not available on PCL project, so we need to split implementations for platforms. Babel extends this S22 implementation with anonymous authentication and moves this logic from PCL to other platform dependent project.


For windows phone implementation we can use matrix library, which allows us to buy license for specific platform. Another way is to write our own implementation that compiles on windows phone.

pátek 5. prosince 2014

Reading of Smart Cards on Apple iOS devices - Part 2

In previous tutorial we have started reading smart card's data using Thursby's PKard reader and their SDK. We can read data from "Printed Information" and get data of facial image. Let's start to read from "CHUID". 

CHUID - Card Holder Unique Identifier 


The CHUID is defined to provide the basis for interoperable identification of individuals and to extend capabilities over magnetic stripe technology for Physical Access Control System applications. It contains a series of mandatory and optional tagged objects. Some of these include the Federal Agency Smart Credential Number (FASC-N), the Global Unique ID (GUID), and the Asymmetric Signature. 















FASC-N 


Let's dive deeper into grabbing FASC-N data. First step is to get CHUID data.

// CHUID
TSS_PKI_Data *CHUID = [TSS_PKI_Data dataObjectWithName:@"CHUID"];

Next step is to get NSData of FASC-N.

if (CHUID) {
   // FASC-N
   NSData *FASCN = [CHUID dataWithBerTlvTag:0x30];
   
   ...
}


Now it's necessary to get string format of FASC-N from NSData. It needs 3 steps to do it.
1) Convert FASC-N NSData to binary string. It should looks like this: "110101001110011....."
2) Divide this binary string into parts each 5 characters long.
3) Replace with corresponding character due to this part of code:
    
// The 40-character FASC-N credential is encoded as a 200 bit (25-byte) record    
// Packed BCD 4-Bit Decimal Format with Odd Parity.
         if ([bits isEqualToString:@"00001"]) return @"0";
    else if ([bits isEqualToString:@"10000"]) return @"1";
    else if ([bits isEqualToString:@"01000"]) return @"2";
    else if ([bits isEqualToString:@"11001"]) return @"3";
    else if ([bits isEqualToString:@"00100"]) return @"4";
    else if ([bits isEqualToString:@"10101"]) return @"5";
    else if ([bits isEqualToString:@"01101"]) return @"6";
    else if ([bits isEqualToString:@"11100"]) return @"7";
    else if ([bits isEqualToString:@"00010"]) return @"8";
    else if ([bits isEqualToString:@"10011"]) return @"9";
    else if ([bits isEqualToString:@"11010"]) return @"S"; // Start Sentinel
    else if ([bits isEqualToString:@"10110"]) return @"F"; // Field Separator

    else if ([bits isEqualToString:@"11111"]) return @"E"; // End Sentinel




















Final string format of FASC-N should looks like this: "S9999F9999F999999F1F1F1234567890199991E8"But how to interpret this string? I found all important informations in documentation in TIG SCEPACS v2.3 by the Physical Access Interagency Interoperability Working Group, December 20, 2005.  - Refer to section 6.1

You will find all informations about FASC-N in the documentation. Here we have FASC-N description:





and here we have FASC-N field description:







































Now it's easy to get anything from FASC-N string. Let's take our example string "S9999F9999F999999F1F1F1234567890199991E8", if you want to display Agency code, you have to look at the tables above. You will find, that Agency code is located after start sentinel, which has length of 1 digit. Agency code has 4 digits and it is located after sentinel. Required agency code is 9999. This way, you can continue parsing all the FASC-N string and get required parts of FASC-N. 


GIUD 


Extending our code we can start grabbing GUID data.

// CHUID
TSS_PKI_Data *CHUID = [TSS_PKI_Data dataObjectWithName:@"CHUID"];
NSUUID *UUID = nil;
VLFASCNData *FASCNData = nil;

if (CHUID) {
        
   // FASC-N
   NSData *FASCN = [CHUID dataWithBerTlvTag:0x30];
   if (FASCN) {
      FASCNData = [[VLFASCNData alloc] initWithFASCNData:FASCN];
   }
        
   // GUID
   NSData *GUID = [CHUID dataWithBerTlvTag:0x34];
   if (GUID) {
      // RFC 4122 - conformant UUID value
      UUID = [[NSUUID alloc]initWithUUIDBytes:GUID.bytes];
   }
}


X.509 / X.509 Extension 


At the end of this tutorial, here is example code how to grab subject name, email or Authority Key Identifier (AKI) / Subject Key Identifier (SKI) from X.509 extension.

NSArray *certs = [TSS_PKI_Identity currentIdentitiesWithAssertion:kAssertCertificateKeyUsageDigitalSignature];

NSString *subjectName;
NSString *emailAddress;
NSData *dataAKI;
NSData *dataSKI;
        
if ( certs.count > 0 ) {
            
   TSS_PKI_Identity *signatureCert = certs[0];
   subjectName = signatureCert.certificate.subjectName;
   emailAddress = signatureCert.certificate.subjectAltNames[X509SubjectAltNameRFC822];
            
   // Authority Key Identifier & Subject Key Identifier
   X509 *inCert = signatureCert.certificate.nativeX509;
   X509_EXTENSION *authorityKeyIdentifier = getExtensionFromCert(inCert, NID_authority_key_identifier);
   X509_EXTENSION *subjectKeyIdentifier = getExtensionFromCert(inCert, NID_subject_key_identifier);
            
   if (authorityKeyIdentifier) {
      dataAKI = [NSData dataWithBytes:authorityKeyIdentifier->value->data length:authorityKeyIdentifier->value->length];
   }
            
   if (subjectKeyIdentifier) {
       dataSKI = [NSData dataWithBytes:subjectKeyIdentifier->value->data length:subjectKeyIdentifier->value->length];
   }
}

It takes a time to get all the informations about reading specific data from smart card. I hope these tutorials will help you with development for iOS devices which needs to grab data from smart cards.

Reading of Smart Cards on Apple iOS devices - Part 1


In this tutorial, I would like to show you, how to read data from smart cards using iOS devices. First, what we need is to connect our iPhone / iPad with hardware device for reading smart cards and SDK to develop our own application. We have used PKard Reader from Thursby Software which is available in several form factors. 

Thursby Software's PKard Reader support the major standard smart card formats including PIV and PIV-I smart cards, the CAC / CAC Dual Persona (
Common Access Card) used by the U.S. military and DOD (Department of Defense).




Using Thursby's PKard Reader and PKard Toolkit for iOS, we can start reading data from smart card. I will show you how to read data from smart card's "Printed information", "CHUID" and get image data from "Facial Image".


Printed information

















// Printed Infromation
TSS_PKI_Data *printedInfo = [TSS_PKI_Data dataObjectWithName:@"Printed Information"];
        
if (printedInfo) {
            
  NSData *nameData = [printedInfo dataWithBerTlvTag:1];
  NSString *name = [[NSString alloc] initWithData:nameData encoding:NSUTF8StringEncoding];
  
  // other tags 
  NSData *employeeAffiliationData = [printedInfo dataWithBerTlvTag:2];
  NSData *expirationDateData = [printedInfo dataWithBerTlvTag:4];
  NSData *agencyCardSerialNumberData = [printedInfo dataWithBerTlvTag:5];
  NSData *issuerIdentificationData = [printedInfo dataWithBerTlvTag:6];
  NSData *organizationAffiliation1Data = [printedInfo dataWithBerTlvTag:7];
  NSData *organizationAffiliation2Data = [printedInfo dataWithBerTlvTag:8];
}


Facial image

If you need to get facial image data, you can do it like this:

// Facial image
NSData *facialImageData = nil;
TSS_PKI_Data *pkiFacialImageData = [TSS_PKI_Data dataObjectWithName:@"Facial Image"];
if (pkiFacialImageData) {
   NSData *cbeffData = [pkiFacialImageData cbeffData];
   
   if (cbeffData) {
      NistBiometricExchangeFormat *cbeff = [[NistBiometricExchangeFormat alloc] initWithCBEFFData:cbeffData];
      facialImageData = cbeff.jpeg;
   }
}

You can find sample project which is included in PKard Toolkit. In case, there are things you are not able to find in documentation, ask Thursby for the answer. Their support works great.

Next part we will read data from "CHUID" especially reading and formating FASC-N, GUID and from X509 extension Authority Key Identifier. 
 


pátek 21. listopadu 2014

Camera Confidentiality Conundrum

One of BABEL's features allows you to capture a photograph using your device's camera then send the image as an attachment. This ability is important for users so they can send images of documents or developing events to their contacts. Originally BABEL would use the device's native camera application to take the photo, however we discovered a serious security flaw with this approach. On many Android devices the native camera app would automatically save photos taken by BABEL, and if the user had cloud backup enabled would also upload them to their cloud service. Obviously this is an unacceptable privacy violation for BABEL so we needed to implement a solution.

The solution we came up with was to develop our own simple camera activity which BABEL could use to capture images. By controlling the image capturing process we can ensure that the photo stays private and is not saved outside of BABEL. This was not a simple task unfortunately, to recreate the vast set of features available in native camera apps would take an enormous amount of development time. So we had to aim to include only the most important camera features in our app.

The features we decided to include were auto-focus, zoom and flash. Auto-focus and Flash were relatively simple to implement using the Android camera API, but the zoom was slightly more complicated. Anybody used to touch-screen devices recognizes the pinch to zoom gesture, surprisingly there is no standard utility in the Android framework for this. So firstly we needed to implement a gesture detector for this that would control the camera's zoom level. Another issue we encountered was a large variance in the number of zoom levels available on each device, some cameras we tested supported 3-4 times as many zoom levels as others! To normalize the zoom behaviour across all devices we added scaling to our zoom gesture detector. Now if the user does a 'pinch' that travels half the length of the screen, the device will perform the maximum zoom change with smaller gestures performing a zoom relative to this maximum.

So with this new camera activity included in BABEL's next release can be confident that photos sent as attachments will remain private and not be accidentally leaked by a third party app. The need for a custom camera was an unanticipated problem which demonstrates the importance of our rigorous testing for each release. In the future we may revisit this custom camera to offer a better, more fully featured camera to BABEL users.

pátek 7. listopadu 2014

UIDocumentInteractionController in landscape mode

The whole iOS version of Babel works in portrait mode, but since we implemented attachments, we wanted to display attachment previews in landscape mode also. We tried it at first with UIDocumentInteractionController, which is displayed modally on UINavigationController.

So the whole app is in portrait mode and only UIDocumentInteractionController is in both portrait and landscape. It worked great, but when you at first turn the iphone to landscape and then display UIDocumentInteractionController, you will see the preview, but the navigation bar is missing. So you cannot get out of this screen, in iOS 8, it looks like this:




In iOS 7, it's ok:


We tried using QLPreviewViewController, but displaying it modally on UINavigationController was the same. Then we tried to push it on the navigation stack with pushViewController:animated and finally it worked on both iOS versions 7 and 8.


However there is one issue with QLPreviewViewController that only occurs in iOS 8 (iOS7 is ok). When you try to play some sound in this preview and turn to landscape, then when you go back (dismiss QLPreviewViewController), the sound continues playing. If you do the same thing in portrait, it stops playing.