duiker101
9/21/2012 - 12:07 AM

a very basic and simple implementation of the Java class org.jasypt.util.password.BasicPasswordEncryptor in ruby.

a very basic and simple implementation of the Java class org.jasypt.util.password.BasicPasswordEncryptor in ruby.

require 'base64'
require 'digest/md5'

def crypt(pas,salt)

	if salt.length == 0
		salt = makeSalt()
	end
	
	md = Digest::MD5.new()
	digest = salt + pas
	
	for i in 0..999
		digest = md5(digest)
		newAr=[]
		digest.scan(/../).each do |d|
			newAr = newAr + [d.hex]
		end
		digest=newAr.pack("C*")
	end
	newAr = salt.unpack("C*") + digest.unpack("C*")
	
	return Base64.encode64(newAr.pack("C*"))
	
end

def makeSalt()
	value = ""; 8.times{value  << (rand(99)).chr}
	return value
end

def compare(plain,enc)
	bytes = Base64.decode64(enc)
	salt = bytes[0..7]
	comp = crypt(plain,salt)
	return comp == enc
end

def md5(mes)
	return Digest::MD5.hexdigest(mes)
end

pas="12345678"
enc = crypt(pas,"")
puts compare(pas,enc)