[英]How to use Java Card crypto sample?
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 Card Connected上的密碼運行示例簡單?
UPDATE
正如@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);
同
Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M2, false);
我在文檔中找不到任何有關它的信息。
這些行似乎是錯誤的:
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
有效)。
奇怪的是,這應該導致CryptoException.ILLEGAL_USE
原因(相對於您得到的3,它是5)...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.