【java.security.SignatureException: Signature length not correct】的解决办法

错误信息

对接某家公司的接口,涉及String转ASCII,验签时候报错。

java.security.SignatureException: Signature length not correct: got 344 but was expecting 256

错误原因

签名长度不正确:实际值为344,但期望值为256

在生成签名的时候,用的是 Base64.encodeBase64String(signByte) 成签名字符串。

Base64.encodeBase64String(signBySHA256WithRSA(sign, priKey).getBytes("UTF-8"));

解决方案

签名的值进行二次Base64.decodeBase64处理。

            //处理公钥
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
            PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);
            //解密
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(pubKey);
            String jwsHeaderBase64 = sign.substring(0,sign.indexOf(".."));
            String jwsSignBase64 = sign.substring(sign.indexOf("..") + 2);
            String dateToSign = stringToAscii(new StringBuilder().append(jwsHeaderBase64).append('.').append(Base64.encodeBase64String(content.getBytes("UTF-8"))).toString());

            signature.update(dateToSign.getBytes("UTF-8"));
            System.out.println(Base64.decodeBase64(jwsSignBase64).length);
            System.out.println(Base64.decodeBase64(jwsSignBase64));
            System.out.println(Base64.decodeBase64(Base64.decodeBase64(jwsSignBase64)).length);
            return signature.verify(Base64.decodeBase64(Base64.decodeBase64(jwsSignBase64)));

你可能感兴趣的:(D5-加解密,C1-Java)