我需要在java中验证签名。我得到一个有多个参数的网址,其中一个是签名(十六进制格式)。签名的消息是所有其他参数的串联的SHA-256哈希。我还有带有公钥的证书用于检查。 我用于测试的所有值都是通过一个应该是正确的示例给我的,我只是创建了连接字符串。
这是我运行的代码:
// signed message --> hash of concat
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update( concat.getBytes() );
byte[] message = digest.digest();
System.out.println("message length "+message.length); // --> 32
// signature belonging to the message --> checkValue
System.out.println("check value length " +checkValue.length()); // --> 512
byte[] sigBytes = checkValue.getBytes();
System.out.println("check value bytes "+sigBytes.length); // --> 512
// public certificate of the CA
File file3 = new File(certificatePath);
byte[] encCertRSA = new byte[(int) file3.length()];
FileInputStream fis3 = new FileInputStream(file3);
fis3.read(encCertRSA);
fis3.close();
InputStream is = new ByteArrayInputStream( encCertRSA );
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certRSA = (X509Certificate)f.generateCertificate(is);
certRSA.checkValidity();
PublicKey pubKeyRSA = certRSA.getPublicKey();
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(pubKeyRSA);
// supply the Signature object with the data for which a signature was generated --> hash of concat
sig.update(message);
boolean isValid = sig.verify( sigBytes );
System.out.println("The signature of the email verifies: " + isValid);
这是我得到的错误:
java.security.SignatureException: Signature length not correct: got 512 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(Unknown Source)
at java.security.Signature$Delegate.engineVerify(Unknown Source)
at java.security.Signature.verify(Unknown Source)
我做错了吗?我期望签名的长度为256,而不是512.我运行一个测试,使用签名值的子字符串来匹配256的长度,我没有得到上面的错误,但是sig.verify返回false
答案 0 :(得分:-1)
如果您查看您编写的代码,那么System.out.println("check value bytes "+sigBytes.length); // --> "512"
然后boolean isValid = sig.verify( sigBytes );
看起来您的sigBytes变量在检查之前已经有512长度