![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e205. Signing a Java ObjectA 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; }
e203. Creating a Signature e204. Verifying a Signature
© 2002 Addison-Wesley. |