Thursday, January 26, 2012

Simple SHA Digest/Hash

import java.security.*

makeDigest = {String msg, int loops = 1, long t1 = (new Date()).getTime(), double q1 = Math.random() ->
    MessageDigest md = MessageDigest.getInstance("SHA")
    (Math.abs(loops) ?: 1).times {
        byte[] randm = {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream()
            DataOutputStream dataOut = new DataOutputStream(byteOut)
            dataOut.writeLong(t1)
            dataOut.writeDouble(q1)
            return byteOut.toByteArray()
        }()
        md.update(randm)
        md.update(msg.getBytes())
    }
    return md.digest()
}

String user = "admin"
String password = "s3cr3t"

int loops = 1
byte[] hash1 = makeDigest(user+password, loops, 0, 0) // not randomized
byte[] hash2 = makeDigest(user+password) // randomized
assert hash1 != hash2
println "$hash1\n$hash2"

No comments:

Post a Comment