2

有人可以给我一个关于如何使用 javacard 签名并验证它的小建议吗?我想我在签名生成和验证方面做错了:

...

SignatureMessageRecovery sig;

...

private Cardlet(byte[] bArray, short bOffset, byte bLength) {
    /* Generate our RSA key */
    keyPair = new KeyPair(KeyPair.ALG_RSA, (short) 512);
    keyPair.genKeyPair();
    /* signature buffer is 64 + 2 (offset + length) */
    sigBuff = JCSystem.makeTransientByteArray((short) (SIG_LENGTH + 2), JCSystem.CLEAR_ON_DESELECT);
    sig = (SignatureMessageRecovery) Signature.getInstance(Signature.ALG_RSA_SHA_ISO9796_MR, false);
}

...

private void insCryptoSigne(APDU apdu) {

    byte[] buffer = apdu.getBuffer();
    short bytesRead = apdu.setIncomingAndReceive();
    short[] m1Data = JCSystem.makeTransientShortArray((short) 1, JCSystem.CLEAR_ON_DESELECT);

    sigLen = sig.sign(buffer, ISO7816.OFFSET_CDATA, bytesRead, sigBuff, (short) 0, m1Data, (short) 0);
    // set m1Length into sigBuff array
    sigBuff[sigLen] = (byte) ((short) (m1Data[(short) 0] & ((short) 0xFF00)) >> ((short) 8));
    sigBuff[(short) (sigLen + 1)] = (byte) (m1Data[(short) 0] & ((short) 0x00FF));

    apdu.setOutgoing();
    apdu.setOutgoingLength((short) (sigLen + 2));// The extra 2 bytes for
    apdu.sendBytesLong(sigBuff, (short) 0, (short) (sigLen + 2));
}

在 Java 方面 ,我已经将公钥作为 X509Certificate 保存在本地文件中。很确定它们与证书和卡中的模数和指数相同。

FileInputStream certis = new FileInputStream(cert);
X509Certificate c1 = new X509Certificate(certis);

...

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] testsig = new byte[64];
System.arraycopy(raw_signature,0, testsig, 0, 64);
Signature signature = Signature.getInstance("SHA1withRSA", "BC");
signature.initVerify(c1.getPublicKey());
System.out.println(c1.getPublicKey());
System.out.println(signature);
System.out.println(file_data.length+":> "+new String(file_data));
signature.update(file_data);
System.out.println("VERIFY > "+signature.verify(testsig)+" <");

结果是假的:(

感谢和问候图里

4

1 回答 1

1

对于初学者,您正在使用两个单独的签名函数。较旧的 ISO9796 与"SHA1withRSA"在 Java 端指定时使用的 PKCS#1 签名格式有很大不同。你真的需要消息恢复吗?它现在主要用于卡可验证证书(如果使用的话)。

只需在 Java Card 端使用SignatureandALG_RSA_SHA_PKCS1代替SignatureMessageRecoveryand即可。ALG_RSA_SHA_ISO9796_MR

如果您想要消息恢复,您可能必须在 Java 端使用 Bouncy Castle 库(即使在 Bouncy 中,要使其正常工作也有点棘手)。

于 2012-01-08T03:11:41.997 回答