Sunday, January 29, 2012

This is the original Bouncy Castle 1.34 specification.
Bouncy Castle Crypto Package

Bouncy Castle Crypto Package


1.0 Introduction

The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms. The package is organised so that it contains a light-weight API suitable for use in any environment (including the newly released J2ME) with the additional infrastructure to conform the algorithms to the JCE framework.

This software is distributed under a license based on the MIT X Consortium license. To view the license, see here

If you have the full package you will have six jar files, bcprov*.jar which contains the BC provider, jce-*.jar which contains the JCE provider, clean room API, and bcmail*.jar which contains the mail API.

Note: if you are using JDK 1.0, you will just find a class hierarchy in the classes directory.

To view examples, look at the test programs in the packages:

  • org.bouncycastle.crypto.test
  • org.bouncycastle.jce.provider.test

To verify the packages, run the following Java programs with the appropriate classpath:

  • java org.bouncycastle.crypto.test.RegressionTest
  • java org.bouncycastle.jce.provider.test.RegressionTest

2.0 Patents

Some of the algorithms in the Bouncy Castle APIs are patented in some places. It is upon the user of the library to be aware of what the legal situation is in their own situation, however we have been asked to specifically mention the patent below at the request of the patent holder.

The IDEA encryption algorithm is patented in the USA, Japan, and Europe including at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland and the United Kingdom. Non-commercial use is free, however any commercial products that make use of IDEA are liable for royalties. Please see www.mediacrypt.com for further details.

3.0 Specifications

  • clean room implementation of the JCE API
  • light-weight cryptographic API consisting of support for
    • BlockCipher
    • BufferedBlockCipher
    • AsymmetricBlockCipher
    • BufferedAsymmetricBlockCipher
    • StreamCipher
    • BufferedStreamCipher
    • KeyAgreement
    • IESCipher
    • Digest
    • Mac
    • PBE
    • Signers
  • JCE compatible framework for a Bouncy Castle provider

4.0 Light-weight API

This API has been specifically developed for those circumstances where the rich API and integration requirements of the JCE are not required.

However as a result, the light-weight API requires more effort and understanding on the part of a developer to initialise and utilise the algorithms.

4.1 Example

To utilise the light-weight API in a program, the fundamentals are as follows;



 /*
  * This will use a supplied key, and encrypt the data
  * This is the equivalent of DES/CBC/PKCS5Padding
  */
 BlockCipher engine = new DESEngine();
 BufferedBlockCipher cipher = new PaddedBlockCipher(new CBCCipher(engine));

 byte[] key = keyString.getBytes();
 byte[] input = inputString.getBytes();

 cipher.init(true, new KeyParameter(key));

 byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
 
 int outputLen = cipher.processBytes(input, 0, input.length, cipherText, 0);
 try
 {
  cipher.doFinal(cipherText, outputLen);
 }
 catch (CryptoException ce)
 {
  System.err.println(ce);
  System.exit(1);
 }

4.2 Algorithms

The light-weight API has built in support for the following:

Symmetric (Block)

The base interface is BlockCipher and has the following implementations which match the modes the block cipher can be operated in.

NameConstructorNotes
BufferedBlockCipherBlockCipher
CBCBlockCipherBlockCipher
CFBBlockCipherBlockCipher, block size (in bits)
OFBBlockCipherBlockCipher, block size (in bits)
SICBlockCipherBlockCipher, block size (in bits)Also known as CTR mode
OpenPGPCFBBlockCipherBlockCipher
GOFBBlockCipherBlockCipherGOST OFB mode

BufferedBlockCipher has a further sub-classes

NameConstructorNotes
PaddedBufferedBlockCipherBlockCiphera buffered block cipher that can use padding - default PKCS5/7 padding
CTSBlockCipherBlockCipherCipher Text Stealing

The following paddings can be used with the PaddedBufferedBlockCipher.

NameDescription
PKCS7PaddingPKCS7/PKCS5 padding
ISO10126d2PaddingISO 10126-2 padding
X932PaddingX9.23 padding
ISO7816d4PaddingISO 7816-4 padding (ISO 9797-1 scheme 2)
ZeroBytePaddingPad with Zeros (not recommended)

The following cipher engines are implemented that can be used with the above modes.

NameKeySizes (in bits) Block SizeNotes
AESEngine0 .. 256 128 bit
AESWrapEngine0 .. 256 128 bitImplements FIPS AES key wrapping
BlowfishEngine0 .. 448 64 bit
CAST5Engine0 .. 128 64 bit
CAST6Engine0 .. 256 128 bit
DESEngine6464 bit
DESedeEngine128, 19264 bit
DESedeWrapEngine128, 19264 bitImplements Draft IETF DESede key wrapping
IDEAEngine12864 bit
RC2Engine0 .. 1024 64 bit
RC532Engine0 .. 128 64 bitUses a 32 bit word
RC564Engine0 .. 128 128 bitUses a 64 bit word
RC6Engine0 .. 256 128 bit
RijndaelEngine0 .. 256 128 bit, 160 bit, 192 bit, 224 bit, 256 bit
SkipjackEngine0 .. 128 64 bit
TwofishEngine128, 192, 256 128 bit
SerpentEngine128, 192, 256 128 bit
GOST28147Engine25664 bitHas a range of S-boxes
CamelliaEngine128, 192, 256128 bit

