title: Java Security - X509 Certificate Verification with Public Key
body: <p>I am working on a project has so much security operations. I have never struggled security issues before. Therefore, my question can be beginner level.</p>
  
  <p>In my problem, I am getting a byte array data has a certificate and some other parameters. I need to verify this certificate and its signature. But I couldn't handle signature verification. In fact, I don't know which public key should I use to verify. </p>
  
  <p>The code is below.
  Thanks for help..!</p>
  
  <pre><code>public boolean startValidation(PublicKey publicKey) {
      CertificateFactory cf;
      try {
           cf = CertificateFactory.getInstance("X.509");
      } catch (CertificateException e) {
          e.printStackTrace();
          return false;
      }
      try {
          certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certBytes));
      } catch (CertificateException e) {
          e.printStackTrace();
          setCertError(0);
          return false;
      }
      if (!checkProvider()){
          setCertError(1);
          return false;
      }
  
      boolean[] usages = certificate.getKeyUsage();
      boolean usage = usages[0] &amp;&amp; usages[2];
      if (!usage){
          setCertError(2);
      }
  
      try {
          certificate.checkValidity();
      } catch (CertificateNotYetValidException e) {
          e.printStackTrace();
          setCertError(3);
          return false;
      } catch (CertificateExpiredException e) {
          e.printStackTrace();
          setCertError(4);
          return false;
      }
  
      System.out.println("Sign Algorithm Name " + certificate.getSigAlgName());
      //Output is SHA256WithRSAEncryption
  
     // Problem area
      try {
          Signature signature = Signature.getInstance("SHA256WithRSA");
          signature.initVerify(publicKey); //Should I use this certificate.getPublicKey() or what ??
          if(signature.verify(certificate.getSignature())){
              System.out.println("Accepted");
          }else System.out.println("Failure");
      } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
      } catch (InvalidKeyException e) {
          e.printStackTrace();
      } catch (SignatureException e) {
          e.printStackTrace();
      }
  
      System.out.println("Public Key Format " + publicKey.getFormat() + "\nPublic Key Algorithm " + publicKey.getAlgorithm() );
      System.out.println("Subject DN -&gt; " + certificate.getSubjectDN().getName());
  
  
      return true;
  }
  </code></pre>