What is meaning of the response status word 0x61xx from a smart card? - protocols

I wrote a Java Card applet that saves some data into the APDU buffer at offset ISO7816.OFFSET_CDATA and sends those bytes as a response.
Util.arrayCopy(Input_Data, (short)0, buffer, (short) ISO7816.OFFSET_CDATA, (short)Datalength);
apdu.setOutgoing();
apdu.setOutgoingLength((short)(DataLength) );
apdu.sendBytesLong(buffer, ISO7816.OFFSET_CDATA, (short)(DataLength));
I tested this in a simulator without any problem. But when I test this on a real smart card (Java Card v2.2.1 manufactured by Gemalto), I get the status word 0x6180 as response.
My command APDU is 00 40 00 00 80 Data, where data has a length of 128 bytes, so I have 4+128 bytes in the buffer and (260-(4+128)) byte is null.

Your simulator probably uses T=1 transport protocol, but your real card does not. It uses T=0 protocol, which means it can either receive data, or send data in a single APDU.
Status word 0x6180 indicates there are 0x80 bytes to receive from the card. Generally, 61XX means XX bytes to receive.
How to receive them? Well, there is a special APDU command called GET RESPONSE. You should call it each time you get 61XX status word. Use XX as the Le byte of your GET RESPONSE APDU
APDU -> 61 XX
00 C0 00 00 XX -> your data 90 00
A few other notes on your code:
Datalength vs DataLength?
Copy your output data to 0 instead of ISO7816.OFFSET_CDATA
Why do you cast DataLength to short each time? Is it short? Do not cast then. Is it byte? You cast it in a wrong way then, because unsigned byte value > 0x80 will be cast to a negative short. The correct cast from an unsigned byte to a short is (short) (DataLength & 0xFF)
Use setOutgoingAndSend whenever you can. It is much simpler.
Use arrayCopyNonAtomic instead of arrayCopy whenever you are not copying to a persistent array. Performance of arrayCopyNonAtomic is much better.

Related

Read JPEG magic number with FileChannel and ByteBuffer

I started digging into Java NIO API and as a first try I wanted to read a JPEG file magic number.
Here's the code
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.io.FileInputStream;
public class JpegMagicNumber {
public static void main(String[] args) throws Exception {
FileChannel file = new FileInputStream(args[0]).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(6);
file.read(buffer);
buffer.flip();
System.out.println(Charset.defaultCharset().decode(buffer).toString());
file.close();
buffer.clear();
}
}
I expect to get the magic number chars back but all I get is garbage data into the terminal.
Am I doing something wrong ?
Short answer: There is nothing particularly defective with the code. JPEG just has 'garbage' up front.
Long answer: JPEG internally is made up of segments, one after the other. These segments start with a 0xFF byte, followed by an identifier byte, and then an optional payload/content.
Example start:
FF D8 FF E0 00 10 4A 46 49 46 00 01 01 00 00 01 00 01 00 00 FF E1
The image starts with the Start Of Image (SOI) segment, 0xFF 0xD8, which has no payload.
The next segment is 'application specific', 0xFF 0xE0. Two bytes follow with the length of the payload (these two bytes included!).
0x4A 0x46 0x49 0x46 : JFIF ← perhaps what you were looking for?
JPEG doesn't have a magic number in the sense you were perhaps looking for, like 'PK' for zip or '‰PNG' for PNG. (The closest thing is 0xFF 0xD8 0xFF for the SOI and the first byte of the next segment.)
So your code does correctly read the first six bytes of the file, decodes them into characters per your native platform, and prints them out, but a JPEG header just looks that way.

Trouble displaying signed unsigned bytes with python

I have a weird problem! I made a client / server Python code with Bluetooth in series, to send and receive byte frames (for example: [0x73, 0x87, 0x02 ....] )
Everything works, the send reception works very well !
The problem is the display of my frames, I noticed that the bytes from 0 to 127 are displayed, but from 128, it displays the byte but it adds a C2 (194) behind, for example: [0x73, 0x7F, 0x87, 0x02, 0x80 ....] == [115, 127, 135, 2, 128 ....] in hex display I would have 73 7F C2 87 2 C2 80 .. , we will notice that he adds a byte C2 from nowhere!
I think that since it is from 128! that it is due to a problem of signed (-128 to 127) / unsigned (0 to 255).
Anyone have any indication of this problem?
Thank you
0xc2 and 0xc3 are byte values that appear when encoding character values between U+0080 and U+00FF as UTF-8. Something on the transmission side is trying to send text instead of bytes, and something in the middle is (properly) converting the text to UTF-8 bytes before sending. The fix is to send bytes instead of text in the first place.

Unknown Error (6c 15) with Setoutgoinglength in java card 2.2.1