Symmetric (Stream)

The base interface is StreamCipher and has the following implementations which match the modes the stream cipher can be operated in.

NameConstructorNotes
BlockStreamCipherBlockCipher

The following cipher engines are implemented that can be used with the above modes.

NameKeySizes (in bits) Notes
RC4Engine40 .. 2048

Block Asymmetric

The base interface is AsymmetricBlockCipher and has the following implementations which match the modes the cipher can be operated in.

NameConstructorNotes
BufferedAsymmetricBlockCipherAsymmetricBlockCipher
OAEPEncodingAsymmetricBlockCipher
PKCS1EncodingAsymmetricBlockCipher
ISO9796d1EncodingAsymmetricBlockCipherISO9796-1

The following cipher engines are implemented that can be used with the above modes.

NameKeySizes (in bits)Notes
RSAEngineany multiple of 8 large enough for the encoding.
ElGamalEngineany multiple of 8 large enough for the encoding.

Digest

The base interface is Digest and has the following implementations

NameOutput (in bits)Notes
MD2Digest128
MD4Digest128
MD5Digest128
RipeMD128Digest128basic RipeMD
RipeMD160Digest160enhanced version of RipeMD
RipeMD256Digest256expanded version of RipeMD128
RipeMD320Digest320expanded version of RipeMD160
SHA1Digest160
SHA224Digest224FIPS 180-2
SHA256Digest256FIPS 180-2
SHA384Digest384FIPS 180-2
SHA512Digest512FIPS 180-2
TigerDigest192The Tiger Digest.
GOST3411Digest256The GOST-3411 Digest.
WhirlpoolDigest512The Whirlpool Digest.

MAC

The base interface is Mac and has the following implementations

NameOutput (in bits)Notes
CBCBlockCipherMacblocksize/2 unless specified
CFBBlockCipherMacblocksize/2, in CFB 8 mode, unless specified
HMacdigest length

PBE

The base class is PBEParametersGenerator and has the following sub-classes

NameConstructorNotes
PKCS5S1ParametersGeneratorDigest
PKCS5S2ParametersGenerator Uses SHA1/Hmac as defined
PKCS12ParametersGeneratorDigest
OpenSSLPBEParametersGenerator Uses MD5 as defined

Key Agreement

Two versions of Diffie-Hellman key agreement are supported, the basic version, and one for use with long term public keys. Two versions of key agreement using Elliptic Curve cryptography are also supported, standard Diffie-Hellman key agreement and standard key agreement with co-factors.

The agreement APIs are in the org.bouncycastle.crypto.agreement package. Classes for generating Diffie-Hellman parameters can be found in the org.bouncycastle.crypto.params and org.bouncycastle.crypto.generators packages.

IESCipher

The IES cipher is based on the one described in IEEE P1363a (draft 10), for use with either traditional Diffie-Hellman or Elliptic Curve Diffie-Hellman.

Note: At the moment this is still a draft, don't use it for anything that may be subject to long term storage, the key values produced may well change as the draft is finalised.

Signers

DSA, ECDSA, ISO-9796-2, GOST-3410-94, GOST-3410-2001, and RSA-PSS are supported by the org.bouncycastle.crypto.signers package. Note: as these are light weight classes, if you need to use SHA1 or GOST-3411 (as defined in the relevant standards) you'll also need to make use of the appropriate digest class in conjunction with these. Classes for generating DSA and ECDSA parameters can be found in the org.bouncycastle.crypto.params and org.bouncycastle.crypto.generators packages.

4.3 ASN.1 package

The light-weight API has direct interfaces into a package capable of reading and writing DER-encoded ASN.1 objects and for the generation of X.509 V3 certificate objects and PKCS12 files. BER InputStream and OutputStream classes are provided as well.

5.0 Bouncy Castle Provider

The Bouncy Castle provider is a JCE compliant provider that is a wrapper built on top of the light-weight API.

The advantage for writing application code that uses the provider interface to cryptographic algorithms is that the actual provider used can be selected at run time. This is extremely valuable for applications that may wish to make use of a provider that has underlying hardware for cryptographic computation, or where an application may have been developed in an environment with cryptographic export controls.

5.1 Example

To utilise the JCE provider in a program, the fundamentals are as follows;


 /*
  * This will generate a random key, and encrypt the data
  */
 Key  key;
 KeyGenerator keyGen;
 Cipher  encrypt;

 Security.addProvider(new BouncyCastleProvider());

 try
 {
  // "BC" is the name of the BouncyCastle provider
  keyGen = KeyGenerator.getInstance("DES", "BC");
  keyGen.init(new SecureRandom());

  key = keyGen.generateKey();

  encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
 }
 catch (Exception e)
 {
  System.err.println(e);
  System.exit(1);
 }

 encrypt.init(Cipher.ENCRYPT_MODE, key);

 bOut = new ByteArrayOutputStream();
 cOut = new CipherOutputStream(bOut, encrypt);

 cOut.write("plaintext".getBytes());
 cOut.close();

 // bOut now contains the cipher text

The provider can also be configured as part of your environment via static registration by adding an entry to the java.security properties file (found in $JAVA_HOME/jre/lib/security/java.security, where $JAVA_HOME is the location of your JDK/JRE distribution). You'll find detailed instructions in the file but basically it comes down to adding a line:


   security.provider.<n>=org.bouncycastle.jce.provider.BouncyCastleProvider


Where <n> is the preference you want the provider at (1 being the most prefered).

Where you put the jar is up to mostly up to you, although with jdk1.3 and jdk1.4 the best (and in some cases only) place to have it is in $JAVA_HOME/jre/lib/ext. Note: under Windows there will normally be a JRE and a JDK install of Java if you think you have installed it correctly and it still doesn't work chances are you have added the provider to the installation not being used.

Note: with JDK 1.4 and later you will need to have installed the unrestricted policy files to take full advantage of the provider. If you do not install the policy files you are likely to get something like the following:


       java.lang.SecurityException: Unsupported keysize or algorithm parameters
               at javax.crypto.Cipher.init(DashoA6275)
The policy files can be found at the same place you downloaded the JDK.

5.2 Algorithms

Symmetric (Block)

Modes:

  • ECB
  • CBC
  • OFB(n)
  • CFB(n)
  • SIC (also known as CTR)
  • OpenPGPCFB
  • CTS (equivalent to CBC/WithCTS)
  • GOFB

Where (n) is a multiple of 8 that gives the blocksize in bits, eg, OFB8. Note that OFB and CFB mode can be used with plain text that is not an exact multiple of the block size if NoPadding has been specified.

Padding Schemes:

  • No padding
  • PKCS5/7
  • ISO10126/ISO10126-2
  • ISO7816-4/ISO9797-1
  • X9.23/X923
  • TBC
  • ZeroByte
  • withCTS (if used with ECB mode)

When placed together this gives a specification for an algorithm as;

  • DES/CBC/X9.23Padding
  • DES/OFB8/NoPadding
  • IDEA/CBC/ISO10126Padding
  • IDEA/CBC/ISO7816-4Padding
  • SKIPJACK/ECB/PKCS7Padding
  • DES/ECB/WithCTS

Note: default key sizes are in bold.

NameKeySizes (in bits) Block SizeNotes
AES0 .. 256 (192)128 bit
AESWrap0 .. 256 (192)128 bitA FIPS AES key wrapper
Blowfish0 .. 448 (448)64 bit
CAST50 .. 128(128)64 bit
CAST60 .. 256(256)128 bit
DES6464 bit
DESede128, 19264 bit
DESedeWrap128, 192128 bitA Draft IETF DESede key wrapper
IDEA128 (128)64 bit
RC20 .. 1024 (128)64 bit
RC50 .. 128 (128)64 bitUses a 32 bit word
RC5-640 .. 256 (256)128 bitUses a 64 bit word
RC60 .. 256 (128)128 bit
Rijndael0 .. 256 (192)128 bit
Skipjack0 .. 128 (128)64 bit
Twofish128, 192, 256 (256)128 bit
Serpent128, 192, 256 (256)128 bit
GOST2814725664 bit
Camellia128, 192, 256128 bit

Symmetric (Stream)

Note: default key sizes are in bold.

NameKeySizes (in bits)Notes
RC440 .. 2048 bits (128)

Block Asymmetric

Encoding:

  • OAEP - Optimal Asymmetric Encryption Padding
  • PCKS1 - PKCS v1.5 Padding
  • ISO9796-1 - ISO9796-1 edition 1 Padding

Note: except as indicated in PKCS 1v2 we recommend you use OAEP, as mandated in X9.44.

When placed together with RSA this gives a specification for an algorithm as;

  • RSA/NONE/NoPadding
  • RSA/NONE/PKCS1Padding
  • RSA/NONE/OAEPWithMD5AndMGF1Padding
  • RSA/NONE/OAEPWithSHA1AndMGF1Padding
  • RSA/NONE/OAEPWithSHA224AndMGF1Padding
  • RSA/NONE/OAEPWithSHA256AndMGF1Padding
  • RSA/NONE/OAEPWithSHA384AndMGF1Padding
  • RSA/NONE/OAEPWithSHA512AndMGF1Padding
  • RSA/NONE/ISO9796-1Padding
NameKeySizes (in bits)Notes
RSAany multiple of 8 bits large enough for the encryption(2048)
ElGamalany multiple of 8 bits large enough for the encryption(1024)

Key Agreement

Diffie-Hellman key agreement is supported using the "DH", "ECDH", and "ECDHC" (ECDH with cofactors) key agreement instances.

Note: with basic "DH" only the basic algorithm fits in with the JCE API, if you're using long-term public keys you may want to look at the light-weight API.

