Class: Ccrypto::Java::CipherEngine

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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DataConversion

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

Constructor Details

#initialize(*args, &block) ⇒ CipherEngine

Design is by the object is initialized (new) all the parameter to setup the cipher shall need to be available including those aux data such as auth_data for GCM mode for example

Raises:

  • (Ccrypto::CipherEngineException)


407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 407

def initialize(*args, &block)

  @spec = args.first

  raise Ccrypto::CipherEngineException, "Unsupported config type #{@spec.class}" if not @spec.is_a?(Ccrypto::CipherConfig)

  @keyJceProvider = @spec.provider_config[:key_jce_provider] || JCEProvider::DEFProv
  @cipherJceProvider = @spec.provider_config[:cipher_jce_provider] || JCEProvider::DEFProv

  raise Ccrypto::CipherEngineException, "Key JCE provider '#{@keyJceProvider}' not registered." if not_empty?(@keyJceProvider) and not JCEProvider.instance.is_provider_registered?(@keyJceProvider)
  raise Ccrypto::CipherEngineException, "Cipher JCE provider '#{@cipherJceProvider}' not registered." if not_empty?(@cipherJceProvider) and not JCEProvider.instance.is_provider_registered?(@cipherJceProvider)

  cSpec = @spec.provider_config[:cipher_str]
  if @cipherJceProvider.nil?
    begin
      logger.debug "Cipher instance #{cSpec} with null provider"
      @cipher = javax.crypto.Cipher.getInstance(cSpec)
    rescue Exception => ex
      logger.debug "Error #{ex.message} for spec '#{cSpec}' using null provider. Retest with BC provider"
      @cipher = javax.crypto.Cipher.getInstance(cSpec, Ccrypto::Java::JCEProvider::BCProv.name)
    end
  else
    logger.debug "Cipher instance #{cSpec} with provider '#{@cipherJceProvider.is_a?(String) ? @cipherJceProvider : @cipherJceProvider.name}'"
    @cipher = javax.crypto.Cipher.getInstance(cSpec, @cipherJceProvider)
  end


  if @spec.has_key?
    keyLen = @spec.ccrypto_key.length
    logger.debug "Using given cipher key of length #{keyLen} bytes / #{keyLen*8}"

  else
    
    logger.debug "Generating cipher key #{@spec.inspect}"
    if @keygenJceProvider.nil?
      kg = javax.crypto.KeyGenerator.getInstance(@spec.provider_config[:keygen_algo])
    else
      kg = javax.crypto.KeyGenerator.getInstance(@spec.provider_config[:keygen_algo], @keygenJceProvider)
    end

    if @spec.provider_config[:require_init_keysize]
      kg.init(@spec.keysize.to_i)
      logger.debug "Init with keysize ; #{@spec.provider_config[:keygen_algo]} / #{@spec.keysize.to_i} bits / #{@spec.keysize.to_i/8} bytes"
    end

    @spec.ccrypto_key = Ccrypto::SecretKey.new(@spec.algo, @spec.keysize, kg.generateKey)
    @spec.ccrypto_key.provider_config = @spec.provider_config

  end

  if @spec.iv_required?
    logger.debug "IV required of length #{@spec.ivLength}"
    if is_empty?(@spec.iv)
      @spec.iv = Ccrypto::Java::SecureRandomEngine.random_bytes(@spec.ivLength)
      logger.debug "Generated IV of length #{to_hex(@spec.iv)}"
    else
      if @spec.iv.is_a?(String)
        @spec.iv = to_java_bytes(@spec.iv)
        logger.debug "Converting IV into  #{to_hex(@spec.iv)}"
      end
    end

    if @spec.is_mode?(:gcm)
      ivParam = javax.crypto.spec.GCMParameterSpec.new(@spec.iv.length*8, @spec.iv) # 12 bytes
    else
      ivParam = javax.crypto.spec.IvParameterSpec.new(@spec.iv) 
    end

  else
    logger.debug "IV is not required"

  end

  logger.debug "spec key : #{@spec.ccrypto_key.inspect}"

  case @spec.ccrypto_key
  when Ccrypto::SecretKey
    logger.debug "Given secret key"
    skey = @spec.ccrypto_key.native_key
  when ::Java::byte[]
    logger.debug "Given byte array key"
    skey = javax.crypto.spec.SecretKeySpec.new(@spec.ccrypto_key, @spec.algo.to_s)
  when String
    logger.debug "Given ruby string key"
    skey = javax.crypto.spec.SecretKeySpec.new(to_java_bytes(@spec.ccrypto_key), @spec.algo.to_s)
  when javax.crypto.spec.SecretKeySpec
    logger.debug "Given Java SecretKeySpec"
    skey = @spec.ccrypto_key
  else
    raise CipherEngineException, "Unknown key type '#{@spec.ccrypto_key}'"
  end

  #logger.debug "SKey : #{to_hex(skey.encoded)}"

  if @spec.is_encrypt_cipher_mode?
    if ivParam.nil?
      logger.debug "Encryption mode"
      @cipher.init(javax.crypto.Cipher::ENCRYPT_MODE, skey)
    else
      logger.debug "Encryption mode with IV"
      @cipher.init(javax.crypto.Cipher::ENCRYPT_MODE, skey, ivParam)
    end

  elsif @spec.is_decrypt_cipher_mode?
    if ivParam.nil?
      logger.debug "Decryption mode"
      @cipher.init(javax.crypto.Cipher::DECRYPT_MODE, skey)
    else
      logger.debug "Decryption mode with IV"
      @cipher.init(javax.crypto.Cipher::DECRYPT_MODE, skey, ivParam)
    end

  else
    raise Ccrypto::CipherEngineException, "Cipher operation must be given"
  end

  if @spec.is_auth_mode_cipher? 

    # AAD can be added anytime before cipher final
    # Special instance method for AAD capable cipher
    instance_eval <<-END

