我使用openssl私钥创建了一个签名。如何在java中验证它?

时间:2014-07-28 12:05:54

标签: java openssl digital-signature verify

使用以下命令在test.txt上生成签名

$ openssl -dgst -sha256 -sign MyPrivateKey.key -out signaturefile test.txt

如何通过java验证签名?

我尝试使用以下方法,但是返回时出现以下错误。

FileInputStream keyfis = new FileInputStream("pubkey.pem");

byte[] encKey = new byte[keyfis.available()];  

keyfis.read(encKey);

keyfis.close();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

FileInputStream signaturefileinput = new FileInputStream("signaturefile");
byte[] sigToVerify = new byte[signaturefileinput.available()]; 
signaturefileinput.read(sigToVerify);   
signaturefileinput.close();
System.out.println(sigToVerify);

Signature signature = Signature.getInstance("SHA256withRSA");

signature.initVerify(pubKey);

FileInputStream datafis = new FileInputStream("test.txt");
BufferedInputStream bufin = new BufferedInputStream(datafis);

byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0) {
    len = bufin.read(buffer);
    signature.update(buffer, 0, len);
};

bufin.close();

boolean verifies = signature.verify(sigToVerify);
System.out.println("signature verifies: " + verifies);

有人可以向我解释导致错误的原因吗?

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(Unknown Source)
    at java.security.KeyFactory.generatePublic(Unknown Source)
    at verifyingsignature.encodingsignature.main(encodingsignature.java:31)
Caused by: java.security.InvalidKeyException: invalid key format
    at sun.security.x509.X509Key.decode(Unknown Source)
    at sun.security.x509.X509Key.decode(Unknown Source)
    at sun.security.rsa.RSAPublicKeyImpl.<init>(Unknown Source)
    at sun.security.rsa.RSAKeyFactory.generatePublic(Unknown Source)
    ... 3 more

0 个答案:

没有答案