ECIES

An implementation of ECIES (stream mode) as described in IEEE P 1363a.

Note: At the moment this is still a draft, don't use it for anything that may be subject to long term storage, the key values produced may well change as the draft is finalised.

Digest

NameOutput (in bits)Notes
GOST3411256
MD2128
MD4128
MD5128
RipeMD128128basic RipeMD
RipeMD160160enhanced version of RipeMD
RipeMD256Digest256expanded version of RipeMD128
RipeMD320Digest320expanded version of RipeMD160
SHA1160
SHA-224224FIPS 180-2
SHA-256256FIPS 180-2
SHA-384384FIPS 180-2
SHA-512512FIPS 180-2
Tiger192
Whirlpool512

MAC

NameOutput (in bits)Notes
Any MAC based on a block cipher, CBC (the default) and CFB modes.half the cipher's block size (usually 32 bits)
HMac-MD2128
HMac-MD4128
HMac-MD5128
HMac-RipeMD128128
HMac-RipeMD160160
HMac-SHA1160
HMac-SHA224224
HMac-SHA256256
HMac-SHA384384
HMac-SHA512512
HMac-Tiger192

Examples:

  • DESMac
  • DESMac/CFB8
  • DESedeMac
  • DESedeMac/CFB8
  • DESedeMac64
  • SKIPJACKMac
  • SKIPJACKMac/CFB8
  • IDEAMac
  • IDEAMac/CFB8
  • RC2Mac
  • RC2Mac/CFB8
  • RC5Mac
  • RC5Mac/CFB8
  • ISO9797ALG3Mac

Signature Algorithms

Schemes:

  • GOST3411withGOST3410 (GOST3411withGOST3410-94)
  • GOST3411withECGOST3410 (GOST3411withGOST3410-2001)
  • MD2withRSA
  • MD5withRSA
  • SHA1withRSA
  • RIPEMD128withRSA
  • RIPEMD160withRSA
  • RIPEMD256withRSA
  • SHA1withDSA
  • SHA1withECDSA
  • SHA224withECDSA
  • SHA256withECDSA
  • SHA384withECDSA
  • SHA512withECDSA
  • SHA224withRSA
  • SHA256withRSA
  • SHA384withRSA
  • SHA512withRSA
  • SHA1withRSAandMGF1
  • SHA256withRSAandMGF1
  • SHA384withRSAandMGF1
  • SHA512withRSAandMGF1

PBE

Schemes:

  • PKCS5S1, any Digest, any symmetric Cipher, ASCII
  • PKCS5S2, SHA1/HMac, any symmetric Cipher, ASCII
  • PKCS12, any Digest, any symmetric Cipher, Unicode

Defined in Bouncy Castle JCE Provider

NameKey Generation SchemeKey Length (in bits)
PBEWithMD5AndDESPKCS5 Scheme 164
PBEWithMD5AndRC2PKCS5 Scheme 1128
PBEWithSHA1AndDESPKCS5 Scheme 164
PBEWithSHA1AndRC2PKCS5 Scheme 1128
PBEWithSHAAnd2-KeyTripleDES-CBCPKCS12128
PBEWithSHAAnd3-KeyTripleDES-CBCPKCS12192
PBEWithSHAAnd128BitRC2-CBCPKCS12128
PBEWithSHAAnd40BitRC2-CBCPKCS1240
PBEWithSHAAnd128BitRC4PKCS12128
PBEWithSHAAnd40BitRC4PKCS1240
PBEWithSHAAndTwofish-CBCPKCS12256
PBEWithSHAAndIDEA-CBCPKCS12128

5.3 Certificates

The Bouncy Castle provider will read X.509 certficates (v2 or v3) as per the examples in the java.security.cert.CertificateFactory class. They can be provided either in the normal PEM encoded format, or as DER binaries.

The CertificiateFactory will also read X.509 CRLs (v2) from either PEM or DER encodings.

In addition to the classes in the org.bouncycastle.ans1.x509 package for certificate generation a more JCE "friendly" class is provided in the package org.bouncycastle.jce. The JCE "friendly" class supports RSA, DSA, and EC-DSA.

5.4 Keystore

The Bouncy Castle package has three implementation of a keystore.

The first "BKS" is a keystore that will work with the keytool in the same fashion as the Sun "JKS" keystore. The keystore is resistent to tampering but not inspection.

The second, Keystore.BouncyCastle, or Keystore.UBER will only work with the keytool if the password is provided on the command line, as the entire keystore is encrypted with a PBE based on SHA1 and Twofish. PBEWithSHAAndTwofish-CBC. This makes the entire keystore resistant to tampering and inspection, and forces verification. The Sun JDK provided keytool will attempt to load a keystore even if no password is given, this is impossible for this version. (One might wonder about going to all this trouble and then having the password on the command line! New keytool anyone?).

In the first case, the keys are encrypted with 3-Key-TripleDES.

