Droidcedas : Signing E-Mail Amongst An Nfc Smart Bill Of Fare On Android

Last fourth dimension nosotros discussed how to access the SIM carte as well as work it equally a secure chemical element to get upwards Android applications. One of the primary problems amongst this approach is that since SIM cards are controlled past times the MNO whatever applets running on a commercial SIM have got to live approved past times them. Needless to say, that considerably limits flexibility. Fortunately, NFC-enabled Android devices tin communicate amongst practically whatever external contactless smart card, as well as y'all tin install anything on those. Let's explore how an NFC smart carte tin live used to sign e-mail on Android.

NFC smart cards

As discussed inwards previous posts, a smart carte is a secure execution surroundings on a unmarried chip, typically packaged inwards a credit-card sized plastic packet or the smaller 2FF/3FF/4FF shape factors when used equally a SIM card. Traditionally, smart cards connect amongst a carte reader using a number of gold-plated contact pads. The pads are used to both render ability to the carte as well as constitute series communication amongst its I/O interface. Size, electrical characteristics as well as communication protocols are defined inwards the 7816 series of ISO standards. Those traditional cards are referred to equally 'contact smart cards'. Contactless cards on the other mitt practise non bespeak to have got physical contact amongst the reader. They pull ability as well as communicate amongst the reader using RF induction. The communication protocol (T=CL) they work is defined inwards ISO 14443 and is really similar to the T1 protocol used past times contact cards. While smart cards that have got exclusively a contactless interface practise exist, dual-interface cards that have got both contacts as well as an antenna for RF communication are the majority. The underlying RF criterion used varies past times manufacturer, as well as both Type Influenza A virus subtype H5N1 as well as Type B are common. 

As we know, NFC has 3 criterion modes of operation: reader/writer (R/W), peer-to-peer (P2P) as well as carte emulation (CE) mode. All NFC-enabled Android devices back upwards R/W as well as P2P mode, as well as some tin render CE, either using a physical secure chemical element (SE) or software emulation. All that is needed to communicate amongst a contactless smart carte is the basic R/W mode, hence they tin live used on practically all Android devices amongst NFC support. This functionality is provided past times the IsoDep class. It provides exclusively basic command-response substitution functionality amongst the transceive() method, whatever higher score protocol bespeak to live implemented past times the customer application.

Securing email

There have got been quite a few novel services that are trying to reinvent secure e-mail inwards recent years. They are trying to larn inwards 'easy' for users past times taking attention of key administration as well as shifting all cryptographic operations to the server. As recent events have got reconfirmed, introducing an intermediary is non a really proficient thought if communication betwixt 2 parties is to live as well as rest secure. Secure e-mail itself is hardly a novel idea, as well as the 'old-school' way of implementing it relies on pubic key cryptography. Each political party is responsible for both protecting their individual key as well as verifying that the populace key of their counterpart matches their actual identity. The method used to verify identity is the biggest departure betwixt the 2 major secure e-mail standards inwards work today, PGP as well as S/MIME. PGP relies on the hence called 'web of trust', where everyone tin vouch for the identity of someone past times signing their key (usually subsequently coming together them inwards person), as well as keys amongst to a greater extent than signatures tin live considered trustworthy. S/MIME, on the other hand, relies on PKI as well as X.509 certificates, where the issuing authorization (CA) is relied upon to verify identity when issuing a certificate. PGP has the payoff of existence decentralized, which makes it harder to interruption the arrangement past times compromising  a unmarried entity, equally has happened amongst a number of populace CAs inwards recent years. However, it requires much to a greater extent than user involvement as well as is peculiarly challenging to novel users. Additionally, patch many commercial as well as opened upwards source PGP implementations practise exist, most mainstream e-mail clients practise non back upwards PGP out of the box as well as require the installation of plugins as well as additional software. On the other hand, all major proprietary (Outlook variants, Mail.app, etc) as well as opened upwards source (Thunderbird) e-mail clients have got built-in as well as mature S/MIME implementations. We volition work S/MIME for this illustration because it is a lot easier to larn started amongst as well as test, but the techniques described tin live used to implement PGP-secured e-mail equally well. Let's outset utter over how S/MIME is implemented.

