如何使用Java卡加密示例?

如何使用Java卡加密示例?,java,servlets,encryption,javacard,Java,Servlets,Encryption,Javacard,我想跑。 我写了这个方法: public static byte[] cipher(byte[] inputData) { Cipher cipher = Cipher.getInstance( Cipher.ALG_DES_CBC_NOPAD, true); DESKey desKey = (DESKey) KeyBuilder.buildKey( KeyBuilder.

我想跑。 我写了这个方法:

public static byte[] cipher(byte[] inputData) {
    Cipher cipher
        = Cipher.getInstance(
                Cipher.ALG_DES_CBC_NOPAD, true);

    DESKey desKey = (DESKey) KeyBuilder.buildKey(
                             KeyBuilder.TYPE_DES,
                             KeyBuilder.LENGTH_DES,
                             false);

    byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};
    desKey.setKey(keyBytes, (short) 0);

    cipher.init(desKey, Cipher.MODE_ENCRYPT);
    byte[] outputData = new byte[8];

    cipher.doFinal(inputData, (short) 0, (short) inputData.length, outputData, (short) 0);
    return outputData;
}
并调用此方法
cipher(“test”.getBytes())。当我调用这个servlet时,服务器会给我内部服务器错误和
javacard.security.CryptoException

我尝试了
ALG_DES_CBC_ISO9797_M1
ALG_DES_CBC_ISO9797_M2
(和其他人),得到了相同的异常

如何在连接的Java卡上运行简单的密码示例

更新

正如@vojta所说,密钥必须是8字节长。所以它一定是这样的:

byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};
我不知道为什么,但它只有在替换时才起作用

Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, true);


我在文档中找不到关于它的任何信息。

这些行似乎是错误的:

byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};
desKey.setKey(keyBytes, (short) 0);

DES密钥应该大于4字节,对吗?标准DES键的长度为8字节(强度为56位)。

除了@vojta的答案外,输入数据应该是块对齐的

您的输入数据
“test”.getBytes()
的长度为4,对于
Cipher.ALG_DES_CBC_NOPAD
无效(但对于
Cipher.ALG_DES_CBC_ISO9797_M2
有效)


奇怪的是,这会导致
加密异常。非法的\u使用
原因(这是5,而不是你得到的3).

只是一些注释:不要在方法中创建新的字节数组->你很快就会耗尽内存<代码>输出数据
数组应该更长,对吗?否则它只能保存一块数据。谢谢。这只是一个示例,但我会考虑,我将其更改为byte[]keyBytes={(byte)0x01,(byte)0x02,(byte)0x03,(byte)0x04,(byte)0x01,(byte)0x02,(byte)0x03,(byte)0x04};但得到了相同的异常。@user980828对异常实例调用getReason的结果是什么?getReason()的结果是3。@user980828表示“没有这样的算法”。您的卡支持classic DES吗?@user980828请尝试替换
Cipher.ALG_DES_CBC_NOPAD,true)带有
Cipher.ALG_DES_CBC_NOPAD,false)?我认为默认平台不支持外部访问。。。
byte[] keyBytes = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04};
desKey.setKey(keyBytes, (short) 0);