The third is a PKCS12 compatabile keystore. PKCS12 provides a slightly different situation from the regular key store, the keystore password is currently the only password used for storing keys. Otherwise it supports all the functionality required for it to be used with the keytool. In some situations other libraries always expect to be dealing with Sun certificates, if this is the case use PKCS12-DEF, and the certificates produced by the key store will be made using the default provider.

There is an example program that produces PKCS12 files suitable for loading into browsers. It is in the package org.bouncycastle.jce.examples.

5.5 Additional support classes for Elliptic Curve.

There are no classes for supporting EC in the JDK prior to JDK 1.5. If you are using an earlier JDK you can find classes for using EC in the following packages:

  • org.bouncycastle.jce.spec
  • org.bouncycastle.jce.interfaces
  • org.bouncycastle.jce

6.0 BouncyCastle S/MIME

To be able to fully compile and utilise the BouncyCastle S/MIME package (including the test classes) you need the jar files for the following APIs.

6.1 Setting up BouncyCastle S/MIME in JavaMail

The BouncyCastle S/MIME handlers may be set in JavaMail two ways.
  • STATICALLY Add the following entries to the mailcap file:
       application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature
       application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime
       application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature
       application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime
       multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed
       
  • DYNAMICALLY The following code will add the BouncyCastle S/MIME handlers dynamically:
       import javax.activation.MailcapCommandMap;
       import javax.activation.CommandMap;
    
       public static void setDefaultMailcap()
       {
           MailcapCommandMap _mailcap =
               (MailcapCommandMap)CommandMap.getDefaultCommandMap();
    
           _mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
           _mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
           _mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
           _mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
           _mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
    
           CommandMap.setDefaultCommandMap(_mailcap);
       }
       

Sunday, June 13, 2010

Integrating Encap in a Java MIDlet

Mini howto cookbook: Integrating Encap in a Java MIDlet

 

Abstract

This article describes a minimalistic approach of integrating Encap activation and authentication into a Java MIDlet. The Java MIDlet talks to a service provider server application that requires the user to log in using an OTP security token, which in this case is embedded into the Java MIDlet. Using embedded OTP is convenient for the user, secure, and cost efficient. The source code for a helper class is provided. This fits well into a scenario where the MIDlet GUI skeleton is already implemented.

Requirements

     The logo and name of the service provider configuration is assumed to be compiled into the Java MIDlet

     The service provider configuration is push, which in a normally is used to start the application automatically, and to pass information through the Java MIDlet to the authentication server. This makes it possible to use existing infrastructure for e.g. logging into an internet bank or similar.

     Java MIDP 2 development environment

Dependencies

The EncapHelper class has the following dependencies that must be available on the classpath in order to compile successfully:

Name

Description

Source

msec-server-common-1.3.3.jar

Common constants used in Encap client and server, Java 1.1

Encap as, www.encap.no

msec-api-core-1.3.3.jar

Encap embedded client API, Java 1.1

Encap as, www.encap.no

msec-api-midp-1.3.3.jar

Encap embedded client API for Java MIDP-2, using kSOAP and IAIK crypto.

Encap as, www.encap.no

ksoap2-j2me-core-2.1.0.jar

kSOAP for Java Microedition.

http://sourceforge.net/projects/ksoap2

 

jce-full-me-20080505.jar (iaik_jce_full_me.jar)

IAIK JCE ME - Crypto library (Basic, non-US version)

http://jce.iaik.tugraz.at/sic/Products/Core-Crypto-Toolkits/JCE-ME

Furthermore the Encap helper requires the URL to the Encap activation/authentication server, and the listening SMS port. Contact Encap as for more information.

 

 

Scenarios

The following is a sample scenario that can be used for development and proof of concept.

     Download/installation: The user downloads and installs the MIDlet application with embedded Encap mSec libraries from some known URL that the developer has published.

     Activation: The user enters the Encap wizard for download/installation/activation from the service provider's web pages, skips the download/installation step in the wizard, starts the Java MIDlet with embedded Encap,  selects Activation in the MIDlet, enters the activation code from the web page, and chooses PIN in the MIDlet.

     Login: The user starts the Java MIDlet with embedded Encap, selects "Login", enters user ID and password, enters Encap PIN, the MIDlet authenticates towards Encap server, receives OTP that it forwards to the service provider, and the service provider grants access to the protected page.

 

Classes and methods

The following classes include a minimalistic approach, i.e. they do not include processing of all events from the Encap mSec API, but just enough to make it work.

     EncapHelper – glue code called by the MIDlet that interfaces the the Encap mSec API.

     EncapHelperListener – the methods that the MIDlet must implement in order to receive events from  the EncapHelper.

The mSec API will create new Thread when required to do network I/O, and pass thre result through the handle(Callback[] callbacks) method, in a similar style as for server side JAAS. The following describes the flow for the success scenarios.

Initialization

  1. The MIDlet calls the constructor of the EncapHelper with the listener to be notified by EncapHelper – in the following, we assume that the MIDlet implements the listener.

