Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 41 total

Hash Referencing Hack for Ruby

Hash Hacks:
1. Method Missing hack to allow easy referencing.
I can never remember whether the Hash i am playing with has symbols for keys or
strings. I also dont like typing the brackets (not all text editors have the
cool "close brace" feature). That's why i came up with this method missing hack.
Instead of explaining what it does, I'll just show you.

Example:
hsh = {"project"=>
{ "prototype_url"=>nil,
"designer_id"=>2,
"finished_at"=>nil, "phone_number"=>"512225555",
"website"=>"http://www.ggg.com",
"first_name"=>"test",
}
}
hsh.project
#=> {"prototype_url"=>nil, "designer_id"=>2, "finished_at"=>nil, "phone_number"=>"512225555", "website"=>"http://www.ggg.com", "first_name"=>"test"}

hsh.project.prototype_url #=> nil
hsh.project.designer_id #=> 2
hsh.project.first_name #=> test

class Hash    		
  def method_missing(method_id, *args, &block)
    method_name = method_id.to_s
    check = self.stringify_keys
    if check.keys.include?(method_name)
      check[method_name]
    else
      super
    end
  end
end




I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox

Peace

--jake

Java - String2MD5

public static byte[] getKeyedDigest(byte[] buffer, byte[] key) {
   try {
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(buffer);
      return md5.digest(key);
   } catch (NoSuchAlgorithmException nsae) {}

   return null;
}

Find every path and it's value in a Hash

Extends Hash class with each_path method.

This method takes a block as argument which is called each time a the recursivly searched Hash returns a key that does not point to another Hash.

Example:
paths = []
complex_hash = Hash[
  :a => { :aa => '1', :ab => '2' },
  :b => { :ba => '3', :bb => '4' }
]
complex_hash.each_path { |path, value| paths << [ path, value ] }
paths.inspect
# => "[[\"b/ba/\", \"3\"], [\"b/bb/\", \"4\"], [\"a/aa/\", \"1\"], [\"a/ab/\", \"2\"]]"


class Hash
  def each_path
    raise ArgumentError unless block_given?
    self.class.each_path( self ) { |path, object| yield path, object }
  end

  protected
  def self.each_path( object, path = '', &block )
    if object.is_a?( Hash ) then object.each do |key, value|
        self.each_path value, "#{ path }#{ key }/", &block
      end
    else yield path, object
    end
  end
end

BSD.py

// BSD Unix TCP/IP Checksum

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="21 Dec 2005 - 3 May 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.3"
__URL__="http://snippets.dzone.com/posts/show/3542"

import HashFunction

class BSD(HashFunction.HashFunction):
	BLOCK_SIZE=1
	DIGEST_SIZE=2

	INIT=0x00
	SUM_REQ="Sum >= 0"

	TEST_DATA="abc"
	TEST_HASH=0x40ac

	def __init__(self, sum=0x00):
		self.sum=sum

	def sumValid(self, sum):
		return sum>=0

	def rotate(self, b):
		if (b&1)!=0:
			return (b>>1)+0x8000

		return b>>1

	def _update(self, b):
		self.sum=(self.rotate(self.sum)+b)&0xffff

	def digest(self):
		return self.sum

	def format(self, data):
		return "%05d" % (data)

	def unformat(self, hash):
		return int(hash)

if __name__=="__main__":
	HashFunction.main(BSD)

recursively merge Hash.

recursively merge Hash.

class Hash
    def recursive_merge(h)
        self.merge!(h) {|key, _old, _new| if _old.class == Hash then _old.recursive_merge(_new) else _new end  } 
    end
end

Mapping hash values

class Hash
  def hmap
    each_pair do |key, value|
      store key, yield(value)
    end
  end
end

Convert Array to Hash

Probably nothing new in this but here is one way of converting an Array to a Hash:

require "enumerator"

class Array
  def to_h
    Hash[*enum_with_index.to_a.flatten]
  end
end

%w{a b c d}.to_h  # =>  {"a"=>0, "b"=>1, "c"=>2, "d"=>3}


Ruby HMAC verifier

// Ruby script to verify the HMAC of a file or string.

#!/usr/bin/env ruby
#
#  Created by Jon (exabrial+hmacruby@gmail.com) on 2006-11-04.
#  Copyright (c) 2006. All rights reserved.
#  Released under MIT License

require 'openssl'
require "getopt/std"
include OpenSSL
include Digest

def printhelp
  help=<<end
Purpose: Provides HMAC-SHA1 of a file or string. Text passwords are SHA1 hashed.
Usage: hmac.rb ["string to digest"] [-f (pathtofile)] [-k (pathtokeyfile)]
Options:
  -f (pathtofile) digests a file instead of a string
  -k (pathtokeyfile) does not prompt for key and uses the specified file as a key instead.
end
  puts help
  exit
end

if ARGV.size < 1
  printhelp
elsif ARGV.size==1
  @plaintext=ARGV.shift
