首页 > 解决方案 > 在 JRuby 中使用 Java 的 MessageDigest 类

问题描述

我正在尝试使用 Java 的消息摘要类来计算我的 rails 应用程序内部大量文件的 md5 哈希。我已经用 JRuby 在 ruby​​ 脚本中编写了一些代码,但是对 Files.readAllBytes() 的调用给了我“未定义的方法 `getFileSystem' for #”。这是我用 ruby​​ 编写的方法:

def calculate_md5_java(zip)
  require 'java'
  import java.security.MessageDigest
  import java.nio.file.Files
  import javax.xml.bind.DatatypeConverter
  import java.nio.file.FileSystems

  md = MessageDigest.getInstance("MD5")

  FileUtils.cp(zip, "GODPLEASELETTHISWORK.zip")

  Zip::File.open("GODPLEASELETTHISWORK.zip") do |z|
    z.each do |entry|
      md.update(Files.readAllBytes(entry.get_input_stream))
    end
  end

  digest = md.digest()
  DatatypeConverter.printHexBinary(digest).toLowerCase()
end

我也尝试将我的论点更改为

 md.update(entry.get_input_stream.read.bytes.to_a)

这给了我:

no method 'update' for arguments (org.jruby.RubyArray) on Java::JavaSecurity::MessageDigest::Delegate available overloads: (byte) (java.nio.ByteBuffer) (byte[])

标签: ruby-on-railsrubyjruby

解决方案


哦土豆!这看起来有点复杂……这可以接受吗?

def check_please(file)
  checksums = {}
  Zlib::GzipReader.wrap(file) do |gz|
    Gem::Package::TarReader.new(gz) do |tar|
      tar.each do |entry|
        checksums[entry.full_name] = Digest::MD5.hexdigest(entry.read) if entry.file?
      end
    end
  end
  checksums
end

File.open("foo.tgz", "rb") do |file|
  puts check_please(file)
end

对于它的价值,我正在使用这个版本的 JRuby 和 Java。

jruby 9.1.9.0 (2.3.3) 2017-05-15 28aa830 Java HotSpot(TM) 64-Bit Server VM 25.40-b25 on 1.8.0_40-b27 +jit [darwin-x86_64]

另外,应归功于:http ://weblog.jamisbuck.org/2015/7/23/tar-gz-in-ruby.html


推荐阅读