JavaCard小程序无法使用RSA加密

时间:2015-10-07 14:01:40

标签: java encryption applet rsa javacard

我正在开发一个JavaCard applet。 Applet在构造函数中生成RSA公钥和私钥,并使用APDU命令加密某些​​字节数组:

 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();
}

主要方法是:

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);
}

当我尝试安装applet APDU响应是6E00(这意味着:没有精确诊断)。

我认为当cipher.doFinal()正在执行时可能会出现问题。

我尝试过其他小程序,一切正常。

我使用JavaCard 2.2.1和Java 1.2编译我的applet

你知道发生了什么吗?

1 个答案:

答案 0 :(得分:4)

我坚信您在安装applet时遇到的错误与您的encryptData方法无关。

我建议你在构造函数中使用try catch来捕获JCVM抛出的异常。例如,当您创建KeyPair对象时,如果平台不支持算法和密钥长度,则会抛出错误。

您可以尝试这样的事情:

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