Class: Ccrypto::Java::HKDFEngine

Inherits:
Object
  • Object
show all
Includes:
DataConversion, TR::CondUtils
Defined in:
lib/ccrypto/java/engines/hkdf_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) ⇒ HKDFEngine

Returns a new instance of HKDFEngine.

Raises:

  • (KDFEngineException)


10
11
12
13
14
15
16
17
18
# File 'lib/ccrypto/java/engines/hkdf_engine.rb', line 10

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

  raise KDFEngineException, "KDF config is expected. Given #{@config}" if not @config.is_a?(Ccrypto::KDFConfig)
  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


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

Instance Method Details

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



20
21
22
23
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
61
62
63
64
65
66
67
68
# File 'lib/ccrypto/java/engines/hkdf_engine.rb', line 20

def derive(input, output = :binary)
  begin

    case @config.digest
    when :sha1
      dig = org.bouncycastle.crypto.digests.SHA1Digest.new
    when :sha224
      dig = org.bouncycastle.crypto.digests.SHA224Digest.new
    when :sha256
      dig = org.bouncycastle.crypto.digests.SHA256Digest.new
    when :sha384
      dig = org.bouncycastle.crypto.digests.SHA384Digest.new
    when :sha512
      dig = org.bouncycastle.crypto.digests.SHA512Digest.new
    when :sha3_224
      dig = org.bouncycastle.crypto.digests.SHA3Digest.new(224)
    when :sha3_256
      dig = org.bouncycastle.crypto.digests.SHA3Digest.new(256)
    when :sha3_384
      dig = org.bouncycastle.crypto.digests.SHA3Digest.new(384)
    when :sha3_512
      dig = org.bouncycastle.crypto.digests.SHA3Digest.new(512)
    else
      raise KDFEngineException, "Digest #{@config.digest} not supported"
    end

    @config.info = "" if @config.info.nil?

    hkdf = org.bouncycastle.crypto.generators.HKDFBytesGenerator.new(dig)
    hkdfParam = org.bouncycastle.crypto.params.HKDFParameters.new(to_java_bytes(input), to_java_bytes(@config.salt) ,to_java_bytes(@config.info))
    hkdf.init(hkdfParam)

    out = ::Java::byte[@config.outBitLength/8].new
    hkdf.generateBytes(out, 0, out.length)

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

  rescue Exception => ex
    raise KDFEngineException, ex
  end
  
end