zargham-ahmad / JavaCard-SS

MIT License
1 stars 5 forks source link

Store key-value pairs in card's memory #2

Open GajdosDavid opened 2 years ago

GajdosDavid commented 2 years ago

Since there's only byte[] and short[] array data types supported in JavaCard, we have quite limited options. Let's use byte[] arrays for storing the key-value bytes.

In all options below I'll assume example: foo (key) - barr (value) I have few ideas on how to do it: 1) Store it all in one array byte[] key_values = [0x03,'f','o','o',0x04,'b','a','r','r'] The key values will be stored in one array together with their length. This way you will know a number of bytes to skip to get to another key-value pair, or to get from key to pair. The length of each record will be len(key)+len(value)+2. However this puts a limitation on number of possible chars for key/value to 255 (2^8 - 1). Also retrieving number of records would be quite impractical as you'd have jump in the array. 2) Split keys and values into seperate arrays Practically like the above, however the values would be seperated into different arrays. From the example above byte[] keys = [0x03,'f','o','o'] byte[] values = [0x04,'b','a','r','r'] This probably only improves retrieving the number of keys as you'd only have to go through keys array. Still limited to 255 chars only 3) Use separate array for size of keys and values byte[] key_values = ['f','o','o','b','a','r','r'] short[] sizes = [3, 4] This allows for keys and values to have 2^16-1 chars (I don't assume to have that much memory to allow user to store ~64kB key-value records, but it adds more freedom). 4) Use 3 arrays byte[] key_values = ['f','o','o','b','a','r','r'] short[] key_sizes = [3] short[] value_sizes = [4] This way len(key_sizes) tells you the count of keys 5) Use 4 arrays byte[] keys = ['f','o','o'] byte[] values = ['b','a','r','r'] short[] key_sizes = [3] short[] value_sizes = [4]

My favourite option is number 4, because when there's not enough space to store another key-value pair, you only have to take care of reallocation of 1 array. If key_sizes/value_sizes array length is exhausted you'll have to reallocate 2 arrays, but this is probably fine as they'll always have the same size, however in case of separate arrays for keys and values they'll most likeley have different sizes so you'll have to check both of their sizes before adding to them. However either of 4 || 5 options is fine for me.

GajdosDavid commented 2 years ago

Question: Do we want to encrypt the key-value pairs stored on the card? Pros: Possibly if attacker can retrieve memory, they would be able to also get the key and decrypt all encrypted stuff. However it'd probably be harder to find the key used to encrypt pairs as the encrypted text would sort of look random in the memory. Cons: If we'll be decryping key-value pairs we'll have to sacrifice some bytes because the data will have to be block aligned.