user4272649
user4272649

Reputation:

Fast way to convert byte[] to short[] on Java Card

I want to optimize SHA-3 algorithm on a Java Card. I need a fast algorithm consuming less memory which allows to easy convert byte[] to short[] (or short[] to byte[]). My current implementation looks like this:

private short[] byteToShort(byte[] b,int len)
{
    short len_conv  = (short)(len/2);
    for ( short x = 0; x < len_conv;x++)
    {
        for ( short j = 0 ; j < 2 ; j++)
            aux[j] = b[2*x+j];
        temp_conv[x] = (short)((((short)aux[1]) & 0xFF) | ((((short)(aux[0]) & 0xFF) << 8 )));
    }
    return temp_conv;
}

where len is actual size of the b array and aux and temp_conv are defined as private and allocated as :

short[] temp_conv = JCSystem.makeTransientShortArray((short)255,JCSystem.CLEAR_ON_DESELECT); // used during conversion
byte[] aux = new byte[2];

I currently use Java Card v 2.2.2

Upvotes: 4

Views: 1262

Answers (1)

vojta
vojta

Reputation: 5661

Do not reinvent the wheel: there are useful built-in static methods in the Java Card API, often implemented as native functions for performance reasons. Your code cannot be better than them.

1) First of all, javacardx.framework.util.ArrayLogic.arrayCopyRepackNonAtomic is what you need when working with a RAM array:

ArrayLogic.arrayCopyRepackNonAtomic(b, (short) 0, len, temp_conv, (short) 0);

There is also arrayCopyRepack, which is useful for persistent arrays (the whole operation is done in a single transaction, but it is a little slower).


2) If you cannot use ArrayLogic, there is always javacard.framework.Util.getShort, which you can use instead of the bitwise magic:

private static final void byteToShort(final byte[] bytes, final short blen, final short[] shorts)
{
    short x = 0;
    short y = 0;
    for (; y < blen; x++, y += 2)
    {
        shorts[x] = Util.getShort(bytes, y);
    }
}

Note there is also setShort, which might be useful for short[] to byte[] conversion.


3) Some other notes on your code in case you really want to implement it on your own:

  • Your aux is stored in the persistent memory. This is awfully slow and it will probably damage your card, because aux is rewritten very often, see Symptoms of EEPROM damage.
  • b[2*x+j] is not effective, because of slow multiplication. You should use two loop variables instead and addition only.
  • Get rid of aux and the inner loop, you don't need them at all
  • What about int len? There is no int in Java Card 2.2.2...

Upvotes: 6

Related Questions