Signing amongst S/MIME

The S/MIME, or Secure/Multipurpose Internet Mail Extensions, standard defines how to include signed and/or encrypted content inwards e-mail messages. It specified both the procedures for creating  signed or encrypted (enveloped) content as well as the MIME media types to work when adding them to the message. For example, a signed message would have got a share amongst the Content-Type: application/pkcs7-signature; name=smime.p7s; smime-type=signed-data which contains the message signature as well as whatever associated attributes. To an e-mail customer that does non back upwards S/MIME, similar most Web postal service apps, this would hold off similar an attachment called smime.p7s. S/MIME-compliant clients would instead parse as well as verify the signature as well as display some visual indication showing the signature verification status.

The to a greater extent than interesting inquiry all the same is what's inwards smime.p7s? The 'p7' stands for PKCS#7, which is the predecessor of the electrical flow Cryptographic Message Syntax (CMS). CMS defines structures used to packet signed, authenticated or encrypted content as well as related attributes. As amongst most PKI X.509-derived standards, those structures are ASN.1 based as well as encoded into binary using DER, but similar certificates as well as CRLs. They are sequences of other structures, which are inwards plow composed of yet other ASN.1 structures, which are..., basically sequences all the way down. Let's attempt to hold off at the higher-level ones used for signed email. The CMS construction describing signed content is predictably called SignedData as well as looks similar this:

SignedData ::= SEQUENCE {         version CMSVersion,         digestAlgorithms DigestAlgorithmIdentifiers,         encapContentInfo EncapsulatedContentInfo,         certificates [0] IMPLICIT CertificateSet OPTIONAL,         crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,         signerInfos SignerInfos } 

Here digestAlgorithms contains the OIDs of the hash algorithms used to make the signature (one for each signer) as well as encapContentInfo describes the information that was signed, as well as tin optionally incorporate the actual data. The optional certificates as well as crls fields are intended to help verify the signer certificate. If absent, the verifier is responsible for collecting them past times other means. The most interesting part, signerInfos, contains the actual signature as well as information virtually the signer. It looks similar this:

SignerInfo ::= SEQUENCE {         version CMSVersion,         sid SignerIdentifier,         digestAlgorithm DigestAlgorithmIdentifier,         signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,         signatureAlgorithm SignatureAlgorithmIdentifier,         signature SignatureValue,         unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL } 

Besides the signature value as well as algorithms used, SignedInfo contains signer identifier used to discover the exact certificate that was used as well as a number of optional signed as well as unsigned attributes. Signed attributes are included when producing the signature value as well as tin incorporate additional information virtually the signature, such equally signing time. Unsigned attribute are non covered past times the signature value, but tin incorporate signed information themselves, such equally counter signature (an additional signature over the signature value).

To total this up, inwards gild to make a S/MIME signed message, nosotros bespeak to sign the e-mail contents as well as whatever attributes, generate the SignedInfo structure, roll it into a SignedData, DER encode the effect as well as add together it to the message using the appropriate MIME type. Sound easy, right? Let's how this tin live done on Android.

Using S/MIME on Android

On whatever platform, y'all bespeak 2 things inwards gild to generate an S/MIME message: a cryptographic provider that tin perform the actual signing using an asymmetric key as well as an ASN.1 parser/generator inwards gild to generate the SignedData structure. Android has JCE providers that back upwards RSA, late fifty-fifty amongst hardware-backed keys. What's left is an ASN.1 generator. While ASN.1 as well as DER/BER have got been unopen to for ages, as well as at that spot are quite a few parsers/generators, the practically useful choices  are non that many. No 1 actually generates code straight from the ASN.1 modules found inwards related standards, most libraries implement exclusively the necessary parts, edifice on available components. Both of Android's major cryptographic libraries, OpenSSL as well as Bouncy Castle incorporate ASN.1 parser/generators as well as have got back upwards for CMS. The related API's are non populace though, hence nosotros bespeak to include our ain libraries.

