Professional Documents
Culture Documents
}
catch(Exception e){
System.out.println(e);
}
}
}
Verify Message Digest
• package veryfiymd;
• import java.security.*;
• import java.io.*;
public class VeryfiyMD {
• public static void main(String[] args) {
• try{
• //read the content of the file
• FileInputStream fis= new FileInputStream("C:\\Users\\dell\\Documents\\NetBeansProjects\\CreateMD\\file.txt");
• //read the object stream
• ObjectInputStream ois= new ObjectInputStream(fis);
• String message= (String) ois.readObject();
• message += "Hello";
• byte[] oldDigest= (byte[])(byte[]) ois.readObject();
• MessageDigest md= MessageDigest.getInstance("SHA");
• byte [] data= message.getBytes();
• md.update(data);
• byte[] newDigest= md.digest();
• //we will to compare Two digest
• if(MessageDigest.isEqual(oldDigest , newDigest))
• System.out.println("Data was not corrected ");
• else
• System.out.println("Data was corrected");
• }
• catch(Exception e ){
• System.out.println(e);
• }}}
Secure Message Digests
A secure message digest is called a Message Authentication Code (MAC). A MAC
has the property that it cannot be created solely from the input data; it requires a
secret key that is shared by the sender and receiver.
• mac.init(kg.generateKey());
• String data = "I had already learnt how to create message digest";
•
• byte buf[] = data.getBytes( );
• mac.update(buf);
• oos.writeObject(data);
• oos.writeObject(mac.doFinal( ));
• } catch (Exception e) {
• System.out.println(e);
• }
• }
• }
How to calculate Own Mac
• package calculatemac;
• import java.security.*;
• import javax.crypto.*;
• import java.io.*;
• import javax.xml.bind.DatatypeConverter;
• public class CalculateMaC {
• import javax.crypto.KeyGenerator;
• import javax.crypto.Mac;
• //Creating/Generating a key
• Key key = keyGen.generateKey();
• System.out.println("Mac result:");
• System.out.println(new String(macResult));
• }
• }
Message Digest Streams
The interface to the message digest class requires that you supply the data for
the digest as a series of single bytes or byte arrays. As we mentioned earlier, this
is not always the most convenient way to process data, which may be coming
from a file or other input stream. This brings us to the message digest stream
classes. These classes implement the standard input and output filter stream
semantics of Java streams so that data can be written to a digest stream that will
calculate the digest as the data itself is written (or the reverse operation for
reading data).
The DigestOutputStream Class
• The symmetric operation to the digest output stream is the DigestInputStream class
(java.security.DigestInputStream):
• public class DigestInputStream extends FilterInputStream
• import java.security.*;
• import java.io.*;
•
•
• }
• catch (Exception e){
• System.out.println(e);
• }
• }
• }
Thank you