使用BouncyCastle进行ECDSA验证:SignatureException:解码签名字节时出错

时间:2018-10-23 14:08:24

标签: java bouncycastle signature ecdsa

当尝试验证签名是否作为字符串保留在数据库上时,出现此异常:

java.security.SignatureException: error decoding signature bytes.
at org.bouncycastle.jcajce.provider.asymmetric.util.DSABase.engineVerify(Unknown Source)
at java.base/java.security.Signature$Delegate.engineVerify(Signature.java:1245)
at java.base/java.security.Signature.verify(Signature.java:674)
at SignCheck.ValidateSignature(SignCheck.java:65)
at SignCheck.main(SignCheck.java:26)

我做错了什么? 这是简化的应用程序:

String signature = "308194024802ce15a95958817cf7ac8086332d0eb7e5a7faed71c225845251514ddf3ca56246498169a27a814f62f457a4336338e9931e4b12dda0e8cf221f83c4a33c31c907a4b3520d0c3c3b0248012801b7f51e810165762ff2848752cefb4dcef1e862d9783740d40d6436e7b45c151bce9ea19c2dce205351115cb3b753af611fdc8dfc19ac11e49f29d81c1699e9f38cdb1ba45d";
String stringToCheck = "CCCCBBBBTue Oct 23 15:26:02 CEST 2018";
String publicKey = "3081a7301006072a8648ce3d020106052b81040027038192000406dbfdc0ccf5cc8230b773b4c21059c3c47e2e832a962a0015f9f440cccc80ca1d4af9f3e39f96dffcd09f6015373e4373a764c2aadac8db8db62e28196a7f7a6cacb971f0cfee570292eb0c8c78b14054ce5b7e85f616b10571044dcfad51c271f09746577aa6068f94d395533f2a8f723a112e72962117fef2e5c6ce4b32d8217a86e96ddec7f8241d4b30941b8f78";

try {
        Security.addProvider(new BouncyCastleProvider());
        Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA", "BC");

        KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
        PublicKey pub= fact.generatePublic(new X509EncodedKeySpec(Hex.decode(publicKey)));
        ecdsaVerify.initVerify(pub);


        ecdsaVerify.update(stringToCheck.getBytes("UTF-8"));
        boolean result = ecdsaVerify.verify(signature.getBytes());

       return result;
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
        e.printStackTrace();
        System.out.println("FALSIFICATION DETECTED!");
    }

1 个答案:

答案 0 :(得分:0)

您要验证的签名为hex格式,而.getBytes()并未执行您期望的签名。您需要将签名的十六进制字符串转换为byte[],然后在ecdsaVerify.verify(signatureBytes)中以该结果进行验证,其中signatureBytesHex.decode(signature)