As usual nosotros plow to Spongy Castle, which is provides all of Bouncy Castle's functionality nether a dissimilar namespace. In gild to live able physical care for CMS as well as generate S/MIME messages, nosotros bespeak the optional scpkix as well as scmail packages. The outset 1 contains PKIX as well as CMS related classes, as well as the mo 1 implements S/MIME. However, at that spot is a twist: Android lacks some of the classes required for generating S/MIME messages. As y'all may know, Android has implementations for most criterion Java APIs, amongst a few exceptions, most notably the GUI widget related AWT as well as Swing packages. Those are rarely missed, because Android has its ain widget as well as graphics libraries. However, likewise widgets AWT contains classes related to MIME media types equally well. Unfortunately, some of those are  used inwards libraries that bargain amongst MIME objects, such equally JavaMail as well as the Bouncy Castle S/MIME implementation. JavaMail versions that include alternative AWT implementations, repackaged for Android have got been available for some time, but since they work some non-standard packet names, they are non a drop-in replacement. That applies to Spongy Castle equally well: some source code modifications are required inwards gild to larn scmail to piece of work amongst the javamail-android library.

With that sorted out, generating an S/MIME message on Android is but a thing of finding the signer key as well as certificate as well as using the proper Bouncy Castle as well as JavaMail APIs to generate as well as ship the message:

PrivateKey signerKey = KeyChain.getPrivateKey(ctx, "smime"); X509Certificate[] chain = KeyChain.getCertificateChain(ctx, "smime"); X509Certificate signerCert = chain[0]; X509Certificate caCert = chain[1];  SMIMESignedGenerator gen = novel SMIMESignedGenerator(); gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder()                     .setProvider("AndroidOpenSSL")                     .setSignedAttributeGenerator(                             novel AttributeTable(signedAttrs))                     .build("SHA512withRSA", signerKey, signerCert)); Store certs = novel JcaCertStore(Arrays.asList(signerCert, caCert)); gen.addCertificates(certs);  MimeMultipart mm = gen.generate(mimeMsg, "SC"); MimeMessage signedMessage = novel MimeMessage(session); Enumeration headers = mimeMsg.getAllHeaderLines(); patch (headers.hasMoreElements()) {     signedMessage.addHeaderLine((String) headers.nextElement()); } signedMessage.setContent(mm); signedMessage.saveChanges();  Transport.send(signedMessage); 

Here nosotros outset larn the signer key as well as certificate using the KeyChain API as well as and hence create an S/MIME generator past times specifying the key, certificate, signature algorithm as well as signed attributes. Note that nosotros specify the AndroidOpenSSL provider explicitly which is the exclusively 1 that tin work hardware-backed keys. This is exclusively required if y'all changed the default provider gild when installing Spongy Castle, past times default AndroidOpenSSL is the preferred JCE provider. We as well as hence add together the certificates nosotros desire to include inwards the generated SignedData as well as generate a multi-part MIME message that includes both the master message (mimeMsg) as well as the signature. Finally nosotros ship the message using the JavaMail Transport class. The JavaMail Session initialization is omitted from the illustration above, regard the sample app for how to laid it upwards to work Gmail's SMTP server. This requires the Gmail trace of piece of work organisation human relationship password to live specified, but amongst a piffling to a greater extent than piece of work it tin live replaced amongst an OAuth token y'all tin obtain from the arrangement AccountManager.

So what virtually smart cards?

Using a MuscleCard to sign email

In gild to sign e-mail using keys stored on a smart carte nosotros bespeak a few things: 
  • a dual-interface smart cards that supports RSA keys
  • a crypto applet that allows us to sign information amongst those keys
  • some kind of middleware that exposes carte functionality through a criterion crypto API
