首先,这不是一个重复的问题,因为大多数人从缺少“ — BEGIN RSA CERTIFICATE–”行的证书创建公钥时报告此异常。
我想要做的要点是1.使用SHA1withRSA算法(RSA密钥为1024位)在JCOP智能卡上签名50Byte消息。2.将签名从智能卡导出到服务器。3.验证服务器上的签名。
智能卡上的代码段以创建签名。关键是我正在使用Java Card中的算法Signature.ALG_RSA_SHA_PKCS1创建签名。
private void setcustccid(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if (buffer[ISO7816.OFFSET_LC] != (byte)24) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
else {
short bytesLeft = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
short readCount = apdu.setIncomingAndReceive();
if (readCount < bytesLeft) {
ISOException.throwIt(ISO7816.SW_BYTES_REMAINING_00);
}
try {
Signature signature = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
signature.init(privKey, Signature.MODE_SIGN);
Util.arrayCopy(buffer, (short)buffer[ISO7816.OFFSET_CDATA], tempStorage, (short) 0, (byte)24);
Util.arrayCopy(transactionHistory, (short)0, tempStorage, (short)24, (byte)30);
}
catch (Exception ex) {
ISOException.throwIt(ISO7816.SW_BYTES_REMAINING_00);
}
signature.sign(tempStorage, (short)0, (short)50, finalEncryptedMsg, (short)0);
}
}
服务器端的代码段试图验证从抛出异常的Java智能卡导出的签名。这里的重点是我在服务器端使用Signature.getInstance(“
SHA1withRSA”)。我正在对签名的消息进行密码解密,只是为了确认生成的公钥是否正常工作。
modulusString = new BigInteger(1, rsaModulus);
exponentString = new BigInteger(1, rsaExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulusString, exponentString);
KeyFactory factor = KeyFactory.getInstance("RSA");
PublicKey publicKey = (RSAPublicKey) factor.generatePublic(keySpec);
rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.DECRYPT_MODE, publicKey);
signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(publicKey);
signature.update(resultBytes);
signature.verify(finalEncryptedMsg);
tempStorage = rsaCipher.doFinal(finalEncryptedMsg);
System.out.println("Decrypted Length = " + tempStorage.length);
例外发生在signature.verify()上。另一个线程引用了相同的异常,但是解决方案是将Bouncy
Castle添加为Signature.getInstance()中的提供者。不确定为什么要要求Bouncy Castle进行签名验证。
任何帮助将不胜感激。如果您需要更多代码来识别问题,请告诉我。
java.security.SignatureException: Signature encoding error
at sun.security.rsa.RSASignature.engineVerify(Unknown Source)
at java.security.Signature$Delegate.engineVerify(Unknown Source)
at java.security.Signature.verify(Unknown Source)
at com.mse.reader.SmartCardReader.main(SmartCardReader.java:234)
Caused by: java.io.IOException: Sequence tag error
at sun.security.util.DerInputStream.getSequence(Unknown Source)
at sun.security.rsa.RSASignature.decodeSignature(Unknown Source)
... 4 more
这是加密的消息和解密的消息。(Base4.encodeBase64)
加密长度= 128
JpypH/vKYR4RLjQA4frCab5WljnAoWgNiGUb0k+DCmh8gdWbOtpR/XUec2rW96Nr1k7czNTb2s/2WQDGXe05a3JjNrlErrfijhdWvn9flIzR/5uPrS3VJw+ALESl8NWqR5HF3AgArE6uYIW87EtSjO0iPJTO2N0cITtLghdUSBs=
解密长度= 50
gCUAABgAAAAAO5rJkAAAAAAAvGFOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=