Digital Signature With Plain Text in Java

Introduction

 
This article is a sequel to my previous article about "XML Digital Signature in Java" posted in this site. Based upon the various feedbacks and comments from my friends, colleagues and well-wishers, I will present a brief glimpse of the creation of a digital signature with plain text. This article is more about a technical overview of digital signature creation with the Java API. As you know, we use digital signatures to authenticate the actual message. In the case of plain text, we can use a detached digital signature to verify that the message contents has not yet been tampered with by unauthorized users. To have a practical feeling of signature creation we can use a Java API called "Signature" to create a digital signature.
 
Technicalities
 
To understand the concept of digital signature creation, we need to use the following procedure. In this case we use asymmetric cryptography to generate the keys. The procedure is given below.
  • Create a pair of keys called Private and Public keys
  • Use the private key and your text message to generate a digital signature
  • Send the public key, actual text message and digital signature separately to the destination
  • Use the public key, text message and digital signature to verify the message
  • If the verification is successful then process the message otherwise throw an exception and discard the message.
To provide a better understanding I provide the following activity diagram.
 
Digital Signature activity diagram 
 

Digital Signature Creation with Java API 

 
Let us see the code below about how to create a digital signature and verify the signature.
  1. //To create digital signature  
  2. Signature sig = Signature.getInstance(ALGORITHM);  
  3. sig.initSign(privateKey);  
  4. sig.update(textBuffer);  
  5. byte[] signedData = sig.sign();  
  6.   
  7. //To verify digital signature  
  8. Signature sig = Signature.getInstance(ALGORITHM);  
  9. sig.initVerify(publicKey);  
  10. byte[] sigBuffer = originalContents.getBytes("UTF8");  
  11. sig.update(sigBuffer);  
  12. isSignOk = sig.verify(signedData);  
In the code above, you can mark that we use the class called "Signature" that is available in the JDK. Let us see the structure of the Signature class.
 
signature class in java 
 
The class signature is an abstract one that provides the basic functionality to create a signature and to verify the signature. It supports the cryptographic algorithms like MD2withRSA, MD5withRSA and SHA1withRSA.
 
As a part of the example, I provide the following complete example of how to create and verify a digital signature for a plain text. Let us see the code below.
  1. package com.ddlab.rnd.crypto;   
  2. import java.io.File;  
  3. import java.security.PrivateKey;  
  4. import java.security.PublicKey;   
  5. /** 
  6.  * The Class TestDigitalSignature is used to test the concept of digital 
  7.  * signature for a plain string. 
  8.  *  
  9.  * @author <a href="mailto:[email protected]">Debadatta Mishra</a> 
  10.  * @since 2013 
  11.  */  
  12. public class TestDigitalSignature {   
  13.       /** 
  14.        * Creates the keys. 
  15.        */  
  16.       public static void createKeys() {  
  17.             if (!new File("keys" + File.separator + "privatekey.key").exists()  
  18.                         && !new File("keys" + File.separator + "publickey.key")  
  19.                                     .exists()) {  
  20.                   KeyGenerator keyGen = new KeyGenerator();  
  21.                   keyGen.storeKeyPairs("keys");  
  22.                   System.out  
  23.                               .println("Private key and Public Keys generated successfully...");  
  24.             }  
  25.       }   
  26.       /** 
  27.        * Generate digital signature. 
  28.        *  
  29.        * @param secretInfoStr 
  30.        *            the secret info str 
  31.        * @param privateKeyPath 
  32.        *            the private key path 
  33.        * @return the byte[] 
  34.        */  
  35.       public static byte[] generateDigitalSignature(String secretInfoStr,  
  36.                   String privateKeyPath) {  
  37.             PrivateKey privateKey = KeyUtil.getStoredPrivateKey(privateKeyPath);  
  38.             byte[] signedDataBytes = DigitalSignatureUtil.getDigitalSignature(  
  39.                         secretInfoStr, privateKey);  
  40.             return signedDataBytes;  
  41.       }   
  42.       /** 
  43.        * Verify digital signature. 
  44.        *  
  45.        * @param secretInfoStr 
  46.        *            the secret info str 
  47.        * @param signedDataBytes 
  48.        *            the signed data bytes 
  49.        * @return true, if successful 
  50.        */  
  51.       public static boolean verifyDigitalSignature(String secretInfoStr,  
  52.                   byte[] signedDataBytes) {  
  53.             PublicKey publicKey = KeyUtil.getStoredPublicKey("keys"  
  54.                         + File.separator + "publickey.key");  
  55.             boolean flag = DigitalSignatureUtil.isTextAndSignatureValid(  
  56.                         secretInfoStr, signedDataBytes, publicKey);  
  57.             return flag;  
  58.       }   
  59.       /** 
  60.        * The main method. 
  61.        *  
  62.        * @param args 
  63.        *            the arguments 
  64.        * @throws Exception 
  65.        *             the exception 
  66.        */  
  67.       public static void main(String[] args) throws Exception {  
  68.             // Create Keys if the keys do not exist  
  69.             createKeys();  
  70.             String mySecretMsg = "This is my secret and authentic message .";  
  71.             String privateKeyPath = "keys" + File.separator + "privatekey.key";  
  72.             // Use Private key and Secret message to generate digital signature  
  73.             byte[] signedBytes = generateDigitalSignature(mySecretMsg,  
  74.                         privateKeyPath);  
  75.             String digitalSignatureStr = new String(signedBytes);  
  76.             System.out.println("Digital Signature : \n" + digitalSignatureStr);  
  77.             // Verify Digital Signature  
  78.             boolean flag = verifyDigitalSignature(mySecretMsg, signedBytes);  
  79.             System.out.println("Digital Signature Verification Status : " + flag);  
  80.       }   
  81. }  
The preceding Java code is available inside the test source folder of the attached project. To get a clear understanding, let me provide both of the following, the class diagrams and sequence diagram.
 
sequence diagram in java 
 
The class diagram is given below.
 
java class diagram  
 
You can download the complete project from this site. If you encounter a problem in viewing the images then you can find all the relevant images inside the diagram folder of the attached project.
 
Configuration
 
Download the complete project. You can configure the complete project in Eclipse and run the test classes available inside the test source folder.
 

Conclusion

 
I hope you have enjoyed my small article about digital signatures for plain text or strings in Java. Download the complete project and go through the source code to understand the concept and its usage. Based upon the complexity and design, you can decide whether to use this concept. For any kind of issues and errors you can contact me at [email protected].


Similar Articles