You are on page 1of 22

Message Digests

Done By :Miaad Saeed AL-Muhaijeri


ID: 2016493017
Content
• Definition of Message Digest :
• Using the Message Digest Class
• Method of MAC Class
• How to Create MAC Class
• Message Digest Streams
• The DigestOutputStream Class
• How to create Message Digest using DigestOutputStream
• How to verify Message Digest using DigestOutputStream
Definition of Message Digest :
A message digest is a fixed size numeric representation of the contents of a
message, computed by a hash function. A message digest can be encrypted.
Message digests are designed to protect the integrity of a piece of data or
media to detect changes and alterations to any part of a message.

Why message digest is used?


Message Digest is used to ensure the integrity of a message transmitted over
an insecure channel. where The message is passed through a Cryptographic
hash function. and then This function creates a compressed image of the
message called Digest.

How is Message Digest generated?


Message digest algorithms rely on cryptographic hash functions to generate a
unique value that is computed from data and a unique symmetric key. A
cryptographic hash function inputs data of arbitrary length and produces a
unique value of a fixed length.
Using the Message Digest Class
Message digests are implemented using the MessageDigest class
(java.security.MessageDigest)

public abstract class MessageDigest extends MessageDigestSpi


Implement operations to create and verify a message digest.

the message digest are obtained through one of these methods:


• public static MessageDigest getInstance(String algorithm)
• public static MessageDigest getInstance(String algorithm, String provider)
Once a message digest object has been obtained, the developer can operate on that
object with these methods:

• public void update(byte input)


• public void update(byte[] input)
• public void update(byte[] input, Int offset, Int length)
• public int digest(byte[] output, int offset, int len)
• public static boolean isEqual(byte digestA[], byte digestB[])
• public void reset( )
• public final String getAlgorithm( )
• public String toString( )

• public Object clone( ) throws CloneNotSupportedException


• public final int getDigestLength( )
package createmd; Create Message Digest
import java.security.*;
import java.io.*;

public class CreateMD {

public static void main(String[] args) {


try{
MessageDigest md = MessageDigest.getInstance("SHA");
String message ="Network and Security Programming";
byte[] data = message.getBytes();
md.update(data);
byte[] mDigest= md.digest();
FileOutputStream fos = new FileOutputStream("file.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(message);
oos.writeObject(mDigest);

}
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.
 

The Mac Class


The Mac class (javax.crypto.Mac) is part of the Java Cryptography Extension
because it involves a cryptographic operation: a secret key is used to calculate the
message digest. This mean that in order to use the Mac class, both sender and
receiver must agree upon which secret key to use.
Method of MAC Class
• public byte[] doFinal( )

• public byte[] doFinal(byte[] input)

• public void doFinal(byte[] output, int offset)

• public void init(SecretKey sk)

• public void init(SecretKey sk, AlgorithmParameterSpec aps)


How to Create MAC Class
• import java.io.*;
• import java.security.*;
• import javax.crypto.*;
• public class SendMac {
• public static void main(String args[]) {
• try {
• FileOutputStream fos = new FileOutputStream("test.txt");
• Mac mac = Mac.getInstance("HmacSHA1");
• //Step 1: Create a KeyGenerator object
• KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
• //Step 2: Initialize the KeyGenerator
• kg.init(512);

• //Step 3: Initialize the Mac object

• mac.init(kg.generateKey());

• ObjectOutputStream oos = new ObjectOutputStream(fos);

• 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 {

• public static void main(String[] args) {


• try{

• Mac mac= Mac.getInstance("HMacSHA1");
• KeyGenerator kg = KeyGenerator.getInstance("HMacSHA1");
• SecretKey sk = kg.generateKey();
• mac.init(sk);
• mac.update("Security programmimg".getBytes());
• byte[] macCode=mac.doFinal();
• System.out.print(DatatypeConverter.printHexBinary(macCode));



• } catch (Exception e) {
• System.out.println(e);
• }
• }

•}
Example

The following example demonstrates the


generation of Message Authentication Code
(MAC) using JCA. Here, we take a simple
message "Hi how are you" and, generate a Mac
for that message
• import java.security.Key;
• import java.security.SecureRandom;

• import javax.crypto.KeyGenerator;
• import javax.crypto.Mac;

• public class SendMac {


• public static void main(String args[]) throws Exception{
• //Creating a KeyGenerator object
• KeyGenerator keyGen = KeyGenerator.getInstance("DES");

• //Creating a SecureRandom object


• SecureRandom secRandom = new SecureRandom();

• //Initializing the KeyGenerator


• keyGen.init(secRandom);

• //Creating/Generating a key
• Key key = keyGen.generateKey();

• //Creating a Mac object


• Mac mac = Mac.getInstance("HmacSHA256");

• //Initializing the Mac object


• mac.init(key);

• //Computing the Mac


• String msg = new String("Hi how are you");
• byte[] bytes = msg.getBytes();
• byte[] macResult = mac.doFinal(bytes);

• 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 first of these classes we'll examine is the DigestOutputStream class


(java.security.DigestOutputStream). This class allows us to write data to a
particular output stream and calculate the message digest of that data
transparently as the data passes through the stream:

• public class DigestOutputStream extends FilterOutputStream


• public DigestOutputStream(OutputStream os, MessageDigest md)
• public MessageDigest getMessageDigest( )
• public void setMessageDigest(MessageDigest md)
• public void write(int b)
• public void write(byte b[], int off, int len)
• public void on(boolean on)
The DigestOutputStream Class

• The symmetric operation to the digest output stream is the DigestInputStream class

(java.security.DigestInputStream):
• public class DigestInputStream extends FilterInputStream

• public DigestInputStream(InputStream is, MessageDigest md)


• public MessageDigest getMessageDigest( )*
• public void setMessageDigest(MessageDigest md)
• public void read(int b)
• public void read(byte b[], int off, int len)
• public void on(boolean on)
How to create Message Digest using
DigestOutputStream
• package createdigeststream;

• import java.security.*;
• import java.io.*;

• public class CreateDigestStream {

• public static void main(String[] args) {



• try{
• // we need to get message digest
• MessageDigest md= MessageDigest.getInstance("SHA");
• //we have to attach output stream by using digest
• FileOutputStream fos = new FileOutputStream("test.txt");
• //we have to get output stream
• DigestOutputStream dos= new DigestOutputStream(fos, md);

• ObjectOutputStream oos = new ObjectOutputStream(dos);
• String message= "Network and Security Programming";
• oos.writeObject(message);
• //call the method
• dos.on(false);
• oos.writeObject(md.digest());

• }
• catch(Exception e){
• System.out.println(e);
• }
• }
• }
How to verify Message Digest using
DigestOutputStream
• package verifymessagedigeststream;
• import java.security.*;
• import java.io.*;
• public class VerifyMessageDigestStream {
public static void main(String[] args) {
• try{
• FileInputStream fis = new FileInputStream("C:\\Users\\dell\\Documents\\NetBeansProjects\\SendMac\\test.txt");
• //i want to get message digest stream
• MessageDigest md = MessageDigest.getInstance("SHA");
• DigestInputStream dis= new DigestInputStream(fis, md);
• ObjectInputStream ois = new ObjectInputStream(dis);

• String message = (String) ois.readObject();
• dis.on(false);
• byte[] oldDigest = (byte[]) ois.readObject();
• if( MessageDigest.isEqual(oldDigest, md.digest()));
• System.out.println("Data was not corrected");
• else
• System.out.println("Data was corrected");



• }
• catch (Exception e){
• System.out.println(e);
• }
• }
• }
Thank you

You might also like