简体   繁体   中英

JavaCard applet is not working with RSA encryption

I am developing a JavaCard applet. Applet generates RSA public and private keys in constructor and with APDU command encrypt some byte array:

 public RSATestApplet() {
    keyPair = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
    keyPair.genKeyPair();
    rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    rsaPublicKey = (RSAPublicKey) keyPair.getPublic();

    cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);

    register();
}

And main method is:

private void encryptData(APDU apdu) {
    if (!rsaPublicKey.isInitialized()) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    byte[] apduBuffer = apdu.getBuffer();
    apdu.setIncomingAndReceive();

    cipher.init(rsaPrivateKey, Cipher.MODE_ENCRYPT);
    byte[] encryptedBuffer = new byte[apduBuffer.length];
    Util.arrayFillNonAtomic(encryptedBuffer, (short) 0,
            (short) encryptedBuffer.length, (byte) 0xAA);
    cipher.doFinal(encryptedBuffer, (short) 0, (short) encryptedBuffer.length, apduBuffer, (short) 0);
    // Just for testing send 120 bytes
    apdu.setOutgoingAndSend((short) 0, (short) 120);
}

And when I try to install applet APDU response is 6E00 (which means: No precise diagnosis).

I think problem may occurs when cipher.doFinal() is executing.

I tried with other applets and everything works fine.

I compile my applet with JavaCard 2.2.1 and Java 1.2

Do you have any idea what's going on?

I strongly believe that the error you get during your installation of applet is not related to your encryptData method.

I would suggest you to use try catch inside your constructor to catch the exception thrown by JCVM. For example, when you create KeyPair object, it can throw an error if the algorithm and key length are not supported by the platform.

You can try something like this:

try {
     keyPair = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_2048);
} catch (CryptoException e) {
     short reason = e.getReason();
     ISOException.throwIt(reason);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM