Method: Ccrypto::Java::PKCS7Engine#decrypt

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

#decrypt(val, &block) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/ccrypto/java/engines/pkcs7_engine.rb', line 342

def decrypt(val, &block)
  validate_input(val, "decrypt") 
  validate_key_must_exist("decrypt")

  raise PKCS7EngineException, "certForDecryption is required for PKCS7 decrypt operation" if is_empty?(@config.certForDecryption)
  raise PKCS7EngineException, "Given certForDecryption must be a Ccrypto::X509Cert object" if not @config.certForDecryption.is_a?(Ccrypto::X509Cert)

  case val
  when java.io.ByteArrayInputStream
    envp = org.bouncycastle.cms.CMSEnvelopedData.new(val)
  else
    if not val.nil?
      ba = to_java_bytes(val)
      case ba
      when ::Java::byte[]
        envp = org.bouncycastle.cms.CMSEnvelopedData.new(ba)
      else
        raise PKCS7EngineException, "Unknown input type '#{ba}' is given"
      end
    else
      raise PKCS7EngineException, "Null input is given"
    end
  end

  if block
    os = block.call(:output_stream)
    intBufSize = block.call(:int_buffer_size)
  end

  os = java.io.ByteArrayOutputStream.new if os.nil?
  intBufSize = 1024000 if is_empty?(intBufSize)

  kt = decryption_key_to_recipient(@config.private_key)

  lastEx = nil
  recipients = envp.getRecipientInfos.getRecipients
  recipients.each do |r|

    begin
      encIs = r.getContentStream(kt).getContentStream
    rescue Exception => ex
      lastEx = ex
      teLogger.debug "Got exception : #{ex.message}. Retry with another envelope"
      next
    end

    begin
      total = 0
      buf = ::Java::byte[intBufSize].new
      while((read = encIs.read(buf, 0, buf.length)) != -1)
        os.write(buf,0, read)
      end

      os.flush
    rescue Exception
    ensure
      begin
        encIs.close
      rescue Exception
      end
    end

    lastEx = nil
    break
  end

  if not lastEx.nil?
    raise PKCS7EngineException, lastEx
  end

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

end