我正在尝试将 Java 哈希函数移植到 Ruby,但最终得到的哈希值与预期不同。下面是相关的java函数(coldfusion):
public string function hashAdministrator(required string pass) {
MessageDigest = createObject('java','java.security.MessageDigest');
for(i=1; i<=5; i++) {
md = MessageDigest.getInstance('SHA-256');
md.update(pass.getBytes('UTF-8'));
pass = enc(md.digest());
}
return pass;
}
private string function enc(strArr) {
//local.strArr = str.getBytes('UTF-8');
local.hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
savecontent variable="local.out" {
for (local.item in strArr) {
writeOutput(hex[bitshrn(bitAnd(240,local.item),4)+1]);
writeOutput(hex[bitAnd(15,local.item)+1]);
}
};
return local.out;
}
下面是我的 ruby 代码:
# encoding: utf-8
require 'digest/sha2'
class RailoPassword
attr_accessor :pass
def admin_password
password = ''
5.times do
md = Digest::SHA2.new
md.update(self.pass)
password = self.enc(md.digest.bytes.to_a)
end
password
end
def enc(strarr)
hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
a = ''
strarr.each do |item|
a << hex[((0xF0 & item) >> 4)]
a << hex[(0x0F & item)]
end
a
end
end
Ruby中的实际实现:
a = RailoPassword.new
a.pass = 'test1234'
puts 'expected: 0be431aeebf55fdc30296e1224fb80b0edbebcddaedb65fcbad1315e906dde65'
puts "actual: #{a.admin_password}"
预期哈希值:0be431aeebf55fdc30296e1224fb80b0edbebcddaedb65fcbad1315e906dde65
返回的哈希值:937e8d5fbb48bd4949536cd65b8d35c426b80d2f830c5c308e2cdec422ae2244
返回的哈希值与我刚刚从 Digest::SHA2 获取十六进制摘要相同:
1.9.3-p547 :335 > Digest::SHA2.hexdigest('test1234')
=> "937e8d5fbb48bd4949536cd65b8d35c426b80d2f830c5c308e2cdec422ae2244"
任何帮助将不胜感激。
最佳答案
这个:
def admin_password
password = ''
5.times do
md = Digest::SHA2.new
md.update(self.pass)
password = self.enc(md.digest.bytes.to_a)
end
password
end
与您的 CFML 逻辑不匹配。应该是这样的(我是 Ruby 新手,所以如果这不是完美的 Ruby,我深表歉意):
def admin_password
# password = '' # get rid of this
5.times do
md = Digest::SHA2.new
md.update(self.pass)
self.pass = self.enc(md.digest.bytes.to_a) # update the correct variable here
end
self.pass # and return the correct variable here
end
完成后,两个代码块返回相同的值,0be431aeebf55fdc30296e1224fb80b0edbebcddaedb65fcbad1315e906dde65
而且,坦率地说,如果您也按照 @owlstead 的建议进行操作并进行了一些调试,那么您会立即明白这一点。所以这也是一个教训:如果您寻求帮助,请注意所提供的帮助。
关于java - 将 ColdFusion Java 哈希函数移植到 Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25221120/