title: Digital signature verification failing - Java
body: <p>I am generating digital signature using below methods with payload as "hello world"</p>
  
  <pre><code>public String generateSignature(String payload) throws Exception{
          Signature rsa = null;
          rsa = Signature.getInstance("SHA256WithRSA/PSS", new BouncyCastleProvider());
          rsa.initSign(getPrivateKey("Keys/private_key"));
          rsa.update(payload.getBytes(StandardCharsets.UTF_8));
          byte[] signatureBytes = Base64.encodeBase64(rsa.sign());
          String signature = DatatypeConverter.printHexBinary(signatureBytes);
          return signature;
      }
  </code></pre>
  
  <p>I am validating the signature with payload "hello world" and signature that I got from generateSignatue method.</p>
  
  <pre><code>public boolean validateSignature(String payload, String signature) throws Exception {
      Signature sig = Signature.getInstance("SHA256WithRSA/PSS", new BouncyCastleProvider());
      boolean isValid = false;
      sig.initVerify(getPublicKey("Keys/public_key"));                
      sig.update(payload.getBytes(StandardCharsets.UTF_8));
      isValid = sig.verify(Base64.decodeBase64(signature.getBytes("UTF-8")));
      return isValid;
  }
  </code></pre>
  
  <p>This is always returning isValid as false, what is the mistake?</p>
  
  <p>Retrieving Public key &amp; private key with below functions (for reference):</p>
  
  <pre><code>public static PublicKey getPublicKey(String filename) throws Exception {
          byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
          X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
          KeyFactory kf = KeyFactory.getInstance("RSA");
          return kf.generatePublic(spec);
      }
  
  public static PrivateKey getPrivateKey(String filename) throws Exception {
      byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
      PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory kf = KeyFactory.getInstance("RSA");
      return kf.generatePrivate(spec);
  }
  </code></pre>