Skip to content

Instantly share code, notes, and snippets.

@huberflores
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huberflores/29b7e9be36a1dc0bfb81 to your computer and use it in GitHub Desktop.
Save huberflores/29b7e9be36a1dc0bfb81 to your computer and use it in GitHub Desktop.
Checksum of a Java Object
package ee.ut.cs.mc.example;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
/*
* author Huber Flores
*/
public class CheckSumTest implements Serializable{
public void bubbleSort(int randValue, int sizeArray) throws NoSuchAlgorithmException, IOException{
CheckObject l = new CheckObject();
BigInteger sum = checksum(l);
System.out.println("Size of the object: " + sizeOf(l));
System.out.println("Checking integrity of the object, checksum= " + sum);
l.bubbleFunction(randValue, sizeArray);
}
public static void main(String[] args) {
CheckSumTest test = new CheckSumTest();
try {
test.bubbleSort(1000000, 9999);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done");
}
class CheckObject implements Serializable{
public int[] bubbleFunction(int randValue, int sizeArray){
int[] num = new int[sizeArray];
Random r = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(randValue);
}
int j;
boolean flag = true;
int temp;
while (flag) {
flag = false;
for (j = 0; j < num.length - 1; j++) {
if (num[j] < num[j + 1])
{
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true;
}
}
}
return num;
}
}
/*
* target object to apply checksum should be Serializable
*/
private BigInteger checksum(Object obj) throws IOException, NoSuchAlgorithmException {
if (obj == null) {
return BigInteger.ZERO;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
MessageDigest m = MessageDigest.getInstance("SHA1");
m.update(bos.toByteArray());
return new BigInteger(1, m.digest());
}
/*
* size of the object.
* some code replicated to be removed.
*/
public double sizeOf(Object obj) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
return bos.toByteArray().length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment