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"

Wednesday, January 25, 2012

File/Directory Traverse

//helpful file properties: http://groovy.codehaus.org/JN2015-Files
 
import groovy.io.FileType

def walkFiles = {filepath, filterOnly, onFind, onEnd = {} ->
    try {
        File f = new File(filepath)
        f.traverse([type:FileType.FILES, nameFilter:filterOnly], onFind)
        onEnd()
    }
    catch (FileNotFoundException e) { println "ERROR: invalid file/directory"}
}

def pf = { file ->
    if (file.name.contains("a"))
        println file.name
}

walkFiles("C:\\123", ~/.*\.ico/, pf)

Tuesday, January 24, 2012

FastMap and IdentityHashMap

@Grapes(
    @Grab(group='javolution', module='javolution', version='5.5.1')
)
import javolution.util.FastMap // also FastSet, FastList

Map labels1 = new FastMap().shared()
Map labels2 = [:] as IdentityHashMap // unsorted

100.times { i ->
    labels1[String.valueOf(i)] = i*i
    labels2[String.valueOf(i)] = i*i
}

assert labels1 == labels2.sort()

see http://javolution.org/target/site/apidocs/javolution/util/FastMap.html

Fibonacci

/**
 * Fibonacci series:
 * the sum of two elements defines the next
 */

int LIMIT = 1000

(a,b) = [0,1]
while (b < LIMIT) {
    print "$b "
    (a,b) = [b, a+b]
}

(source)