Activation

  1. The MIDlet calls the waitForStartMessage() method of EncapHelper that waits for incoming SMS from server.
  2. The MIDlet calls the getInitParams() method of EncapHelper with the received SMS as parameter.
  3. The EncapHelper calls the MIDlet's listener inputActivationCode() method, that should prompt the user for the activation code.
  4. The MIDlet calls the EncapHelper's continueWithActivationId() method with the activation code from the user as argument. This causes the Encap mSec API to contact the server to verify the activation code, and call the EncapHelper's handle() method with a PinCallback to request the user PIN.
  5. The EncapHelper calls the MIDlet's inputChoosePin()  method to request the user to choose and confirm PIN.
  6. The MIDlet calls EncapHelper's activate() method with the user PIN as argument. This causes Encap mSec API to contact the server to complete activation, and call the EncapHelper's handle() method with a ResultCallback.
  7. The EncapHelper calls the MIDlet's activationSuccess() method which indicates that the mSec API has now completed activation of the embedded security token, which can furthermore be used for authentication.

Authentication

  1. The MIDlet calls the waitForStartMessage() method of EncapHelper that waits for incoming SMS from server.
  2. The MIDlet calls the getInitParams() method of EncapHelper with the received SMS as parameter.
  3. The EncapHelper calls the MIDlet's inputPin()  method to request the user to choose and confirm PIN.
  4. The MIDlet calls EncapHelper's authenticate() method with the user PIN as argument. This causes Encap mSec API to contact the server to complete activation, and call the EncapHelper's handle() method with a ResultCallback.
  5. The EncapHelper calls the MIDlet's authenticationSuccess() method with an OTP as argument. The mSec API has now completed authentication with the embedded security token, which can furthermore be used for authentication. The OTP can be sent as authentication token towards the service provider. The OTP is present to provide compatibility with stand alone OTP devices, the user is already authenticated in the mobile channel.

 

Source code

EncapHelperListener.java

/*

* Copyright (C) Arne Riiber 2010

* All rights reserved.

*/

 

package no.riiber.microedition.midlet;

 

/**

*

* @author arne

* @since Jul 7, 2009

* @since Jun 12, 2010 5:53:56 PM

*/

interface EncapHelperListener {

    /**

     * Activation failed with the specified symbolic message

     * @param message The reason why activation failed

     */

    void activationFailed(String message);

 

    /**

     * Activation success with the specified result

     * @param result The result that can be displayed to user (if any)

     */

    void activationSuccess(String result);

 

    /**

     * Authentication failed with the specified symbolic message

     * @param message The reason why activation failed

     */

    void authenticationFailed(String message);

 

    /** Authentication success with result from server

     *

     * @param result (OTP to display or URL)

     */

    void authenticationSuccess(String result);

 

    /**

     * Do input activation code from user

     *

     * @param length Number of characters.

     * @param isNumeric If true, input digits only. If false, any characters.

     */

    void inputActivationCode(int length, boolean isNumeric);

 

    /**

     * Do input PIN from user

     *

     * @param length Number of characters.

     * @param isNumeric If true, input digits only. If false, any characters.

     */

    void inputPin(int length, boolean isNumeric);

 

    /**

     * Do input from user to choose PIN (and confirm PIN)

     *

     * @param length Number of characters.

     * @param isNumeric If true, input digits only. If false, any characters.

     */

    void inputChoosePin(int length, boolean isNumeric);

 

}

EncapHelper.java

/*

* Copyright (C) Arne Riiber 2010

* All rights reserved.

*/

 

package no.riiber.microedition.midlet;

 

import encap.msec.client.api.Activater;

import encap.msec.client.api.Authenticater;

import encap.msec.client.api.MSec;

import encap.msec.client.api.StartParams;

import encap.msec.client.api.callback.ActivationIdCallback;

import encap.msec.client.api.callback.Callback;

import encap.msec.client.api.callback.PinCallback;

import encap.msec.client.api.callback.ResultCallback;

import encap.msec.client.platform.communication.MIDPCommunication;

import encap.msec.client.platform.crypto.MIDPCrypto;

import encap.msec.client.platform.storage.MIDPPersistentStorage;

import encap.msec.client.storage.Config;

import encap.msec.client.storage.IntegrityViolatedException;

import encap.msec.common.CommonConstants;

import javax.microedition.io.Connector;

import javax.wireless.messaging.BinaryMessage;

import javax.wireless.messaging.Message;

import javax.wireless.messaging.MessageConnection;

 

/**

* EncapHelper - The necessary glue to call Encap server for authentication

*

* @author arne

* @since Jul 3, 2009

*/

class EncapHelper implements encap.msec.client.api.callback.CallbackHandler {

 

    private String smsPort = "16999"; // Contact Encap as for advice

    private String APPLICATION_ID = "bankId";

    private String url = "http://localhost:8080/mSecFront"; // Contact Encap as for advice

    private Authenticater authenticater;

    private Activater activater;

    private EncapHelperListener encapHelperListener;

    /** holds pin len + format for retry pin */

    private Config config;

 

 