I wrote a code that for java card 2.2.1 and I test it eith JCIDE.
I get error in method Setoutgoinglength()
public void getoutput(APDU apdu)
{
byte [] buffer = apdu.getBuffer();
byte hello[] = {'H','E','L','L','O',' ','W','O','R','L','D',' ', 'J','A','V','A',' ','C','A','R','D'};
short le = apdu.setOutgoing();
short totalBytes = (short) hello.length;
Util.arrayCopyNonAtomic(hello, (short)0, buffer, (short)0, (short)totalBytes);
apdu.setOutgoingLength(totalBytes);
apdu.sendBytes((short) 0, (short) hello.length);}
6CXX means that your Le is not equal to the correct length of response data (XX is equal to the length of correct response data). 6C15 specifically means that the correct Le to be used should be 0x15.
What happened is that your Le field is 0x00 (which is actually interpreted by the card as 256 in decimal form) but you used totalBytes, which has a value of 0x15, as parameter to apdu.setOutgoingLength() which is not equal to 256.
The correct APDU to send is 00 40 00 00 15

Converting hex values in buffer to integer

Background: I'm using node.js to get the volume setting from a device via serial connection. I need to obtain this data as an integer value.
I have the data in a buffer ('buf'), and am using readInt16BE() to convert to an int, as follows:
console.log( buf )
console.log( buf.readInt16BE(0) )
Which gives me the following output as I adjust the external device:
<Buffer 00 7e>
126
<Buffer 00 7f>
127
<Buffer 01 00>
256
<Buffer 01 01>
257
<Buffer 01 02>
258
Problem: All looks well until we reach 127, then we take a jump to 256. Maybe it's something to do with signed and unsigned integers - I don't know!
Unfortunately I have very limited documentation about the external device, I'm having to reverse engineer it! Is it possible it only sends a 7-bit value? Hopefully there is a way around this?
Regarding a solution - I must also be able to convert back from int to this format!
Question: How can I create a sequential range of integers when 7F seems to be the largest value my device sends, which causes a big jump in my integer scale?
Thanks :)
127 is the maximum value of a signed 8-bit integer. If the integer is overflowing into the next byte at 128 it would be safe to assume you are not being sent a 16 bit value, but rather 2 signed 8-bit values, and reading the value as a 16-bit integer would be incorrect.
I would start by using the first byte as a multiplier of 128 and add the second byte, this will give the series you are seeking.
buf = Buffer([0,127]) //<Buffer 00 7f>
buf.readInt8(0) * 128 + buf.readInt8(1)
>127
buf = Buffer([1,0]) //<Buffer 01 00>
buf.readInt8(0) * 128 + buf.readInt8(1)
>128
buf = Buffer([1,1]) //<Buffer 01 01>
buf.readInt8(0) * 128 + buf.readInt8(1)
>129
The way to get back is to divide by 128, round it down to the nearest integer for the first byte, and the second byte contains the remainder.
i = 129
buf = Buffer([Math.floor(i / 128), i % 128])
<Buffer 01 01>
Needed to treat the data as two signed 8-bit values. As per #forrestj the solution is to do:
valueInt = buf.readInt8(0) * 128 + buf.readInt8(1)
We can also convert the int value into the original format by doing the following:
byte1 = Math.floor(valueInt / 128)
byte2 = valueInt % 128

