Project/Java Network Programming
Digest Streams
Triton
2010. 12. 27. 08:02
The java.util.security package contains two filter streams that can calculate a message digest for a stream. They are DigestInputStream and DigestOutputStream. A message digest, represented in Java by the java.util.security.MessageDigest class, is a strong hash code for the stream. Message digests can be used for digital signatures and for detecting data that has been corrupted in transit across the network.
In practice, the use of message digests in digital signatures is more important. Mere data corruption can be detected with much simpler, less computationally expensive algorithms. However, the digest filter streams are so easy to use that at times it may be worth paying the computational price for the corresponding increase in programmer productivity.
MessageDigest sha = MessageDigest.getInstance("SHA"); // Construct a MessageDigest object that uses a particular algorighm, such as the Secure Hash Algorith (SHA).
DigestOutputStream dout = new DigestOutputStream(out, sha); //Pass both the MessageDigest object and the stream you want to digest to the DigestOutputStream constructor. This chains the digest stream to the underlying output stream.
byte[] buffer = new byte[128];
while (true){
int bytesRead = in.read(buffer);
if (bytesRead < 0 ) break;
dout.write(buffer, 0, bytesRead);
}
dout.flush();
dout.close();
byte[]result = dout.getMessageDigest().digest(); // Invoke the getMessageDigest() method to retrieve the MessageDigest object. Finally you invoke the digest() method on the MessageDigest object to finish calculating the actual digest.
Calculating the digest of an input stream you read is equally simple. It still isn't quite as transparent as some of the other filter streams because you do need to be at least marginally conversant with the methods of the MessageDigest class. Nonetheless, it's still far easier than writing your own secure hash function and manually feeding it each byte you write.