    public EncapHelper(

            EncapHelperListener encapHelperListener) throws IntegrityViolatedException {

 

        //#debug

        System.out.println(this.getClass());

 

        this.encapHelperListener = encapHelperListener;

 

        MIDPCommunication communication = new MIDPCommunication();

        //communication.setClientVersion(clientVersion);

        MIDPPersistentStorage persistentStorage = new MIDPPersistentStorage();

        MIDPCrypto crypto = new MIDPCrypto();

 

        this.authenticater = MSec.getAuthenticater(this, communication, persistentStorage, crypto);

        this.activater = MSec.getActivater(this, communication, persistentStorage, crypto);

    }

 

 

    /**

     * Call Encap server to get challenge

     *

     * @param command - Incoming message from server

     */

    public void getInitParams(String command) {

        //#debug

        System.out.println("getInitParams(" + command+ ")");

        StartParams startParams = extractParams(command);

            //new StartParams(command);

        startParams.setAppId(APPLICATION_ID);

        startParams.setUrl(url);

 

        String functionCmd = startParams.getCommand();

 

        if (functionCmd.equals(CommonConstants.AUTH_CMD)) {

 

            startParams.setSecurityObject(startParams.getSessionId());

            String serviceProviderId = startParams.getServiceProviderId();

            //#debug

            System.out.println("Calling MSec API: authenticater.getInitParams(" + startParams + ")");

 

            authenticater.getInitParams(startParams); // non-blocking

            // Result passed in handle(callback)

        } else if (functionCmd.equals(CommonConstants.ACTIVATE_CMD)) {

            startParams.setSecurityObject(startParams.getSessionId());

            String serviceProviderId = startParams.getServiceProviderId();

 

            //#debug

            System.out.println("Calling MSec API: activater.getInitParams(" + startParams + ")");

 

            activater.getInitParams(startParams); // non-blocking

            // Result passed in handle(callback)

        } else {

            // ignore

            //#debug

            System.out.println("Ignoring command: " + command);

        }

    }

 

    /**

     * Handle response from MSec API

     *

     * @param callbacks

     * @throws java.lang.Exception

     */

    public void handle(Callback[] callbacks) throws Exception {

        //#debug

        System.out.println("handle(" + callbacks[0] + ")");

 

        if (callbacks[0] instanceof ActivationIdCallback) {

            ActivationIdCallback callback = (ActivationIdCallback)callbacks[0];

            this.config = callback.getConfig();

            encapHelperListener.inputActivationCode(

                    config.getActivationCodeLength(),

                    CommonConstants.NUMERIC.equals(config.getActivationCodeFormat())

            );

        } else if (callbacks[0] instanceof PinCallback) {

 

            PinCallback callback = (PinCallback) callbacks[0];

            this.config = callback.getConfig();

            if (callback.getCommand().equals(CommonConstants.ACTIVATE_CMD)) {

                encapHelperListener.inputChoosePin(

                        config.getPinLength(),

                        CommonConstants.NUMERIC.equals(config.getPinFormat())

                );

            } else {

                encapHelperListener.inputPin(

                        config.getPinLength(),

                        CommonConstants.NUMERIC.equals(config.getPinFormat())

                );

            }

        } else if (callbacks[0] instanceof ResultCallback) {

            ResultCallback resultCallback = (ResultCallback) callbacks[0];

            if (resultCallback.getCommand().equals(CommonConstants.AUTH_CMD)) {

                if (resultCallback.getServerResponse().getStatus() == CommonConstants.SUCCESS) {

                    String securityCode = new String(resultCallback.getServerResponse().getSecureObject());

                    encapHelperListener.authenticationSuccess(securityCode);

                } else if (resultCallback.getServerResponse().getStatus() == CommonConstants.FAIL_RETRY) {

                    //  no callback.getConfig() available

                    //encapHelperListener.authenticationRetryInputPin(...)

                    encapHelperListener.inputPin(

                            config.getPinLength(),

                            CommonConstants.NUMERIC.equals(config.getPinFormat())

                    );

 

                } else {

                    // error

                    encapHelperListener.authenticationFailed(resultCallback.getServerResponse().getAdditionalInfo());

                }

            } else if (resultCallback.getCommand().equals(CommonConstants.ACTIVATE_CMD)) {

                if (resultCallback.getServerResponse().getStatus() == CommonConstants.SUCCESS) {

                    encapHelperListener.activationSuccess(new String(resultCallback.getServerResponse().getSecureObject()));

                } else {

                    // error

                    encapHelperListener.activationFailed(resultCallback.getServerResponse().getAdditionalInfo());

                }

            } else {

                //#debug

                System.out.println("Ignoring ResultCallback: " + callbacks[0]);

            }

        } else {

            //#debug

            System.out.println("Ignoring callback: " + callbacks[0]);

        }

    }

 

    /**

     * Continue activation with the specified activation code (activation ID).

     *

     * @param activationId Activation Code from user

     */

    public void continueWithActivationId(String activationId) {

        //#debug

        System.out.println("continueWithActivationId(" + activationId + ")");

        activater.continueWithActivationId(activationId);

    }

 

