LEQADA
LEQADA

Reputation: 1982

How to use Java Card crypto sample?

I'm trying to make run example from IBM website. I wrote this method:

public static byte[] cipher(byte[] inputData) {
    Cipher cipher
        = Cipher.getInstance(
                Cipher.ALG_DES_CBC_NOPAD, true);

    DESKey desKey = (DESKey) KeyBuilder.buildKey(
                             KeyBuilder.TYPE_DES,
                             KeyBuilder.LENGTH_DES,
                             false);

    byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};
    desKey.setKey(keyBytes, (short) 0);

    cipher.init(desKey, Cipher.MODE_ENCRYPT);
    byte[] outputData = new byte[8];

    cipher.doFinal(inputData, (short) 0, (short) inputData.length, outputData, (short) 0);
    return outputData;
}

And call this method cipher("test".getBytes());. When I call this servlet server gives me Internal server error and javacard.security.CryptoException.

I tried ALG_DES_CBC_ISO9797_M1, ALG_DES_CBC_ISO9797_M2 (and others) and got the same exception.

How to make run simple example of cipher on Java Card Connected?

UPDATE

As @vojta said, key must be 8 bytes long. So it must be something like this:

byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};

I don't know why, but it works only if replace

Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, true);

with

Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M2, false);

I could not find anything about it in documentation.

Upvotes: 2

Views: 586

Answers (2)

vlp
vlp

Reputation: 8116

In addition to @vojta's answer, the input data should be block aligned.

Your input data "test".getBytes() have length 4 which is not valid for Cipher.ALG_DES_CBC_NOPAD (but valid for Cipher.ALG_DES_CBC_ISO9797_M2).

Strange is that this should cause CryptoException.ILLEGAL_USE reason (which is 5 opposed to 3 you are getting)...

Upvotes: 1

vojta
vojta

Reputation: 5661

These lines seem to be wrong:

byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};
desKey.setKey(keyBytes, (short) 0);

DES key should be longer than 4 bytes, right? Standard DES key is 8 bytes long (with strength of 56 bits).

Upvotes: 2

Related Questions