Signing a Java Object

A signed object makes a copy of a serializable object and signs it with a private key. Since the signed object makes a copy of the original object, any further modifications to the original object do not affect the signed object.
// Create a public and private key PublicKey publicKey = null; PrivateKey privateKey = null; try { // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024); KeyPair keypair = keyGen.genKeyPair(); privateKey = keypair.getPrivate(); publicKey = keypair.getPublic(); } catch (NoSuchAlgorithmException e) { } // Create the signed object SignedObject so = null; try { Serializable o = new MyClass(); Signature sig = Signature.getInstance(privateKey.getAlgorithm()); so = new SignedObject(o, privateKey, sig); } catch (NoSuchAlgorithmException e) { } catch (SignatureException e) { } catch (InvalidKeyException e) { } catch (IOException e) { } // Verify the signed object try { Signature sig = Signature.getInstance(publicKey.getAlgorithm()); // Verify the signed object boolean b = so.verify(publicKey, sig); // Retrieve the object MyClass o = (MyClass)so.getObject(); } catch (SignatureException e) { } catch (InvalidKeyException e) { } catch (NoSuchAlgorithmException e) { } catch (ClassNotFoundException e) { } catch (IOException e) { } public class MyClass implements Serializable { String s = "my string"; int i = 123; }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.