www.pudn.com > HandsOnMessageDigest.rar > MessageDigestApplet.java, change:2011-05-05,size:1725b


package com.nxp.id.jcop.training.messagedigest; 
 
import javacard.framework.APDU; 
import javacard.framework.ISO7816; 
import javacard.framework.Applet; 
import javacard.framework.ISOException; 
import javacard.security.MessageDigest; 
 
public class MessageDigestApplet extends Applet { 
	private static final byte INS_INITIALIZE = (byte)0x22; 
	private static final byte INS_TEST_SHA1 = (byte)0x33; 
	private static final byte INS_TEST_SHA256 = (byte)0x33; 
	 
	MessageDigest sha1; 
	MessageDigest sha256; 
	 
	public MessageDigestApplet(){ 
		sha1 = MessageDigest.getInstance(MessageDigest.ALG_SHA, false); 
	} 
	 
	public static void install(byte[] bArray, short bOffset, byte bLength) { 
		// GP-compliant JavaCard applet registration 
		new com.nxp.id.jcop.training.messagedigest.MessageDigestApplet() 
				.register(bArray, (short) (bOffset + 1), bArray[bOffset]); 
	} 
 
	public void process(APDU apdu) { 
		// Good practice: Return 9000 on SELECT 
		if (selectingApplet()) { 
			return; 
		} 
 
		byte[] buf = apdu.getBuffer(); 
		switch (buf[ISO7816.OFFSET_INS]) { 
		case (byte) INS_INITIALIZE: 
				sha1.reset(); 
			break; 
		case INS_TEST_SHA1: 
				short lc = apdu.setIncomingAndReceive(); 
				short resultLength = sha1.doFinal(buf, ISO7816.OFFSET_CDATA, lc, buf, (short) (ISO7816.OFFSET_CDATA + lc)); 
				apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, (short) (resultLength + lc)); 
			break; 
		default: 
			// good practice: If you don't know the INStruction, say so: 
			ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 
		} 
	} 
} 
 
/** 
 * TASK FOR YOU: 
 *  
 * 1. Write a test script 
 * 2. Implement SHA256 and extend test script 
 * 3. How would you verify a message digest from the reader? 
*/