title: Verifying a signature with a public key
body: <p>I have an external service which call me back after some defined event, and sign his request with its private key.</p>
  
  <p>I have stored the public key which look like :</p>
  
  <pre><code>-----BEGIN PUBLIC KEY-----
  ........................................
  -----END PUBLIC KEY-----
  </code></pre>
  
  <p>So my work is to check if request's content has not been alterned by verifying signature.</p>
  
  <p>Here is my algorithm :</p>
  
  <pre><code>// 1 - reading public key :
  Scanner scanner = new Scanner( new File( keyPath ) );
  
  
  //            encodedPublicKey.toString( );
  StringBuilder sb = new StringBuilder( );
  while ( scanner.hasNextLine( ) )
  {
      sb.append( scanner.nextLine( ) );
      sb.append( '\n' );
  }
  
  byte[] encodedPublicKey = sb.toString( ).getBytes( "utf-8" );
  
  // 2 - loading public key in a relevant object :
  X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( publicKeyBytes );
  
  KeyFactory keyFactory = KeyFactory.getInstance( "DSA" );
  
  PublicKey publicKey = keyFactory.generatePublic( publicKeySpec );
  
  // 3 - verifying content with signature and content :
  Signature sig = Signature.getInstance( "SHA1withDSA" );
  sig.initVerify( publicKey );
  sig.update( message.getBytes( ) );
  ret = sig.verify( sign.getBytes( ) );
  </code></pre>
  
  <p>But for now my algorithm is stoped at "PublicKey publicKey = keyFactory.generatePublic( publicKeySpec )" step by this message :</p>
  
  <pre><code>java.security.spec.InvalidKeySpecException: Inappropriate key specification: invalid key format
  </code></pre>
  
  <p>So how can I load my key in a way that is accepted by java api ?</p>