// create a key pair generator KeyPairGenerator keyInstance = KeyPairGenerator.getInstance("signaturealgorithm"); // init keypair generator SecureRandom random = SecureRandom.getInstance("algorithm", "provider"); keyInstance.initialize(sizeinbits, randomsource); // store key pair KeyPair pair = keyInstance.generateKeyPair(); PrivateKey private = pair.getPrivate(); PublicKey public = pair.getPublic(); |
DigitalSignatureSimpleEncryption.java
package dk.cryptography; import java.security.KeyPairGenerator; import java.security.KeyPair; import java.security.PublicKey; import java.security.PrivateKey; import java.security.Signature; import java.io.FileInputStream; import java.io.File; public class DigitalSignatureSimpleEncryption { public static void main(String[] unused) { try { // Generate a key-pair KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(512); // keysize is 512 bits KeyPair kp = kpg.generateKeyPair(); PublicKey pubk = kp.getPublic(); PrivateKey prvk = kp.getPrivate(); String dataFileName = "DigitalSignatureSimpleEncryption.java"; byte[] signaturebytes = sign(dataFileName, prvk, "SHAwithDSA"); System.out.println("Signature(hex, length="+signaturebytes.length+"):" + byteArray2Hex(signaturebytes)); boolean result = verify(dataFileName, pubk, "SHAwithDSA", signaturebytes); System.out.println("\nSignature Verification Result = " + result); } catch(Exception ex) { ex.printStackTrace(); } } private static byte[] sign(String datafile, PrivateKey prvKey, String sigAlg) throws Exception { Signature sig = Signature.getInstance(sigAlg); sig.initSign(prvKey); File f; FileInputStream fis = new FileInputStream(f=new File(datafile)); byte[] dataBytes = new byte[(int)f.length()]; //small file - read all int nread = fis.read(dataBytes); //hopefully nread==fis.length() fis.close(); sig.update(dataBytes, 0, nread); return sig.sign(); } private static boolean verify(String datafile, PublicKey pubKey, String sigAlg, byte[] sigbytes) throws Exception { Signature sig = Signature.getInstance(sigAlg); sig.initVerify(pubKey); File f; FileInputStream fis = new FileInputStream(f=new File(datafile)); byte[] dataBytes = new byte[(int)f.length()]; //small file - read all int nread = fis.read(dataBytes); //hopefully nread==fis.length() sig.update(dataBytes, 0, nread); return sig.verify(sigbytes); } private static String byteArray2Hex(byte[] byteArray){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteArray.length; i++){ String hex = Integer.toHexString(255 & (int)byteArray[i]); sb.append( ((i%8)==0 ? "\n " : " ") + (hex.length()<2 ? ("0"+hex) : hex)); } return sb.toString(); } } |
SignatureDigest.java
package dk.cryptography; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.util.Arrays; public class SignatureDigest { public static void main(String[] args) { String messageText = "To whom it may concern, ..."; try { MessageDigest theDigest = MessageDigest.getInstance("SHA"); //SHA or MD5 theDigest.update(messageText.getBytes()); //update digest w/message byte[] digestBytes = theDigest.digest(); //compute digest //for demo, generate private/public keys KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(512); // keysize is 512 bits KeyPair kp = kpg.generateKeyPair(); RSAPublicKey pubk = (RSAPublicKey)kp.getPublic(); RSAPrivateKey prvk = (RSAPrivateKey)kp.getPrivate(); //perform RSA private key enctyption of digest with private key BigInteger digestNum = new BigInteger(digestBytes); BigInteger signature = digestNum.modPow( prvk.getPrivateExponent(), prvk.getModulus()); byte[] signaturebytes = signature.toByteArray(); System.out.println("Signature(hex, length="+signaturebytes.length+"):" + byteArray2Hex(signaturebytes)); //Now, signaturebytes = signature for the message text. //Anybody wanting to verify signature needs original text message // + signature bytes + public key //verify signature (normally done in different program) BigInteger sigVerify = new BigInteger(signaturebytes); BigInteger chkDigest = sigVerify.modPow( pubk.getPublicExponent(), pubk.getModulus()); byte[] chkDigestBytes = chkDigest.toByteArray(); //Now, if signature works correctly: digestBytes==chkDigestBytes boolean matched = Arrays.equals(digestBytes,chkDigestBytes); System.out.println( matched? "Signatures match!" : "Signatures doesn't match"); } catch(Exception ex) { ex.printStackTrace(); } } private static String byteArray2Hex(byte[] byteArray){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteArray.length; i++){ String hex = Integer.toHexString(255 & (int)byteArray[i]); sb.append( ((i%8)==0 ? "\n " : " ") + (hex.length()<2 ? ("0"+hex) : hex)); } return sb.toString(); } } |
SignatureKeystoreClient.java
package dk.cryptography; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.Key; import java.security.KeyStore; import java.security.Signature; import java.security.interfaces.RSAPrivateKey; public class SignatureKeystoreClient { public static void main(String[] args) { //args[0]=filename.. if(args.length<1) { System.out.println("Argument syntax: <message filename> "); return; } try { //..use keytool to generate key in keystore.. with properties.. //fx. keytool -genkey -alias keyAlias -keyalg RSA -keypass theKeyPassword String keyStorePwd = "keyPass"; //password to access keystore String keyAlias = "keyAlias"; //alias indentifying key in keystore String testKeyPassword = "theKeyPassword"; //password to acces key //load keystore from keystore file KeyStore keystore = KeyStore.getInstance("JKS"); //creates keystore String keyStoreFileName = System.getProperty("user.home")+File.separator+".keystore"; keystore.load(new FileInputStream(keyStoreFileName), keyStorePwd.toCharArray()); Key testKey = keystore.getKey(keyAlias,testKeyPassword.toCharArray()); RSAPrivateKey prvk = (RSAPrivateKey)testKey; //assume it's an RSA key java.security.cert.Certificate cert = keystore.getCertificate(keyAlias); Signature signer = Signature.getInstance("SHA1withRSA"); signer.initSign(prvk); File f; FileInputStream fis = new FileInputStream(f=new File(args[0])); byte[] dataBytes = new byte[(int)f.length()]; //small file - read all int nread = fis.read(dataBytes); //hopefully nread==fis.length() fis.close(); signer.update(dataBytes); byte[] signatureBytes = signer.sign(); FileOutputStream out = new FileOutputStream(args[0] + ".sig"); //signature to file.. out.write(signatureBytes); out.close(); } catch(Exception ex) { ex.printStackTrace(); } } } |
SignatureKeystoreVerify.java
package dk.cryptography; import java.io.File; import java.io.FileInputStream; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.interfaces.RSAPublicKey; public class SignatureKeystoreVerify { public static void main(String[] args) { //args[0]=filename.. if(args.length!=3) { System.out.println("Argument syntax: <message filename> <.sig file> <cert file>"); return; } try { //..use keytool to generate key in keystore.. with properties.. //fx. keytool -genkey -alias keyAlias -keyalg RSA -keypass theKeyPassword // keytool -export -alias keyAlias -file keyAlias.cert // java SignatureKeystoreVerify message message.sig keyAlias.cert //load certificate using a X.509 certificate factory FileInputStream certFile = new FileInputStream(args[2]); CertificateFactory certX509Fact = CertificateFactory.getInstance("X.509"); Certificate cert = certX509Fact.generateCertificate(certFile); certFile.close(); RSAPublicKey pubk = (RSAPublicKey)cert.getPublicKey(); //assuming RSA key, get pub key Signature signVerifier = Signature.getInstance("SHA1withRSA"); signVerifier.initVerify(pubk); File f=new File(args[0]); //read original message data FileInputStream messageStream = new FileInputStream(f); byte[] messageBytes = new byte[(int)f.length()]; //small file - read all int nread = messageStream.read(messageBytes); //hopefully nread==fis.length() messageStream.close(); signVerifier.update(messageBytes); f = new File(args[1]); //read client generated signature byte[] signatureBytes = new byte[(int)f.length()]; FileInputStream signatureStream = new FileInputStream(f); nread = signatureStream.read(signatureBytes); //hopefully nread==fis.length() signatureStream.close(); System.out.println( signVerifier.verify(signatureBytes) ? "Signatures match!" : "Signatures doesn't match"); } catch(Exception ex) { ex.printStackTrace(); } } } |