patternjavaMinor
Selecting an algorithm and key for Java Card encryption
Viewed 0 times
encryptioncardjavaalgorithmforselectingandkey
Problem
I was playing around with Java Card and I try to do one of the examples.
P1 is what it has to do (e.g. decrypt, encrypt, etc) and P2 is to select which key to use in P1. Here is what the code looks like - well, half of it anyway, since I'm not really used to formatting in this site and it takes awhile to copy the code and make it pretty.
So my question here is, how can I simplify this nested switch? Or maybe I don't need to use nested switch at all?
P1 is what it has to do (e.g. decrypt, encrypt, etc) and P2 is to select which key to use in P1. Here is what the code looks like - well, half of it anyway, since I'm not really used to formatting in this site and it takes awhile to copy the code and make it pretty.
So my question here is, how can I simplify this nested switch? Or maybe I don't need to use nested switch at all?
switch (buf[ISO7816.OFFSET_P1]){
case (byte) 0x01:
switch (buf[ISO7816.OFFSET_P2]){
case (byte) 0x01:
doSingleDES(apdu, DESKey1);
return;
case (byte) 0x02:
doSingleDES(apdu, DESKey2);
return;
case (byte) 0x03:
doSingleDES(apdu, DESKey3);
return;
case (byte) 0x04:
doSingleDES(apdu, DESKey3);
return;
default:
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
}return;
case (byte) 0x02:
switch (buf[ISO7816.OFFSET_P2]){
case (byte) 0x01:
doEncrypt(apdu, DESKey1);
return;
case (byte) 0x02:
doEncrypt(apdu, DESKey2);
return;
case (byte) 0x03:
doEncrypt(apdu, DESKey3);
return;
case (byte) 0x04:
doEncrypt(apdu, DESKey4);
return;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}return;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);Solution
I would focus on eliminating the inner
switch statements. You could try to eliminate the outer switch as well, but it's probably not worthwhile, especially for a resource-constrained environment.byte[][] desKeys = new byte[][] {
null, DESKey1, DESKey2, DESKey3, DESKey4
};
try {
switch (buf[ISO7816.OFFSET_P1]) {
case 0x01:
doSingleDES(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
return;
case 0x02:
doEncrypt(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
return;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
} catch (ArrayIndexOutOfBoundsException badP2) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}Code Snippets
byte[][] desKeys = new byte[][] {
null, DESKey1, DESKey2, DESKey3, DESKey4
};
try {
switch (buf[ISO7816.OFFSET_P1]) {
case 0x01:
doSingleDES(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
return;
case 0x02:
doEncrypt(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
return;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
} catch (ArrayIndexOutOfBoundsException badP2) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}Context
StackExchange Code Review Q#38149, answer score: 6
Revisions (0)
No revisions yet.