RSA Signing and verifying in java

Carmen Cojocaru picture Carmen Cojocaru · Jan 17, 2014 · Viewed 14k times · Source

I'm trying to sign a message in java and it doesn't seem to work. The verifying step gives me false.

Can anyone tell me where is my mistake. I can't understand what I'm doing wrong. Thanks

String messageString = "text";
try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
        keyGen.initialize(512, new SecureRandom());
        KeyPair keyPair = keyGen.generateKeyPair();
        PublicKey RSAPublicKey = keyPair.getPublic();
        PrivateKey RSAPrivateKey = keyPair.getPrivate();

        System.out.println("public key = " + RSAPublicKey);
        System.out.println("private key = " + RSAPrivateKey);

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Signature signature = Signature.getInstance("SHA1withRSA", "BC");
        signature.initSign(RSAPrivateKey, new SecureRandom());
        byte[] message = messageString.getBytes();
        signature.update(message);
        byte[] sigBytes = signature.sign();

        Signature signature1 = Signature.getInstance("SHA1withRSA", "BC");
        signature1.initVerify(RSAPublicKey);
        signature1.update(sigBytes);

        boolean result = signature1.verify(sigBytes);
        System.out.println("result = "+result);
    } catch (NoSuchAlgorithmException | NoSuchProviderException | SignatureException | InvalidKeyException ex) {

    }    }

Answer

Developer Marius Žilėnas picture Developer Marius Žilėnas · Jan 17, 2014

You have your signature in variable sigBytes and your message is in variable message. To verify a message first do signature1.update(message) and then do signature1.verify(sigBytes).

The following code example verifies signature:

Signature signature1 = Signature.getInstance("SHA1withRSA", "BC");
signature1.initVerify(RSAPublicKey);
signature1.update(message);
boolean result = signature1.verify(sigBytes);

:)