title: RSA Signing and verifying in java
body: <p>I'm trying to sign a message in java and it doesn't seem to work. The verifying step gives me false.</p>
  
  <p>Can anyone tell me where is my mistake. I can't understand what I'm doing wrong.
  Thanks </p>
  
  <pre><code>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) {
  
      }    }
  </code></pre>