Saturday, May 3, 2014

Digital Signature in Java Part II

Previously on this blog post, we have created a digital signature by encrypting message digest using private key. Now we will see what Java provides for us to simplify digital signature creation.


First, we created the message that we want to sign and generate its byte array as shown above.


Next, we created a Signature object. This class takes an algorithm name as its parameter. In the code above we passed MD5WithRSA as the input since we want to use message digest with RSA as we did on this blog post. We could use other algorithm names as well.

Next we initialized the Signature object with our private key object. Refer to this post on how to create private key using RSA. Then we updated the signature with our original message.


Now we are ready to sign the message with our private key. The code above showed us how to do that by simply calling sign() method on the Signature object. The signatureByte above is our digital signature byte. We can now send it along with the message string to the recipients.


When the recipient receives our message, he/she needs to verify the signature as well as the message. First, recipient has to initialize the Signature object with our shared public key as shown above. Here is the post that explains how to create a public key. Note that for message signing we called initSign() while for message verifying we called initVerify() method.

Then we updated the Signature object with the plain message that was sent along with the signature by calling update() method. To verify if the signature is valid, we passed the signature byte that we got from the sender to the Signature object as we did above.

0 comments:

 

©2009 Stay the Same | by TNB