def update_aad(val)
    logger.debug "Adding Additional Authenticated Data of length : \#{val.length}"
    @cipher.updateAAD(to_java_bytes(val))
end

    END

  end

end

Class Method Details

.get_cipher_config(algo, keysize = nil, mode = nil, padding = nil) ⇒ Object



344
345
346
347
348
349
350
351
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 344

def self.get_cipher_config(algo, keysize = nil, mode = nil, padding = nil)
  params = { algo: algo }
  params[:keysize] = keysize if not_empty?(keysize)
  params[:mode] = mode if not_empty?(mode)
  params[:padding] = padding if not_empty?(padding)

  supported_ciphers.find(params).map { |c| c.dup }
end

.is_refresh_always?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 32

def self.is_refresh_always?
  ENV['CC_J_SUPCIPHER_REFRESH_ALWAYS'] == "true"
end

.load_algo_into_cache(list) ⇒ Object



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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 36

def self.load_algo_into_cache(list)
  
  skipped = []

  java.security.Security.getAlgorithms("Cipher").to_a.delete_if { |e| e.include?(".") }.sort.each do |c|

    #next if skipped.map { |e|
    #  if c.downcase =~ /#{e}/i
    #    1
    #  else
    #    0
    #  end
    #}.include?(1)

    testSpec = c
    loop do

      begin

        kg = javax.crypto.KeyGenerator.getInstance(testSpec, JCEProvider::DEFProv)
        logger.debug "#{testSpec} is good!"

        native = { keygen_algo: testSpec, require_init_keysize: true }
        opts = { fixed_input_length_in_byte: -1 }

        #if ["chacha20-poly1305","xsalsa20","salsa20","chacha20","chacha","chacha7539"].include?(testSpec.downcase)
        if ["chacha20-poly1305","xsalsa20","salsa20"].include?(testSpec.downcase)

          begin
            kg = javax.crypto.KeyGenerator.getInstance(testSpec, JCEProvider::DEFProv)
            tkey = kg.generateKey
            opts[:keysize] = tkey.encoded.length*8
            native[:require_init_keysize] = false

            cspec = [testSpec]
            if ["chacha20-poly1305", "chacha20","chacha7539"].include?(testSpec.downcase)
              ivLen = 12
              iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
              ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 12 bytes

            elsif ["xsalsa20"].include?(testSpec.downcase)
              ivLen = 24
              iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
              ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 24 bytes

            elsif ["salsa20","chacha"].include?(testSpec.downcase)
              ivLen = 8
              iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
              ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 8 bytes
            end

            decSuss, blocksize = test_encrypt_decrypt(cspec.join("/"), tkey, ivParam)

            if decSuss

              opts[:block_size] = blocksize

              begin
                test_encrypt_decrypt(cspec.join("/"), tkey, ivParam, blocksize+1)
              rescue Exception => ex
                opts[:mandatory_block_size] = blocksize
              end

              opts[:ivLength] = ivLen

              opts[:authMode] = ["chacha20-poly1305"].include?(testSpec.downcase)

              opts[:mode] = nil
              opts[:padding] = nil

              native[:cipher_str] = testSpec
              # key generated from this provider
              native[:key_jce_provider] = JCEProvider::DEFProv.name
              # tested with cipher using this provider
              native[:cipher_jce_provider] = JCEProvider::DEFProv.name

              # construct the key config too as key config not depending on cipher
              # but cipher depending on key config
              kconf = Ccrypto::KeyConfig.new(testSpec, opts[:keysize])
              kconf.provider_config = { keygen_algo: native[:keygen_algo], keysize: opts[:keysize], key_jce_provider: native[:key_jce_provider] }

              conf = Ccrypto::CipherConfig.new(testSpec, opts)
              conf.provider_config = native.clone
              conf.key_config = kconf

              logger.debug "Registering : #{testSpec}/#{opts[:keysize]}"

              list.register(conf.clone)

            end


          rescue Exception => ex
            logger.debug "Special algo '#{testSpec}' failed : #{ex}"
            logger.debug ex.backtrace.join("\n")
          end

          break

        else  # other algo except those special one

          goodKz = []
          [128,192,224,256,384,512].each do |kz|
            begin

              kg = javax.crypto.KeyGenerator.getInstance(testSpec, JCEProvider::DEFProv)
              kg.init(kz)
              kg.generateKey

              goodKz << kz

            rescue Exception => ex
              #logger.debug "Failed probing for cipher algo #{testSpec}/#{kz} : #{ex}"
            end
          end # keysize loop

          authMode = [:gcm,:ccm]
          [:none,:cbc,:cfb,:ecb,:gcm,:ofb,:ctr,:ccm].each do |mode|

            goodKz.each do |kz|

              begin

                kg = javax.crypto.KeyGenerator.getInstance(testSpec, JCEProvider::DEFProv)
                kg.init(kz)
                tkey = kg.generateKey

                [:NoPadding, :PKCS5Padding, :PKCS7Padding].each do |pad|

                  if [:gcm, :ccm].include?(mode) and pad != :NoPadding
                    next
                  end

                  begin

                    jceAlgo = [testSpec,mode,pad]
                    cs = jceAlgo.join("/")
                    logger.debug "Testing cipher with spec : #{cs} (#{kz})"
                    tc = javax.crypto.Cipher.getInstance(cs, JCEProvider::DEFProv)

                    ivParam = nil
                    ivLen = 0
                    if mode == :gcm
                      ivLen = 12
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.GCMParameterSpec.new(iv.length*8, iv) # 16 bytes

                    elsif ["blowfish","cast5","gost28147","idea","skipjack","tea","xtea","des","desede", "gost3412-2015","rc2","rc5"].include?(testSpec.downcase)
                      if mode != :ecb
                        ivLen = 8
                        iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                        ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 16 bytes
                      end

                    elsif ["shacal-2","shacal2"].include?(testSpec.downcase)
                      if mode != :ecb
                        ivLen = 32
                        iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                        ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 16 bytes
                        opts[:min_input_length] = 32
                      end

                    elsif ["threefish-1024"].include?(testSpec.downcase)
                      if mode != :ecb
                        ivLen = 128
                        iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                        ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 16 bytes
                      end

                    elsif ["threefish-256"].include?(testSpec.downcase)
                      if mode != :ecb
                        ivLen = 32
                        iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                        ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 16 bytes
                      end

                    elsif ["threefish-512"].include?(testSpec.downcase)
                      if mode != :ecb
                        ivLen = 64
                        iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                        ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 64 bytes
                      end

                    elsif ["chacha20","chacha7539"].include?(testSpec.downcase)
                      ivLen = 12
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 12 bytes

                    elsif ["xsalsa20"].include?(testSpec.downcase)
                      ivLen = 24
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 24 bytes

                    elsif ["salsa20","chacha"].include?(testSpec.downcase)
                      ivLen = 8
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 8 bytes

                    elsif testSpec.downcase[0...3] == "des"
                      ivLen = 8
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 8 bytes

                    elsif ["grain128","grainv1", "hc128","hc256","vmpc","vmpc-ksa3","zuc-128","zuc-256"].include?(testSpec.downcase)
                      ivLen = 16
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 8 bytes


                    elsif mode == :ccm
                      ivLen = 7
                      iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                      ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 7 bytes

                    elsif mode != :ecb  
                      #if not ["hc128","hc256"].include?(testSpec.downcase)
                        ivLen = 16
                        iv = Ccrypto::Java::SecureRandomEngine.random_bytes(ivLen)
                        ivParam = javax.crypto.spec.IvParameterSpec.new(iv) # 16 bytes
                      #end

                    else
                      ivLen = 0

                    end

                    decSuccess, blocksize = test_encrypt_decrypt(cs, tkey, ivParam)

                    if decSuccess

                      opts[:block_size] = blocksize

                      if blocksize > 0
                        opts[:mandatory_block_size] = -1
                        begin
                          test_encrypt_decrypt(cs, tkey, ivParam, blocksize+1)
                        rescue Exception => ex
                          logger.debug "Config #{cs} must work on block size"
                          opts[:mandatory_block_size] = blocksize
                        end
                      end

                      opts[:keysize] = kz
                      opts[:mode] = mode.to_s
                      opts[:ivLength] = ivLen
                      opts[:padding] = pad.to_s

                      opts[:authMode] = authMode.include?(mode)

                      native[:cipher_str] = cs
                      # key generated from this provider
                      native[:key_jce_provider] = JCEProvider::DEFProv.name
                      # tested with cipher using this provider
                      native[:cipher_jce_provider] = JCEProvider::DEFProv.name

                      # construct the key config too as key config not depending on cipher
                      # but cipher depending on key config
                      kconf = Ccrypto::KeyConfig.new(testSpec, opts[:keysize])
                      kconf.provider_config = { keygen_algo: native[:keygen_algo], keysize: opts[:keysize], key_jce_provider: native[:key_jce_provider] }

                      conf = Ccrypto::CipherConfig.new(testSpec, opts)
                      conf.provider_config = native.clone
                      conf.key_config = kconf

                      logger.debug "Registering : #{testSpec}/#{kz}/#{mode}/#{pad}"

                      list.register(conf.clone)

                    end # decryption successful!

                  rescue Exception => ex
                    logger.debug "Failed for cipher algo #{testSpec}/#{kz}/#{mode}/#{pad} : #{ex}"
                    if ex.message =~ /array length/
                      puts ex.backtrace.join("\n")
                    end
                    Ccrypto::Java.on_detail_debug ex.backtrace.join("\n")
                    #logger.debug ex.backtrace.join("\n")
                  end

                end


              rescue Exception => ex
                #p ex
                logger.debug "Failed for cipher algo #{testSpec}/#{kz}/#{mode} : #{ex}"
                #logger.error ex.backtrace.join("\n")
              end

            end

          end # mode loop

          break

        end
      rescue Exception => ex
        logger.debug "Probing for cipher algo : #{ex}"
        #logger.error ex.backtrace.join("\n")
        break
      end

    end # loop key type

  end

  list
