Rsa2验签报错【java.security.SignatureException: Signature length not correct】的解决办法
在进行RSA2进行验签的时候,报了以下错误:
java.security.SignatureException: Signature length not correct: got 344 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:189)
at java.security.Signature$Delegate.engineVerify(Signature.java:1192)
at java.security.Signature.verify(Signature.java:626)
翻译成中文的意思是:java.security.signatureException:签名长度不正确:得到344,但期望256
问题原因是:
在生成签名的时候,用的是 Base64.encodeBase64String(signByte) 成签名字符串。
1 /** 2 * 生成签名字符串. 3 * @param encryptStr 4 * @return 5 * @throws Exception 6 */ 7 private static String generateSignByRsa(String encryptStr) throws Exception { 8 if (logger.isInfoEnabled()) { 9 logger.info("生成Rsa签名字符串..."); 10 } 11 12 // 用商户私钥生成签名字符串 13 RsaEncrypt rsaEncrypt = new RsaEncrypt(); 14 rsaEncrypt.loadPrivateKey(MpayConfig.signMap.get(MpayConfig.PRIVATE_KEY)); 15 byte[] signByte = rsaEncrypt.sign(encryptStr, rsaEncrypt.getPrivateKey()); 16 String reqSign = Base64.encodeBase64String(signByte); 17 logger.info("Rsa签名字符串:" + reqSign); 18 return reqSign; 19 }
在验签的时候,直接getBytes方法返回字节数据,这样就导致签名字符串长度不一致了。
1 RsaEncrypt rsaEncrypt=new RsaEncrypt(); 2 rsaEncrypt.loadPublicKey(publicKey); 3 return rsaEncrypt.verifySign(content,sign.getBytes(RsaEncrypt.ENCODING),rsaEncrypt.getPublicKey());
解决方案:
正确的方式应该是,获取签名字符串字节数组时,跟签名时保持一样,用Base64Util.decode(sign)方法来获取
1 RsaEncrypt rsaEncrypt=new RsaEncrypt(); 2 rsaEncrypt.loadPublicKey(publicKey); 3 byte[] signByte = Base64Util.decode(sign); 4 return rsaEncrypt.verifySign(content,signByte,rsaEncrypt.getPublicKey());