security
Signing a Java Object example
With this example we are going to demonstrate how to sign a Java Object. In particular, we will use the Digital Signature Algorithm (DSA) to create a 1024-bit key pair and then sign a Serializable Object, using the key pair Signature. In short, to sign an Object in Java you should:
- Create a KeyPairGenerator for the DSA algorithm and initialize it with a 1024-bit key size.
- Generate the KeyPair, with the
genKeyPair()
API method of the KeyPairGenerator. - Get the PrivateKey component and the PublicKey component of the key pair, using the
getPrivate()
andgetPublic()
API methods of the KeyPair. - Create a new String Object.
- Create a new Signature Object for the specified algorithm, using the
getInstance(String algorithm)
API method. - Create a new SignedObject, using the initial Object to be signed, the PrivateKey and the Signature.
- Verify the signed Object. Use the
getInstance(String algorithm)
of the Signature, using the public key’s algorithm. Then invoke theverify(PublicKey verificationKey, Signature verificationEngine)
API method of the SignedObject. - Retrieve the Object, using the
getObject()
API method of the SignedObject.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; 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; import java.security.SignedObject; public class ObjectSigningExample { public static void main(String[] args) { try { // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.genKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // We can sign Serializable objects only String unsignedObject = new String("A Test Object"); Signature signature = Signature.getInstance(privateKey.getAlgorithm()); SignedObject signedObject = new SignedObject(unsignedObject, privateKey, signature); // Verify the signed object Signature sig = Signature.getInstance(publicKey.getAlgorithm()); boolean verified = signedObject.verify(publicKey, sig); System.out.println("Is signed Object verified ? " + verified); // Retrieve the object unsignedObject = (String) signedObject.getObject(); System.out.println("Unsigned Object : " + unsignedObject); } catch (SignatureException e) { } catch (InvalidKeyException e) { } catch (NoSuchAlgorithmException e) { } catch (ClassNotFoundException e) { } catch (IOException e) { } } }
Output:
Is signed Object verified ? true
Unsigned Object : A Test Object
This was an example of how to sign a Java Object.