Search code examples
encryptionjavacarddes

Error in doFinal on multiple DES_CBC_NOPAD encryption


I had a problem with DES encryption on Java Card: I encrypt the data before sending it and then send it as a response to requests coming from some library.

If in one applet SELECT sends requests for information, then through 28-30 encryptions on the card the session falls with the error 6F00. After that, all encryption calls return 6F00. The problem disappears if you do a second selection of the applet.

All data before encryption, I make a multiple of 8, so the error due to the length of the message I eliminated immediately. There may be a memory problem, but I call JCSystem.requestObjectDeletion(); after each sending of data.

Below is the initialization and encryption function implemented in my Applet.

public static void Init()
    rw_des_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    rw_cipherDes = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    rw_des_key.setKey(rwdeskey, (short) 0);
}

public static short RWEncrypt(byte[] msg, short pos, short len, byte[] encMsg, short encPos) throws ArithmeticException, ArrayIndexOutOfBoundsException, ArrayStoreException, ClassCastException, IndexOutOfBoundsException, NegativeArraySizeException, NullPointerException, RuntimeException, SecurityException {
        rw_cipherDes.init(rw_des_key, Cipher.MODE_ENCRYPT);
        return rw_cipherDes.doFinal(msg, (short) pos, len, encMsg, (short) encPos);}

If someone can tell what might be the case, then I will be very grateful!


Solution

  • This problem occurs when external access (externalAccess) flag is false in the object but the corresponding object is called by a shareable interface.

    For example (from your code): -

    rw_cipherDes = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);

    Here the external access flag is False i.e. you are instructing the Cipher API not to provide the access of cipher object to any external application (which is for the case of calling this API by shareable interface).

    So, the following line will generate a security exception (hence SW 6F00) when called from across applications by shareable interface.

    return rw_cipherDes.doFinal(msg, (short) pos, len, encMsg, (short) encPos);}

    Obviously,when you call the same API from its own application, then it will work fine.

    Solution is allowing externalAccess (true) for the object. This would make it accessible via shareable interface.

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