Javacard des algorithm API usage Example

Source: Internet
Author: User
Tags function prototype html form loop case switch loop

Many times we do not need to implement a more complex algorithm, but only need to know how to invoke the existing implementation. API calls, in the form of include+ functions, Java is actually nothing more than import+ class (method, variable) Form, other languages are similar, such as the front-end framework of the web, the so-called framework is actually a bunch of others have written code, you take to use, Then continue to fill in the above code, in the final analysis is actually code reuse. And here in Java, because the implementation is encapsulated in the form of a. class file, we see interfaces: a bunch of. class files in which the concrete implementation of the method is hidden, only a function prototype is seen, so the difficulty of calling the Javacard API is that you have to read the API comments written by others (all-England, To learn English well, to understand what each function does, and then you know what functions you need to use to achieve your function and what the order of the calls is, usually in the API (library) directory, there will be a document (in HTML form). If you flip the. class file with Eclipse, there will be a bunch of HTML tag characters looking at the pain.

Not much to say, on the code:

Des.java (the main file that calls the DES algorithm API):

Package Helloworld;import Javacard.framework.jcsystem;import Javacard.security.deskey;import Javacard.security.Key ; Import Javacard.security.keybuilder;import Javacardx.crypto.cipher;public class des{private Cipher DESEngine; Private Key mykey;private byte[] temp;private randgenerator rand;public Des () {// Must first initialize (get instance instance to init otherwise error) Desengine = Cipher.getinstance (cipher.alg_des_cbc_iso9797_m1, false);// Buildkey creates an uninitialized key, and the key value needs to be manually assigned with the Setkey function MyKey = Keybuilder.buildkey (Keybuilder.type_des, Keybuilder.length_des, FALSE);//Set the staging variable temptemp = Jcsystem.maketransientbytearray (short), jcsystem.clear_on_deselect);//Allocate space for Rand objects, Otherwise, the code of the Randgenerator class cannot be executed!! Rand = new Randgenerator ();//****** 1 ******* first automatically generate a key//generate 64bit random number temp = rand. Genratesecurerand (short)://util.arrayfillnonatomic (Temp1, (short), (short), (byte) 0x11);//Set Key--Take a random number when the key (( Deskey) MyKey). Setkey (temp, (short) 0); 2 ******* initializing encryption key and encryption mode Desengine.init (MyKey, cipher.mode_encrypt);} Public final void Getcipher (byte[] inbuf, ShoRT Inoffset, Short inlength, byte[] outbuf, short outoffset) {//****** 3 ******* incoming ciphertext encrypted and get ciphertext// Need to pay special attention to dofinal encryption after the result is estimated to be more than 64, so outbuf in the previous definition should also be new enough size, otherwise no precise ... Desengine.dofinal (Inbuf, Inoffset, Inlength, Outbuf, Outoffset);}}

(It's too cumbersome to generate the key by hand, so I'm going to call the API that generates the random number and take the random number as the key)

The Randgenerator.java file that generates the random number is then called the Randomdata API:

Package Helloworld;import Javacard.framework.jcsystem;import Javacard.security.randomdata;public class Randgenerator{private byte[] temp;//The value of the random number private randomdata random;private byte size;//random number length//constructor public Randgenerator () {size = (byte) 4;temp = Jcsystem.maketransientbytearray ((short) 4, jcsystem.clear_on_deselect);// The getinstance of the class must first call this function to get an object instance to use other methods, otherwise 6f00random = Randomdata.getinstance (randomdata.alg_secure_random);} Generates a random number of length lengths and returns public final byte[] Genratesecurerand (short length) {temp = new byte[length];// Generates a random number of 4bit random.generatedata (temp, (short) 0, (short) length); return temp;} Returns the random number length public final byte getrandsize () {return size;}}

Finally, test the Applet,hello.java file:

Package Helloworld;//import Hello;import Javacard.framework.apdu;import javacard.framework.applet;import Javacard.framework.iso7816;import Javacard.framework.isoexception;import Javacard.framework.util;public Class Hello extends Applet {//The following are instantiations of unallocated space! You need to use the New keyword later or use the GetInstance function to allocate space! Private Des des = new des ();p ublic static void Install (byte[] Barray, short boffset, byte blength) {//Gp-compliant Javaca Rd applet Registrationnew Hello (). Register (Barray, (short) (Boffset + 1), Barray[boffset]);} public void process (APDU APDU) {//Good Practice:return 9000 on selectif (Selectingapplet ()) {Return;} Set buffer to array buf map binding byte[] buf = Apdu.getbuffer (); Short LC = Apdu.setincomingandreceive ();//Read data and return data length lcbyte[] data = new BYTE[LC]; Util.arraycopynonatomic (buf, ISO7816. Offset_cdata, data, (short) 0, LC);//byte[] src = {' h ', ' e ', ' l ', ' l ', ' o ', ', ', ' w ', ' O ', ' r ', ' L ', ' d '};//11 bytesbyte[] Cipher = new Byte[128];byte ins = buf[iso7816. Offset_ins];switch (INS) {case (byte) 0x00://ins = = 0x00 indicates to use desEncryption//****** 3 ******* the incoming ciphertext encryption and obtains ciphertext DES. Getcipher (data, (short) 0, LC, cipher, (short) 0); Util.arraycopynonatomic (cipher, (short) 0, buf, (short) ISO7816. Offset_cdata, LC); Apdu.setoutgoingandsend ((short) 5, LC); break;//must have a break otherwise it will continue into the switch loop case (byte) 0x01:break; default://good practice:if you don ' t know the instruction, say So:ISOException.throwIt (iso7816.sw_ins_not_supported);}} }


Then perform the test with the JCOP shell tool.

Test Script (DES.JCSH):

/select 554433221100/send 00000000041234567804/send 00000000048765432104

/The first sentence indicates the applet selected for the aid, the last two sentences are input a string of 0x04 length of data to allow the applet to perform encryption (note the conversion between hexadecimal and decimal number, although here 0x04 length equals 4 length of decimal, but 0x20 will remember to convert).

The execution script sees the result:



The applet returns the encrypted ciphertext after the length of the 0x04.


Finally, some of the things that you need to be aware of in writing your code are documented.

1: Because there are multiple classes involved, there will be objects in another class (file) to create the class, but remember to allocate space for this object! Class if there is a getinstance function call this function to instantiate the object, if not, use the New keyword to allocate space to the object! Prior to the appearance of their own no space allocated to the object, the results of the test returned 6F00, and then debugging the time has been skipped Des.java, because there is no space allocated to this object, there is no way to jump past the execution of Des.java inside the code. This is especially important in object-oriented programming.

2: Staging object (contains variable/array) and persistent object. Use Jcsystem.maketransientbytearray (the first parameter represents the length of the array, the second parameter represents the declaration period (which is typically recycled when clear_on_deselect is the deselect of the Aid's applet)) A function can declare a staged array of a fixed length. Why use a staging object? Because Javacard is so small, it has storage space (either memory or ROM (including that EEPROM) is very limited, ROM is generally used to store card operating system (COS, generally written in the assembly) and virtual machines (must have the operating system as the basis for the lower layer, itself is not the operating system), the permanent object will be stored in the EEPROM space, and the temporary objects (arrays) stored in the RAM space, natural read and write speed is much faster, so for the need to update the frequency of data, and staging can, declared as a staging object can improve program efficiency. At the same time, the objects created in the EEPROM must be atomic (such as Javacard's transaction [transaction] processing mechanism), while the handling of objects within RAM is naturally not atomic.

3: Reading the function inside the API is easy to find some in front with the word "@deprecated", @override means to overwrite the parent class, and the previous method is not recommended (will be eliminated or what), generally this method will be deleted line off.

4: Then say a des encryption is not related to the public key cryptography, such as the RSA algorithm, des these symmetric cipher system only need a key, and the public key system requires a public key, so need to use a KeyPair object to store the private key and public key, Instead of using the Privatekey object and the PublicKey object, you need to use the KeyPair object to cover both objects, and then continue to write the RSA algorithm API call blog.

5:switch is equivalent to a loop, after each case must be added a break keyword, or after the execution of a case will continue to run the loop, the next time the value of the cases is indeterminate, so will jump to execute the code inside the default statement, So if there is no break in the execution of a case, then the statement inside the default will be executed later in the program.

6: Refer to the initialization of the object (allocated space), note that this operation is generally placed in the constructor of the class, if it is the applet master file, the install () to complete these operations.

7: Finally extract a few of the above key functions to mention:

Desengine = Cipher.getinstance (cipher.alg_des_cbc_iso9797_m1, false);


The above code is used to instantiate the Des Engine object, to do some allocation of space and initialization of the work, instead of new to complete the allocation of space.


MyKey = Keybuilder.buildkey (Keybuilder.type_des, Keybuilder.length_des, false);

Then this code is used to create uninitialized key objects, before we talk about objects you must give them space before you use them! The Buildkey out here is just an object that has a blank space assigned to it, and you need to use the Setkey function to initialize the key later.

((Deskey) myKey). Setkey (temp, (short) 0);

This is the set (initialize) key, where temp is stored is the previously mentioned generated random number, which is taken when the key is made.

The key is set, and then the key is thrown into the Des engine object, using the following function:

Desengine.init (MyKey, Cipher.mode_encrypt);

The second parameter represents the setup mode, which has two types: encryption and decryption.

Finally, you can encrypt the ciphertext by passing in the data:

Desengine.dofinal (Inbuf, Inoffset, Inlength, Outbuf, Outoffset);












Javacard des algorithm API usage Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.