-3

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?

yoano
  • 1,466
  • 2
  • 16
  • 20
  • 1
    The example [in the wikipedia article](https://en.wikipedia.org/wiki/Java_Card#Hello_World_Program) encodes strings as char literals: `{'H','E','L','L','O'}'` - that's much easier to read. – Andy Turner Apr 07 '16 at 08:31

3 Answers3

2

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.

Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113
1

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.

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • it needs this format: new byte[]{0x4A, 0x61, 0x6E, 0x20, 0x56, 0x6F, 0x73, 0x73, 0x61, 0x65, 0x72, 0x74}; – yoano Apr 07 '16 at 08:27
  • Minor nit: you may also want to specify the `Charset` that you want the byte array to be written in, e.g. `a.getBytes(StandardCharsets.UTF_8)`. – Andy Turner Apr 07 '16 at 08:39
0

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.

erickson
  • 265,237
  • 58
  • 395
  • 493