Greetings!

Currently, I'm hitting a road block on a task that I need to perform. My goal is to hash my source code and check if the code has been changed during runtime. if it has been modified, it shouldn't be allowed to run.

My question is how do i achieve this? I've been reading around a lot and am currently I'm still looking for solutions. However, I cannot find the solution I need. Can someone point me in the right direction by telling me how to hash my source code?

Thanks for your time :D

These functions are called one-way hashes (as opposed to encryption-decryption which are often confused with hashing). There are multiple solutions to your problem. If you are reading the entire file in-memory as a single string, the simplest solution would be to just call hashCode method on that string. This is a pretty rudimentary solution which might raise some eyebrows though.

If you need real one-way hash algorithms, there are many out there, ranging from simple MD5 to SHA and others. MessageDigest class is your friend. A sample code which I found in the wild from here:

import java.security.MessageDigest;

reader = null; // buffered/file reader
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
while ((line = reader.readLine()) != null) {  
  messageDigest.update(line.getBytes());
}
final String encryptedString = new String(messageDigest.digest());

BTW, what exactly are you trying to hash here? The source code in plain text or the .class files?

Edited 4 Years Ago by ~s.o.s~

I am trying to make sure that the code I am running is unedited by someone else (original code). so, should I hash the plain text code or the .class files? what is a better solution?

Thank you very much :D

Thanks for the inputs, However I am really curious about hashing .class files. can someone give me some direction regarding this?

Thanks!

Hashing always happens at the binary level i.e. with bytes and not text. Hashing a .class file is in no way different that hashing a .avi file. If you'll notice in my original snippet, I hash the underlying bytes of the line read and not the line itself.

That being said, what kind of directions do you need? Hashing a .class file is as simple as running it through the code I posted but instead using a FileInputStream (since we want to read raw bytes) though I really see no use for this sort of stuff. If you need protection, use the JAR signer mentioned by James. Or a very simple utility like Proguard which provides the first line of defense by obfuscating the jar file.

Thanks Guys! I'll try it right away and report back with what happens :D
Thank you again!

This article has been dead for over six months. Start a new discussion instead.