Method: Ccrypto::Java::PKCS7Engine#encrypt

Defined in:
lib/ccrypto/java/engines/pkcs7_engine.rb

#encrypt(val, &block) ⇒ Object



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
# File 'lib/ccrypto/java/engines/pkcs7_engine.rb', line 271

def encrypt(val, &block)

  gen = org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator.new
  @config.recipient_certs.each do |re|
    gen.addRecipientInfoGenerator(to_cms_recipint_info(re))
  end

  intBufSize = 1024000
  if block
    cipher = block.call(:cipher)
    teLogger.debug "Application given cipher #{cipher}"

    prov = block.call(:jce_provider)
    intBufSize = block.call(:int_buffer_size)
    os = block.call(:output_stream)
    if not os.nil? and not os.is_a?(java.io.OutputStream)
      raise PKCS7EngineException, "java.io.OutputStream expected but was given '#{os.class}'"
    end
  end

  cipher = Ccrypto::DirectCipherConfig.new({ algo: :aes, keysize: 256, mode: :cbc }) if cipher.nil?
  prov =  Ccrypto::Java::JCEProvider::DEFProv if is_empty?(prov)
  intBufSize = 1024000 if is_empty?(intBufSize)

  os = java.io.ByteArrayOutputStream.new if os.nil?

  encOut = gen.open(os, org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder.new(cipher_to_bc_cms_algo(cipher)).setProvider(prov).build())

  case val
  when java.io.InputStream
    
    begin
      total = 0
      buf = ::Java::byte[intBufSize].new
      while((read = val.read(buf, 0, buf.length)) != -1)
        encOut.write(buf, 0, read)
      end

      encOut.flush
      encOut.close

    rescue Exception
    ensure
      begin
        encOut.close
      rescue Exception
      end
    end

  else

    if val.nil?
      raise PKCS7EngineException, "Nil input is given."
    else
      ba = to_java_bytes(val)
      case ba
      when ::Java::byte[]
        encOut.write(ba)
        encOut.close
        encOut.close
      else
        raise PKCS7EngineException, "Unknown format given as input #{val}"
      end
    end

  end

  os.toByteArray if os.is_a?(java.io.ByteArrayOutputStream)

end