在Java卡中使用CBC DES加密

时间:2016-02-24 17:06:12

标签: encryption javacard 3des cbc-mode

我正在尝试使用Cipher类加密数据。我想指定初始向量,所以我使用以下函数:

try {
    cipherCBC = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    cipherCBC.init(k, Cipher.MODE_ENCRYPT,INITVECTOR,(short)0,(short)8);
    cipherCBC.doFinal(data, (short) 0, (short) data.length, result, (short) 0);
} catch (Exception e) {
    ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}

字节数组INITVECTOR由8字节数组初始化。

问题是当我使用init函数时,我总是遇到异常。

额外信息:

关键是在这里构建:

octetsLus = (byte) (apdu.setIncomingAndReceive());
if (octetsLus != 16) {
    ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}    

// build host crypto 
Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+4),  message, (short) 0,(short) 4);
Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+8),  message, (short) 4,(short) 4);
Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA),    message, (short) 8,(short) 4);
Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+12), message, (short) 12,(short) 4);

// GENERATE SESSION KEYS 
encrypt_DES(ENC_key, message,(byte) 0x01);
Util.arrayCopy(result,(short) 0, ENC_SESS_KEY, (short) 0,(short) 16);

encrypt_DES(MAC_key, message,(byte) 0x01);
Util.arrayCopy(result,(short) 0, MAC_SESS_KEY, (short) 0,(short) 16);

ENC_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
ENC_key.setKey(ENC_SESS_KEY, (short) 0);

MAC_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
MAC_key.setKey(MAC_SESS_KEY, (short) 0);


 Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA), message, (short) 0,(short) 8); 
 Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+8), message, (short) 8,(short) 8);

   for(i=0;i<8;i++)
     message[(short)(16+i)]=(byte)PADDING[i];

关于初始向量,即使我使用以下初始化,我也会遇到同样的问题:

INITVECTOR =new byte[]{(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00};

另一方面,当我使用使用默认初始化参数的init函数时,加密函数运行良好:

cipherCBC.init(k, Cipher.MODE_ENCRYPT);

0 个答案:

没有答案