EVP_BytesToKeyをRubyで実装する

訳あってEVP_BytesToKeyをRubyで実装したので、ログを残しておく。

require 'digest/md5'

def bytes_to_key0(md_buf, salt, data, count)
  src = md_buf.empty? ? '' : md_buf
  src << data
  src << salt if salt

  dst = Digest::MD5.digest(src)

  (count - 1).times do
    dst = Digest::MD5.digest(dst)
  end

  return dst
end

def bytes_to_key(salt, data, count)
  key = ''
  nkey = 32
  iv = ''
  niv = 16
  md_buf = ''

  loop do
    md_buf = bytes_to_key0(md_buf, salt, data, count)

    if nkey.nonzero?
      key << md_buf
      nkey -= md_buf.length
    elsif niv.nonzero?
      iv << md_buf
      niv -= md_buf.length
    end

    if nkey.zero? and niv.zero?
      break
    end
  end

  return [key, iv]
end