Search code examples
javasecuritycertificatedigital-signatureobjectoutputstream

Can't verify signature after reading signed file


sign.verify(signature) returns false in the verifySignature method; and I think it has something to do about how I use outputstreams and inputstreams with the signedobject.obj file (certificate passed validity). I can read the message correctly from file.

Code:

RSAPrivateKey pk = (RSAPrivateKey) ks.getKey("CS2", "fihjo".toCharArray());
Signature s = Signature.getInstance("SHA1withRSA");
s.initSign(pk);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
String message = "Hi Sign ME!!!";
oos.writeObject(message);
oos.writeObject(s.sign());
byte[] barr = baos.toByteArray();
s.update(barr);

FileOutputStream out1 = new FileOutputStream("signedobject.obj");
out1.write(barr);
//out1.write(s.sign());
out1.close();

verifySignature(ks);

verifySignature(KeyStore) method:

FileInputStream fis = new FileInputStream("signedobject.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
String message   = (String)ois.readObject(); // read message
System.out.println("msg: "+message);
byte[] signature = (byte[])ois.readObject(); // read signature, hmmm

X509Certificate xcert = (X509Certificate) ks.getCertificate("CS1");
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initVerify(xcert.getPublicKey());
sign.update(message.getBytes());
if ( sign.verify(signature) )  // This is where it fails!
System.out.println("It is validly signed. String: "+message);
else System.out.println("It isn't valid");

Solution

  • You have to call sign after update on the byte array of the message. For example:

    String message = "Hi Sign ME!!!";
    s.update(message.getBytes("UTF8");
    byte[] signature = s.sign()
    
    oos.writeObject(message);
    oos.writeObject(signature);