What is the structure of an application protocol data unit (APDU) command and response? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying to learn Java Card. I have just started and have not found many resources. My first question is how to understand APDU commands. (such as those defined in ISO/IEC 7816-4)
For example, if I see a byte pattern such as 10101010 how can I understand the meaning of this, and in particular determine the CLA or INS, for example?
APDU commands are a queue of binary numbers in the following form:
CLA | INS | P1 | P2 | Lc | CData | Le
The first four sections, i.e CLA , INS , P1 and P2 are mandatory in all APDU commands and each one has one byte length. These one-byte-length sections stand for Class, Instruction, Parameter1 and Parameter2 respectively.
The last three sections, i.e Lc , CData and Le are optional.Lc is the encoding of Nc, which is the encoding of the length of the CDATA field. Le is the encoding of Ne, then encoding of the maximum response data that may be send. Based on presence or absence of these sections, we have 4 case for APDU commands, as below:
Case1: CLA | INS | P1 | P2
Case2: CLA | INS | P1 | P2 | Le
Case3: CLA | INS | P1 | P2 | Lc | Data
Case4: CLA | INS | P1 | P2 | Lc | Data | Le
The length of CData is different for different commands and different applets. based on the length of CData (i.e Lc) and the length of maximum response data that may send (i.e Le), we have to type of APDU commands:
Normal/Short APDU commands, when Lc and Le are smaller than 0xFF
Extended length APDU commands, when Lc and/or Le are greater than 0xFF.
So for the length of these sections we have:
Lc : 1 byte for Short APDU commands and 3 byte (they specify this length, because its enough) for Extended APDU commands.
Data : Different lengths.
Le : Same as Lc.
How can I understand APDU commands?
Answer:
When you write an applet, you specify the response of your applet to different APDU commands that it will receive in the future. Card Manager is an applet also. The commands that it support is defined in your card's specifications/datasheet. Normally almost all cards are GlobalPlatform and ISO7816 compliant, so they must support those mandatory APDU commands that is defined in these documents. For example, as 0xA4 is defined as SELECT FILE command in ISO7816-4 standard, If you see an APDU like xx A4 xx xx is sending to Card Manager, you can conclude that it is related with SELECT FILE.
Note that you can choose one value for different functions in your different applets. For example in the following, Applet1 will return 0x6990 in the reception of 00 B0 xx xx APDU commands, while Applet2 will return 0x6991 in the reception of the same command:
Applet1:
public class SOQ extends Applet {
private SOQ() {
}
public static void install(byte bArray[], short bOffset, byte bLength)
throws ISOException {
new SOQ().register();
}
public void process(APDU arg0) throws ISOException {
byte buffer[] = arg0.getBuffer();
if(buffer[ISO7816.OFFSET_CLA] == (byte) 0x00 &&buffer[ISO7816.OFFSET_INS] == (byte) 0xB0){
ISOException.throwIt((short)0x6990);
}
}
}
Output:
OpenSC: opensc-tool.exe -s 00a404000b0102030405060708090000 -s 00B00000 -s 00B00
100
Using reader with a card: ACS CCID USB Reader 0
Sending: 00 A4 04 00 0B 01 02 03 04 05 06 07 08 09 00 00
Received (SW1=0x90, SW2=0x90)
Sending: 00 B0 00 00
Received (SW1=0x69, SW2=0x90)
Sending: 00 B0 01 00
Received (SW1=0x69, SW2=0x90)
Applet2:
public class SOQ extends Applet {
private SOQ() {
}
public static void install(byte bArray[], short bOffset, byte bLength)
throws ISOException {
new SOQ().register();
}
public void process(APDU arg0) throws ISOException {
byte buffer[] = arg0.getBuffer();
if(buffer[ISO7816.OFFSET_CLA] == (byte) 0x00 && buffer[ISO7816.OFFSET_INS] == (byte) 0xB0){
ISOException.throwIt((short)0x6991);
}
}
}
Output:
OpenSC: opensc-tool.exe -s 00a404000b0102030405060708090000 -s 00B00000 -s 00B00
100
Using reader with a card: ACS CCID USB Reader 0
Sending: 00 A4 04 00 0B 01 02 03 04 05 06 07 08 09 00 00
Received (SW1=0x90, SW2=0x00)
Sending: 00 B0 00 00
Received (SW1=0x69, SW2=0x91)
Sending: 00 B0 01 00
Received (SW1=0x69, SW2=0x91)
So the final and short answer to your question (How can I understand APDU commands?) is:
You are dealing with your applet?
You defined the supported commands and their forms, yourself!
You are dealing with another applet (Card Manager, for example)?
You need the source code of that applet or its documentation about its supported commands and their forms or the standard/specification that that applet is compliant with (Global Platform for Card Managers for example).
Note: we have almost the same for APDU responses.
I am afraid such a "complete" e-book simply does not exist. Honestly, I think it is not necessary at all. If you know the basic Java syntax, you will find JavaCard quite easy to learn (although annoying to use). All the usual difficult stuff (threading, GUI, IO, annotations, templates, databases, ...) is just missing in Javacard and the standard libraries are so limited you will be able to learn them in a few days.
There are a few nice tutorials out there:
http://www.oracle.com/technetwork/java/embedded/javacard/overview/index.html
http://javacard.vetilles.com/tutorial/
and a very good SO question:
How to get started with Java Cards?
To answer your question: JavaCard is just a language for writing smartcard applications called applets. It handles all the application logic, but it does not specify the APDU format. That is because JavaCard is not the only smartcard technology. APDU format is specifed in ISO7816 standard, which I really recommend you to read through. It is not free to download, but you can find the most important parts here:
http://www.cardwerk.com/smartcards/smartcard_standard_ISO7816-4_5_basic_organizations.aspx
You would find there, that your APDU command consists of a header:
00A404000E
and a data part:
63616C63756C61746F722E617070.
The header specifies what function should be called:
00 - class byte (CLA, 00 means "inter-industry command sent to logical channel 0")
A4 - instruction byte (INS, A4 means "SELECT applet command")
04 - parameter 1 (P1)
00 - parameter 2 (P2)
0E - length of the data part (Lc)
and the data part contains the identifier of the applet which should be selected for future usage (in your case it is an ASCII encoded string "calculator.app" btw).

Resources