Class: Ccrypto::Java::PBKDF2Engine

Inherits:
Object
  • Object
show all
Includes:
DataConversion, TR::CondUtils
Defined in:
lib/ccrypto/java/engines/pbkdf2_engine.rb

Instance Method Summary collapse

Methods included from DataConversion

#from_b64, #from_hex, included, #to_b64, #to_b64_mime, #to_bin, #to_hex, #to_java_bytes, #to_str

Constructor Details

#initialize(*args, &block) ⇒ PBKDF2Engine

Returns a new instance of PBKDF2Engine.

Raises:

  • (KDFEngineException)


11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ccrypto/java/engines/pbkdf2_engine.rb', line 11

def initialize(*args, &block)
  @config = args.first

  raise KDFEngineException, "KDF config is expected. Given #{@config}" if not @config.is_a?(Ccrypto::PBKDF2Config)
  raise KDFEngineException, "Output bit length (outBitLength) value is not given or not a positive value (#{@config.outBitLength})" if is_empty?(@config.outBitLength) or @config.outBitLength <= 0

  raise KDFEngineException, "Digest algo is not supported. Given #{@config.digest}, supported: #{supported_digest.join(", ")}" if not @config.digest.nil? and not is_digest_supported?(@config.digest)

  @config.digest = default_digest if is_empty?(@config.digest)

  @config.salt = SecureRandom.random_bytes(16) if is_empty?(@config.salt)
end

Instance Method Details

#default_digestObject



62
63
64
# File 'lib/ccrypto/java/engines/pbkdf2_engine.rb', line 62

def default_digest
  :sha256
end

#derive(input, output = :binary) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ccrypto/java/engines/pbkdf2_engine.rb', line 24

def derive(input, output = :binary)
  
  begin

    case input
    when String
      if input.ascii_only?
        pass = input.to_java.toCharArray
      else
        pass = to_hex(to_java_bytes(input)).to_java.toCharArray
      end
    when ::Java::byte[]
      pass = to_hex(to_java_bytes(input)).to_java.toCharArray
    else
      raise KDFEngineException, "Input type '#{input.class}' cannot convert to char array"
    end

    skf = javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHMAC#{@config.digest.upcase}",JCEProvider::DEFProv)
    keySpec = javax.crypto.spec.PBEKeySpec.new(pass.to_java, to_java_bytes(@config.salt), @config.iter, @config.outBitLength)

    sk = skf.generateSecret(keySpec)
    out = sk.encoded

    case output
    when :b64
      to_b64(out)
    when :hex
      to_hex(out)
    else
      out
    end

  rescue Exception => ex
    raise KDFEngineException, ex
  end
  
end