3

I have a key pair already, public and private. How do I actually use the java.security.Signature to do verification of a string I signed with one of the keys?

Edit:

I have both the keys as Strings. The verify method, it is actually

verify(byte[] signature)

The javadoc says:

verify(byte[] signature) Indicates whether the given signature can be verified using the public key or a certificate of the signer.

How would I make that signature recognize which public/private key to use for that verifying, before I call the verify method? In other words, how do I turn my string keys into key objects that would get accepted by signature?

1
  • Is there by any chance a method named verify in that class? If so perhaps you have a more specific question. Commented Feb 10, 2012 at 0:21

1 Answer 1

8
  1. Use KeyFactory to translate key specifications to objects.
  2. Call Signature.getInstance(algName) to get a signature instance.
  3. Use Signature's initVerify method to associate a key for signature verification.
  4. Use update to feed the Signature bytes.
  5. Finally, call verify.
  6. Profit

From the KeyFactory javadoc:

The following is an example of how to use a key factory in order to instantiate a DSA public key from its encoding. Assume Alice has received a digital signature from Bob. Bob also sent her his public key (in encoded format) to verify his signature. Alice then performs the following actions:

X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
Signature sig = Signature.getInstance("DSA");
sig.initVerify(bobPubKey);
sig.update(data);
sig.verify(signature);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. So in my case, I would change "DSA" to "RSA", right?
@sammiwei, I don't know whether it's "RSASSA-PSS" or what the appropriate algorithm name is to your situation, but you are correct in that you need to substitute the correct name for "DSA" in two places in that example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.