简体   繁体   中英

Hardcode string on a javacard

I need to save a variable on a JavaCard. Javacard's don't support Strings, so I have to hardcode some String variables as byte arrays. Unfortunately, I don't know how to achieve this format:

new byte[]{0x4A, 0x61, 0x6E, 0x20, 0x56, 0x6F, 0x73, 0x73, 0x61, 0x65, 0x72, 0x74};

Is there an online tool available? Or is there a program that output's it that way so I can copy paste the output and use that for hardcoding?

You don't need any tool for that. If you want to store an string in your applet in the applet developing step (I mean in the programming phase) use a byte array as below :

public static byte[] myFiled = {(byte)'T', (byte)'E', (byte)'S', (byte)'T'};

or use Hex values instead of the letters:

public static byte[] myFiled = {(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13};

It's necessary to cast the array elements to byte explicitly

And if you want to store the string after developing in installing your applet, first convert it to its hex value using this online tool for example , and then send it to card in the data field of an APDU command. And then using arrayCopy or arrayCopyNonAtomic methods store it in you byte array.

Just use String::getBytes() :

String a = "HelloWorld";
byte[] inBytes = a.getBytes();
System.out.println(Arrays.toString(inBytes));

OUTPUT:

[72, 101, 108, 108, 111, 87, 111, 114, 108, 100]

IDEONE DEMO


ADD ON: as @AndyTurner mentioned, you can specify charset using String::getBytes(Charset) . Find here a nice explanation.

Here's a method to convert a string to an array literal that represents US-ASCII–encoded bytes.

static String format(String str)
{
  byte[] encoded = str.getBytes(StandardCharsets.US_ASCII);
  return IntStream.range(0, encoded.length)
    .mapToObj(idx -> String.format("0x%02X", encoded[idx]))
    .collect(Collectors.joining(", ", "{ ", " }"));
}

Because it uses ASCII, the high bit of each byte is zero, and no downcasts to byte are required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM