我使用以下代码在Javacard中加密和解密数据:
private byte[] hello = {'h','e','l','l','o','1','2','3'};
private byte []encryptedData = new byte[8];
private void encrypt(byte[] dataToEncrypt){
try{
byte []inputData = dataToEncrypt;
Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);
DESKey desKey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES,KeyBuilder.LENGTH_DES,false);
byte [] keyBytes = {(byte)0x01,(byte)0x02,(byte)0x03,(byte)0x04, (byte)0x05,(byte)0x06,(byte)0x07,(byte)0x08};
desKey.setKey(keyBytes, (short)0);
cipher.init(desKey, Cipher.MODE_ENCRYPT);
cipher.doFinal(inputData, (short)0, (short)inputData.length, encryptedData,(short)0);
showMessage(encryptedData);
}
catch(CryptoException e){
}
}
private byte []decryptedData = new byte[8];
private void decrypt(byte[] dataToDecrypt){
try{
byte []outputData = dataToDecrypt;
Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);
DESKey desKey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES,KeyBuilder.LENGTH_DES,false);
byte [] keyBytes = {(byte)0x01,(byte)0x02,(byte)0x03,(byte)0x04, (byte)0x05,(byte)0x06,(byte)0x07,(byte)0x08};
desKey.setKey(keyBytes, (short)0);
cipher.init(desKey, Cipher.MODE_DECRYPT);
cipher.doFinal(outputData, (short)0, (short)outputData.length, decryptedData,(short)0);
showMessage(decryptedData);
}
catch(CryptoException e){
}
}
encrypt(hello);
decrypt(encryptedData);
每当我尝试加密一个大小为8字节的对象时,一切正常。但是,只要要加密的对象的大小是其他任何东西,它就不起作用。我相信有一些填充问题。谢谢您的帮助。