else
  begin
    opt = Getopt::Std.getopts("f:k:")
  rescue Getopt::StdError
    printhelp
  end
  
  if opt["f"]
    @plaintext=File.read(opt["f"])
  end
  if opt["k"]
    @key=File.read(opt["k"])
  end
  
  printhelp if (!@plaintext&&!@key)
end

def getkey
  return @key if @key
  print "Please type your key then push enter:"
  return SHA1.new(gets()).to_s
end

def main
  hmacd=HMAC.new(getkey(), SHA1.new)
  hmacd.update(@plaintext)
  puts hmacd.to_s
end

main

Adler32.py

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="21 Dec 2005 - 17 Jul 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.3"
__URL__="http://snippets.dzone.com/posts/show/2889"

import HashFunction

class Adler32(HashFunction.HashFunction):
	BLOCK_SIZE=1
	DIGEST_SIZE=2

	INIT=0x0001
	SUM_REQ="Sum >= 0"

	BASE=65521

	TEST_DATA="abc"
	TEST_HASH=0x24d0127

	def __init__(self, sum=0x0001):
		self.sum=sum

	def sumValid(self, sum):
		return sum>=0

	def _update(self, b):
		s1=self.sum&0xffff
		s2=(self.sum>>16)&0xffff

		s1=(s1+(b&0xff))%self.BASE
		s2=(s1+s2)%self.BASE

		self.sum=(s2<<16)|s1

	def digest(self):
		return self.sum

	def formatDigest(self):
		return "%02x" % (self.digest())

	def unformatDigest(self, hash):
		return int(hash, 16)

if __name__=="__main__":
	HashFunction.main(Adler32, "Adler32.py")

HashFunction.py

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="21 Dec 2005 - 17 Jul 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.3"
__URL__="http://snippets.dzone.com/posts/show/2888"

import sys
from getopt import getopt

TEST_MODE="TEST"
HASH_MODE="HASH"

class HashFunction:
	"""Base class for hash functions"""

	# bytes
	BLOCK_SIZE=1
	DIGEST_SIZE=1

	INIT=0x00
	SUM_REQ="Sum >= 0"

	TEST_DATA="abc"
	TEST_HASH=0x26

	def __init__(self, sum=0x00):
		"""Sets the context to some initial sum"""
		self.sum=sum&0xff

	def sumValid(self, sum):
		return sum>=0

	def _update(self, b):
		"""Data is an array of bytes"""

		self.sum=(self.sum+b)&0xff

	def update(self, data):
		"""Helper for _update(). Data is a string."""

		for byte in data:
			self._update(ord(byte))

	def digest(self):
		"""Returns an integer or long integer"""

		return self.sum

	def formatDigest(self):
		"""Returns a formatted string, different for each algorithm"""

		return "%02x" % (self.digest())

	def unformatDigest(self, hash):
		"""Converts formatted hash into integer"""

		return int(hash, 16)

	def reset(self):
		"""Reinitializes the hash"""

		self.__init__()

	def test(self):
		self.reset()
		self.update(self.TEST_DATA)
		hash=self.digest()
		formattedHash=self.formatDigest()
		unformattedHash=self.unformatDigest(formattedHash)

		if unformattedHash==self.TEST_HASH:
			return "OK"

		return [self.TEST_DATA, hash, formattedHash, unformattedHash, self.TEST_HASH]

def usage(script=sys.argv[0]):
	print "Usage: %s [options] <file1 file2 file3 ... >" % (script)
	print "\n-s --sum <sum>"
	print "-t --test engine"
	print "-h --help usage"

	sys.exit()

def main(hasher=HashFunction, script="HashFunction.py"):
	global TEST_MODE
	global HASH_MODE

	systemArgs=sys.argv[1:] # ignore program name

	mode=HASH_MODE
	sum=hasher.INIT

	optlist, args=[], []
	try:
		optlist, args=getopt(systemArgs, "s:th", ["sum=", "test", "help"])
	except Exception, e:
		usage(script)

	if len(optlist)<1 and len(args)<1:
		usage(script)

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage(script)
		elif option=="-t" or option=="--test":
			mode=TEST_MODE
		elif option=="-s" or option=="--sum":
			try:
				sum=hasher.unformatDigest(value)
				if not hasher.sumValid(sum):
					raise Exception
			except Exception, e:
				raise "Requires: %s" % (hasher.SUM_REQ)

	hasher=hasher()

	if mode==TEST_MODE:
		print hasher.test()
	elif mode==HASH_MODE:
		for file in args:
			f=None
			try:
				f=open(file, "rb")
			except Exception, e:
				print "Could not open %s" % (file)
			else:
				hasher.reset()
				for line in f:
					hasher.update(line)
				f.close()

				print hasher.formatDigest()

if __name__=="__main__":
	main(HashFunction, "HashFunction.py")
« Newer Snippets
Older Snippets »
Showing 11-20 of 41 total