    /**

     * Call this method from GUI to activate with user PIN

     * @param pin

     */

    void activate(byte[] pin) {

        //#debug

        System.out.println("activate(pin.length=" + new String(pin).length() + ")");

        activater.activate(pin);

    }

 

    /**

     * Call this method from GUI to authenticate with user PIN

     * @param pin

     */

    public void authenticate(byte[] pin) {

        //#debug

        System.out.println("authenticate(pin.length=" + new String(pin).length() + ")");

        authenticater.authenticate(pin);

    }

 

    /**

     * Wait for incoming message (SMS) from server

     *

     * @return Message from server

     * @throws java.lang.Exception

     */

    public String waitForStartMessage() throws Exception {

        MessageConnection messageConnection = null;

        try {

            String addr = "sms://:" + smsPort;

            //#debug

            System.out.println("waitForStartMessage: Listening on "+ addr);

            messageConnection = (MessageConnection) Connector.open(addr);

 

            // block until message ready or connection closed

            Message message = messageConnection.receive();

 

            byte[] data = ((BinaryMessage) message).getPayloadData();

            String startMessage = new String(data);

            //#debug

            System.out.println("waitForStartMessage: BinaryMessage received: " + startMessage);

            return startMessage;

        } catch (Exception e) {

            System.err.println(e);

            throw e;

        } finally {

            if (messageConnection != null) {

                try {

                    messageConnection.close();

                } catch (Exception e) {

                }

            }

        }

    }

 

    //

 

    /**

     * An utility to extract parameters from an URL style encoded string.

     * <p/>

     * The parameters are encoded on format name1=value1&name2=value2 as is.

     * The parameter name and value can not contain '=' or '&'.

     */

    private static StartParams extractParams(String str) {

        String pval; // parameter value

        String pname; // parameter name

        boolean finished = false;

 

        StartParams start = new StartParams();

        while (!finished) {

            pname = str.substring(0, str.indexOf('='));

            if (str.indexOf('&') != -1) {

                // more parameters follow (a=1&b=2&...)

                pval = str.substring(str.indexOf('=') + 1, str.indexOf('&'));

                str = str.substring(str.indexOf('&') + 1);

            } else {

                // no more parameters (a=1&b=2)

                pval = str.substring(str.indexOf('=') + 1);

                finished = true;

            }

            if(pname.equals(CommonConstants.PARAM_CMD)){

                          start.setCommand(pval);

            } else if(pname.equals(CommonConstants.PARAM_SESSION_ID)){

                          start.setSessionId(pval);

            } else if(pname.equals(CommonConstants.PARAM_SPCODE)){

                          start.setServiceProviderId(pval);

            } else if(pname.equals(CommonConstants.ACTIVATION_CODE_FORMAT)){

                          start.setActivationCodeFormat(pval);

            } else if(pname.equals(CommonConstants.ACTIVATION_CODE_LENGTH)){

                          start.setActivationCodeLength(pval);

            } else if(pname.equals(CommonConstants.PARAM_ACTIVATIONCODE)){

                          start.setActivationCode(pval);

            } else if(pname.equals(CommonConstants.PARAM_ACTIVATIONCODE)){

                          start.setActivationCode(pval);

            }

        }

        return start;

    }

 

 

 

}

 

 

2010-06-13 Arne Riiber

 


Wednesday, June 9, 2010

Automated testing for Java phones: http://webcast-west.sun.com/interactive/10A12537/index.html The framework makes it easy to create Java phone client and Java server skeleton that will run tests, either automated with no user interaction, or interactive. Typically client code will connect to a server and do some stuff, then do something with the result - and this can be verified. Logging for Java phones:
  1. microlog - http://blogs.sun.com/mobility_techtips/entry/powerful_logging_in_java_me
  2. your own log implementation - http://blogs.sun.com/mobility_techtips/entry/simple_strategy_for_logging_and
  3. another option (used by us so far) is http://www.j2mepolish.org/cms/leftsection/documentation/building/preprocessing/directives.html#preprocessing-debug
A funny thing about iPhone v.3: For Basic HTTP authentication over a secure connection (HTTPS), Safari on iPhone displays: Secure Connection. Username: ... Password: ... (It misses to display the realm name - usually the name of the service you are authenticating to)

Tuesday, June 8, 2010

Windows phone 7

Windows phone 7

By following Windows Phone 7 link on digi.no - results:

+ Distribution through Windows Phone Marketplace, free download or pay (with revenue sharing 70/30)
o Distribution of enterprise applications through Windows Phone Marketplace? not decided by Microsoft yet.
+ App can store data isolated from other apps ("Isolated storage")
+ App can send/receive Windows Phone Push Notification (looks similar to Apple's Push Notification)
+ AES/SHA-1 supported
+ Web Service supported
-  App can not send/receive SMS (but can pre-fill SMS Compose Task dialog for sending SMS)
-  App can not retrieve Unique Device ID but rumours say some kind of phone serial number ID