end

.supported_ciphersObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 10

def self.supported_ciphers

  if @supported.nil?

    if is_refresh_always?
      logger.debug "Refresh due to env flag" 
      @supported = SupportedCipherList.new
    else
      logger.debug "Load support cipher from storage" 
      @supported = SupportedCipherList.load_from_storage("#{Ccrypto::Java::Provider.provider_name}_supported_cipher")
    end

    if @supported.empty?
      logger.debug "Supported cipher list is empty. Probe for supported algo and save to cache"
      @supported = load_algo_into_cache(@supported)
      @supported.save_to_storage("#{Ccrypto::Java::Provider.provider_name}_supported_cipher")
    end
  end

  @supported
end

Instance Method Details

#final(val = nil, &block) ⇒ Object



551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 551

def final(val = nil, &block)
  baos = java.io.ByteArrayOutputStream.new
  if not_empty?(val)
    res = update(to_java_bytes(val))
    baos.write(res) if not_empty?(res)
  end

  begin
    res = @cipher.doFinal

    logger.debug "Final output length : #{res.length}"

    baos.write(res) if not_empty?(res)
    cres = baos.toByteArray
    logger.debug "Cipher length : #{cres.length}"

    cres

  rescue Exception => ex
    raise Ccrypto::CipherEngineException, ex
  end
end

#resetObject



574
575
576
577
578
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 574

def reset
  if not @spec.nil?
    @cipher = javax.crypto.Cipher.getInstance(@spec.provider_config[:cipher_str])
  end
end

#update(val) ⇒ Object



540
541
542
543
544
545
546
547
548
549
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 540

def update(val)
  logger.debug "Passing #{val.length} / #{to_java_bytes(val).length} bytes to cipher"
  res = @cipher.update(to_java_bytes(val))  
  if res.nil?
    logger.debug "Cipher update returns nothing"
  else
    logger.debug "Cipher update output length #{res.length}"
  end
  res
end