解释Java卡HelloWorld小程序

Jea*_*ean 1 java javacard

下面,您会看到一个java卡程序,它在收到APDU Command = 8000000000(其来源)时返回"Hello Word"

package helloWorldPackage;

import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.Util;

public class HelloWorldApplet extends Applet 
{
    private static final byte[] helloWorld = {(byte)'H',(byte)'e',(byte)'l',(byte)'l',(byte)'o',(byte)' ',(byte)'W',(byte)'o',(byte)'r',(byte)'l',(byte)'d',};
    private static final byte HW_CLA = (byte)0x80;
    private static final byte HW_INS = (byte)0x00;

    public static void install(byte[] bArray, short bOffset, byte bLength) 
        {
        new HelloWorldApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
        }

    public void process(APDU apdu) 
        {
        if (selectingApplet()) 
            {
            return;
            }

        byte[] buffer = apdu.getBuffer();
        byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);
        byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF);

        if (CLA != HW_CLA)
            {
            ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
            }

        switch ( INS ) 
            {
            case HW_INS:
                getHelloWorld( apdu );
                break;
            default:
                ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
            }
        }

    private void getHelloWorld( APDU apdu)
        {
        byte[] buffer = apdu.getBuffer();
        short length = (short) helloWorld.length;
        Util.arrayCopyNonAtomic(helloWorld, (short)0, buffer, (short)0, (short) length);
        apdu.setOutgoingAndSend((short)0, length);
        }
}
Run Code Online (Sandbox Code Playgroud)

我明白了,但我无法理解程序员在行中使用的原因&0XFF:

        byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);
        byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF);
Run Code Online (Sandbox Code Playgroud)

为什么他通常不使用以下线?

        byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA]);
        byte INS = (byte) (buffer[ISO7816.OFFSET_INS]);
Run Code Online (Sandbox Code Playgroud)

而且在线:

ew HelloWorldApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
Run Code Online (Sandbox Code Playgroud)

他的意思是+1什么?

Maa*_*wes 5

虽然我们看不到作者的意图,但行:

    byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);
Run Code Online (Sandbox Code Playgroud)

是100%相当于:

    byte CLA = buffer[ISO7816.OFFSET_CLA];
Run Code Online (Sandbox Code Playgroud)

Java经常使用整数作为操作的结果,并且因为Java Card通常不支持int值,所以经常需要转换为byteshort.我只能猜测& 0xFF和演员是否存在是因为过度热衷于摆脱中间int价值.让Java支持无符号字节也可能是一次糟糕的尝试.


register方法需要实例AID.该AID在全局平台期间给出的用户参数范围内INSTALL for INSTALL,但前面是一个包含AID长度的字节(包括5到15之间).所以+ 1是跳过那个长度字节 - 它又出现在方法的最后一个参数register:bArray[bOffset].