Most recent dual-interface JavaCards fulfill our requirements, but nosotros volition live using a NXP J3A081 which supports JavaCard 2.2.2 as well as 2048-bit RSA keys. When it comes to opened upwards source crypto applets though, unfortunately the choices are quite limited. Just virtually the exclusively 1 that is both full-featured as well as good supported inwards middleware libraries is the venerable MuscleCard applet. We volition live using 1 of the fairly recent forks, updated to back upwards JavaCard 2.2 as well as extended APDUs. To load the applet on the carte y'all bespeak a GlobalPlatform-compatible loader application, similar GPJ, as well as of course of teaching the CardManager keys. Once y'all have got initialized it, y'all tin personalize it past times generating or importing keys as well as certificates. After that the carte tin live used inwards whatever application that supports PKCS#11, for illustration Thunderbird as well as Firefox. Because the carte is dual-interface, practically whatever smart carte reader tin live used on desktops. When the OpenSC PKCS#11 module is loaded inwards Thunderbird the carte volition present upwards inwards the Security Devices dialog similar this:


If the certificate installed inwards the carte has your e-mail inwards the Subject Alternative Name extension, y'all should live able ship signed as well as encrypted emails (if y'all have got the recipient's certificate, of course). But how to hit the same thing inwards Android?

Using MuscleCard on Android

Android doesn't back upwards PKCS#11 modules, hence inwards gild to expose the cards crypto functionality nosotros could implement a custom JCE provider that provides card-backed implementations of the Signature as well as KeyStrore engine classes. That is quite a flake of piece of work though, as well as since nosotros are exclusively targeting the Bouncy Castle S/MIME API, nosotros tin larn away past times implementing the ContentSigner interface. It provides an OutputStream clients write information to live signed to, an AlgorithmIdentifer for the signature method used as well as a getSignature() method that returns the actual signature value. Our MuscleCard-backed implementation could hold off similar this:

class MuscleCardContentSigner implements ContentSigner {      individual ByteArrayOutputStream baos = novel ByteArrayOutputStream();     individual MuscleCard msc;     individual String pin; ...     @Override     populace byte[] getSignature() {         msc.select();         msc.verifyPin(pin);          byte[] information = baos.toByteArray();         baos.reset();         render msc.sign(data);     } } 

Here the MuscleCard class is our 'middleware' as well as encapsulates the card's RSA signature functionality. It is implemented past times sending the required command APDUs for each functioning using Android's IsoDep API as well as aggregating as well as converting the effect equally needed. For example, the verifyPin() is implemented similar this:

class MuscleCard {     individual IsoDep tag;     populace boolean verifyPin(String pin) throws IOException {       String cmd = String.format("B0 42 01 00 %02x %s", pin.length(),                                  toHex(pin.getBytes("ASCII")));       ResponseApdu rapdu = novel ResponseApdu(tag.transceive(fromHex(cmd)));       if (rapdu.getSW() != SW_SUCCESS) {          render false;       }        render true;    } } 

Signing is a piffling to a greater extent than complicated because it involves creating as well as updating temporary I/O objects, but follows the same principle. Since the applet does non back upwards padding or hashing, nosotros bespeak to generate as well as pad the PKCS#1 (or PSS) signature block on Android as well as ship the consummate information to the card. Finally, nosotros bespeak to plug our signer implementation into the Bouncy Castle CMS generator:

ContentSigner mscCs = novel MuscleCardContentSigner(muscleCard, pin); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(                            novel JcaDigestCalculatorProviderBuilder()                            .setProvider("SC")                            .build()).build(mscCs, cardCert)); 

After that the signed message tin live generated precisely similar when using local key shop keys. Of course, at that spot are a few caveats. Since apps cannot command when an NFC connectedness is established, nosotros tin exclusively sign information subsequently the carte has been picked upwards past times the device as well as nosotros have got received an Intent amongst a alive IsoDep instance. Additionally, since signing tin have got a few seconds, nosotros bespeak to brand certain the connectedness is non broken past times placing the device on top of the carte (or work some kind of awkward instance amongst a carte slot). Our implementation also takes a few shortcuts past times hard-coding the certificate object ID as well as size, equally good equally the carte PIN, but those tin live remedied amongst a piffling to a greater extent than code. The UI of our homebrew S/MIME customer is shown below.


