import java.io.*;
import java.security.*;
import sun.misc.*;


public class UseDigSign{
public static void main(String[] args) {
//Defining the algorithm used for creating the signature
String algo = "DSA";
//Generating a key pair
KeyPair kp = generateKeyPair(algo);
// Generating a digital signature for the original message string that
// is a command-line argument while executing the program
byte[] sig = createSign(args[0], algo, kp);
//Verifying the digital signature
verifySign(args[0], algo, sig, kp.getPublic());
}

static KeyPair generateKeyPair(String algo){
try{
KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
System.out.println("Key pair is generated");
KeyPair kp = kpg.genKeyPair();
return kp;
}catch(Exception e){
System.out.println(e);
}
return null;
}

static byte[] createSign(String s, String algo, KeyPair kp){
try{
Signature mySign = Signature.getInstance(algo);
PrivateKey prik = kp.getPrivate();
PublicKey pubk = kp.getPublic();
mySign.initSign(prik);
System.out.println("\nSignature is generated");
mySign.update(s.getBytes());
byte[] b = mySign.sign();
System.out.println("\nOriginal Message: "+s);
System.out.println("\nPrivate key: "+
convertBase64(prik.getEncoded()));
System.out.println("\nPublic key : "+
convertBase64(pubk.getEncoded()));
System.out.println("\nSignature : "+convertBase64(b));
return b;
}catch(Exception e){
System.out.println(e);
}
return null;
}



static void verifySign(String s, String algo, byte[] sig, PublicKey pubk){
try{
Signature mySign = Signature.getInstance(algo);
System.out.println("\nSignature is being verified");
mySign.initVerify(pubk);

mySign.update(s.getBytes());
if(mySign.verify(sig))
System.out.println("\nSignature is verified sucessfully");
else
System.out.println("\nSignature not verified");
}catch(Exception e){
System.out.println(e);
}
}
static String convertBase64(byte[] data){
BASE64Encoder encoder = new BASE64Encoder();
String encoded = encoder.encodeBuffer(data);
return encoded;
}
}
