Verifying a signature with a public key

Viewed 29812

I have an external service which call me back after some defined event, and sign his request with its private key.

I have stored the public key which look like :

-----BEGIN PUBLIC KEY-----
........................................
-----END PUBLIC KEY-----

So my work is to check if request's content has not been alterned by verifying signature.

Here is my algorithm :

// 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( ) );

But for now my algorithm is stoped at "PublicKey publicKey = keyFactory.generatePublic( publicKeySpec )" step by this message :

java.security.spec.InvalidKeySpecException: Inappropriate key specification: invalid key format

So how can I load my key in a way that is accepted by java api ?

1 Answers
Related