After y'all import a PKCS#12 file inwards the arrangement credential shop y'all tin sign emails using the imported keys. The 'Sign amongst NFC' push clitoris is exclusively enabled when a compatible carte has been detected. The easiest way to verify the e-mail signature is to ship a message to a desktop customer that supports S/MIME. There are also a few Android e-mail apps that back upwards S/MIME, but setup tin live a flake challenging because they frequently work their ain trust as well as key stores. You tin also dump the generated message to external storage using MimeMessage.writeTo() as well as and hence parse the CMS construction using the OpenSSL cms command:

$ openssl cms -cmsout -in signed.message -noout -print CMS_ContentInfo:    contentType: pkcs7-signedData (1.2.840.113549.1.7.2)   d.signedData:      version: 1     digestAlgorithms:         algorithm: sha512 (2.16.840.1.101.3.4.2.3)         parameter: NULL     encapContentInfo:        eContentType: pkcs7-data (1.2.840.113549.1.7.1)       eContent: <absent>     certificates:       d.certificate:          cert_info:            version: 2           serialNumber: iv           signature:              algorithm: sha1WithRSAEncryption (1.2.840.113549.1.1.5)             ...     crls:       <empty>     signerInfos:         version: 1         d.issuerAndSerialNumber:            issuer: C=JP, ST=Tokyo, CN=keystore-test-CA           serialNumber: 3         digestAlgorithm:            algorithm: sha512 (2.16.840.1.101.3.4.2.3)           parameter: NULL         signedAttrs:             object: contentType (1.2.840.113549.1.9.3)             value.set:               OBJECT:pkcs7-data (1.2.840.113549.1.7.1)              object: signingTime (1.2.840.113549.1.9.5)             value.set:               UTCTIME:Oct 25 16:25:29 2013 GMT              object: messageDigest (1.2.840.113549.1.9.4)             value.set:               OCTET STRING:                 0000 - 88 bd 87 84 xv 53 3d d8-72 64 c7 36 f8   .....S=.rd.6.                 000d - b0 f3 39 ninety b2 a4 77 56-5c 9f e4 2e 7c   ..9...wV\...|                 001a - 7d 2e 0b 08 b4 b7 e7 6c-e9 b6 61 00 xiii   }......l..a..                 0027 - 25 62 69 2a bc 08 5b 4c-4f c9 73 cf d3   %bi*..[LO.s..                 0034 - c6 1e 51 c2 5f c1 64 77-3b 45 e2 cb      ..Q._.dw;E..         signatureAlgorithm:            algorithm: rsaEncryption (1.2.840.113549.1.1.1)           parameter: NULL         signature:            0000 - a0 d0 ce 35 46 8c f9 cd-e5 db ed d8 e3 f0 08   ...5F..........           ...         unsignedAttrs:           <empty> 

Email encryption using the NFC smart carte tin live implemented inwards a similar fashion, but this fourth dimension the carte volition live required when decrypting the message.

Summary

Practically all NFC-enabled Android devices tin live used to communicate amongst a contactless or dual-interface smart card. If the interface of carte applications is known, it is fairly slow to implement an Android element that exposes carte functionality via a custom interface, or fifty-fifty equally a criterion JCE provider. The card's cryptographic functionality tin as well as hence live used to secure e-mail or render HTTPS as well as VPN authentication. This could live peculiarly useful when dealing amongst keys that have got been generated on the carte as well as cannot live extracted. If a PKCS#12 backup file is available, importing the file inwards the arrangement credential shop tin render a amend user sense as well as comparable safety levels if the device has a hardware-backed credential store. 
0 Komentar untuk "Droidcedas : Signing E-Mail Amongst An Nfc Smart Bill Of Fare On Android"

Back To Top