Sunday, June 29, 2014
Today in this tutorial I am going to show you how to generate and use Digital Signature to sign any data or document in Java. Digital Signatures are a very important part of security. It ensures authenticity and non-repudiation of any data. In order to prove authenticity, the sender of the data signs the data with a digital signature and the receiver verifies the signature. Here we will only consider about signing the data, while verifying digital signature will be discussed in another later tutorial.

How to sign data with digital signature ?
1. Form the message to be signed.
2. Generate a public-private key pair
3. Calculate hash of the message and encrypt it with sender's private key
4. Send the dugutally signed message with the signature along with the public key.

In this tutorial, we will be signing the data stored in a file. The file path will be taken as an input. The resulting output will be two file : a .dsa file containing the digital signature, and a .pubkey file containing the public key in encoded form.
You can directly use keys either stored in keystore or files but here we will generate the key pair. The procedure taken here to sign data is described step by step

  • Create KeyPairGenerator object with DSA as algorithm using getInstance() method.
  • Initialize the object created with the key-size using initialize() method, e.g. 1024 bits
  • Generate the KeyPair object from KeyPairGenerator object and extract PrivateKey and PublicKey object.
  • Save the public key in encoded form in a file.
  • Create the Signature object with SHA1withDSA (where SHA1 is the message digest algorithm and DSA is the signature algorithm) using getInstance() method.
  • Initialize the signature object with the private key using initSign() method.
  • Read the data from file and go on updating signature object with the data using update() method.
  • Finally get the signature as output using sign() method and save it in a file.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

public class DataSigner {
 
 /**
  * Signs the data in a file and saves the digital signature and 
  * public key in two seperate files withot changing original data
  * @param path File path whose data to be signed
  * @throws FileNotFoundException
  * @throws IOException
  * @throws SignatureException
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeyException
  */
 public void sign(String path) throws FileNotFoundException, IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException{
  //get key pair generator for Digital Signature Algorithm
  KeyPairGenerator kGen = KeyPairGenerator.getInstance("DSA");
  kGen.initialize(1024);  //1024 is the key size
  KeyPair keyPair = kGen.generateKeyPair();  //generate orivate-public key pair
  PrivateKey privKey = keyPair.getPrivate();  //extract private key from pair
  PublicKey pubKey = keyPair.getPublic();  //extract public key from pair
  saveToFile(pubKey.getEncoded(), path+".pubkey");  //save public key to file in encoded form
  //Get signature object for signing with SHA1 as MessageDigest and DSA as signature algorithm
  Signature signature = Signature.getInstance("SHA1withDSA");
  signature.initSign(privKey);  //initialize signature object for signing
  
  try(BufferedInputStream bin = new BufferedInputStream(new FileInputStream(path))){
   byte buf[] = new byte[4096];
   int read = 0;
   while((read = bin.read(buf)) != -1)  //read data to be signed
    signature.update(buf, 0, read);  //update signature object with data
  }
  
  byte out[] = signature.sign();  //sign the data
  saveToFile(out, path+".dsa");  //save the digital signature in file
 }
 
 /**
  * Saves a byte array in file
  * @param data byte array to be saved
  * @param path File path of the data to be saved
  * @throws IOException
  */
 public void saveToFile(byte[] data, String path) throws IOException{
  try(FileOutputStream fos = new FileOutputStream(path)){
   fos.write(data);
  }
 }
 
 public static void main(String[] args) {
  try {
   new DataSigner().sign("sample.txt");
  } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException | IOException e) {
   e.printStackTrace();
  } 
 }
}
NOTE : You will need a sample.txt file to run this code. As an output two files will be created with names as the original file name (with its extension intact) with extensions .pubkey and .dsa. For example in this case the files will be sample.txt.dsa having signature and sample.txt.pubkey having the public key.
------------------------------------------------------------------------------------------------------------------------
Download Links
------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire

Happy coding and keep in touch to know the verification of digital signature.

0 comments:

Post a Comment

Total Pageviews

Followers


Labels

Popular Posts

free counters