Class: Ccrypto::Java::PKCS7Engine

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

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(config) ⇒ PKCS7Engine

Returns a new instance of PKCS7Engine.



13
14
15
16
# File 'lib/ccrypto/java/engines/pkcs7_engine.rb', line 13

def initialize(config)
  raise PKCS7EngineException, "Ccrypto::PKCS7Config is expected. Given #{config}" if not config.is_a?(Ccrypto::PKCS7Config)
  @config = config
end

Instance Method Details

#decrypt(val, &block) ⇒ Object



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
415
416
417
418
419
420
421
# File 'lib/ccrypto/java/engines/pkcs7_engine.rb', line 349

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
      logger.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

#encrypt(val, &block) ⇒ Object



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
343
344
345
346
347
# File 'lib/ccrypto/java/engines/pkcs7_engine.rb', line 268

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)
    logger.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

  if cipher.nil?
    cipher = CipherEngine.get_cipher_config(:aes, 256, :cbc)
    if not_empty?(cipher)
      cipher = cipher.first
    else
      raise PKCS7EngineException, "Not able to get AES/256/CBC from CipherEngine"
    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

#sign(val, outForm = :bin, &block) ⇒ Object



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

def sign(val, outForm = :bin, &block)

  validate_input(val, "signing")
  validate_key_must_exist("signing")

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

  privKey = @config.private_key

  prov = nil
  signHash = nil
  attached = true
  caCerts = []
  os = nil
  readBufSize = 1024000
  signSpec = nil
  if block
    prov = block.call(:jce_provider)
    signHash = block.call(:sign_hash)
    detSign = block.call(:detached_sign)
    attached = ! detSign if is_bool?(detSign)
    caCerts = block.call(:ca_certs)
    os = block.call(:output_stream)
    if not (os.nil? or os.is_a?(java.io.OutputStream))
      raise PKCS7EngineException, "Given output_stream is not type of java.io.OutputStream (Given #{os}). Please provide an java.io.OutputStream object or use default which is java.io.ByteArrayOutputStream"
    end
    readBufSize = block.call(:read_buffer_size)
    signSpec = block.call(:signing_spec)
  end

  caCerts = [] if caCerts.nil?
  prov = Ccrypto::Java::JCEProvider::DEFProv if is_empty?(prov)
  signHash = :sha256 if is_empty?(signHash)
  attached = true if is_empty?(attached)
  readBufSize = 1024000 if readBufSize.to_i > 0

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

  lst = java.util.ArrayList.new 
  lst.add(@config.signerCert.nativeX509)
  caCerts.each do |cc|
    list.add(cc.nativeX509)
  end
  store = org.bouncycastle.cert.jcajce.JcaCertStore.new(lst)

  gen = org.bouncycastle.cms.CMSSignedDataStreamGenerator.new

  if is_empty?(signSpec)
    gKey = privKey
    loop do
      case gKey
      when ::Java::OrgBouncycastleJcajceProviderAsymmetricEc::BCECPrivateKey
        signSpec = "#{signHash.upcase}withECDSA"
        break
      when java.security.interfaces.RSAPrivateKey
        signSpec = "#{signHash.to_s.upcase}withRSA"
        break
      when Ccrypto::PrivateKey
        gKey = gKey.native_privKey
      else
        raise PKCS7EngineException, "Unknown private key type '#{gKey}' to derive the hash algo from"
      end
    end
  end

  #signer = org.bouncycastle.operator.jcajce.JcaContentSignerBuilder.new(signSpec).setProvider(prov).build(privKey)
  signer = org.bouncycastle.operator.jcajce.JcaContentSignerBuilder.new(signSpec).setProvider(prov).build(gKey)
  infoGen = org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder.new(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder.new.setProvider(prov).build()).build(signer, @config.signerCert.nativeX509)
  gen.addSignerInfoGenerator(infoGen)
  
  gen.addCertificates(store)

  begin

    if attached
      logger.debug "Initiated attached sign"
    else
      logger.debug "Initiated detached sign"
    end

    sos = gen.open(os, attached)

    case val
    when java.io.InputStream
      logger.debug "InputStream data-to-be-signed detected"
      buf = ::Java::Byte[readBufSize].new
      read = 0
      processed = 0
      while((read = val.read(buf, 0, buf.length)) != -1)
        sos.write(buf, 0 ,read)
        processed += read
        block.call(:processed, processed) if block
      end
    else
      logger.debug "Byte array data-to-be-signed detected"
      ba = to_java_bytes(val)
      if ba.is_a?(::Java::byte[])
        sos.write(ba)
        sos.flush
        sos.close
      else
        raise PKCS7EngineException, "Not able to convert given input into byte array. Got #{val.class}"
      end
    end

    os.toByteArray

  rescue Exception => ex
    raise PKCS7EngineException, ex
  ensure 

    begin
      sos.close
    rescue Exception; end
  end

end

#verify(val, inForm = :bin, &block) ⇒ Object



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

def verify(val, inForm = :bin, &block)

  srcData = nil
  os = nil
  prov = Ccrypto::Java::JCEProvider::DEFProv
  if block
    srcData = block.call(:signed_data)
    os = block.call(:output_stream)
    prov = block.call(:jce_provider)
  end

  os = java.io.ByteArrayOutputStream.new if os.nil?
  prov = Ccrypto::Java::JCEProvider::DEFProv if is_empty?(prov)

  data = nil
  case srcData
  when java.io.File
    data = org.bouncycastle.cms.CMSProcessableFile.new(val)
    logger.debug "Given original data is a java.io.File"
  else
    if not_empty?(srcData)
      ba = to_java_bytes(srcData)
      if ba.is_a?(::Java::byte[])
        data = org.bouncycastle.cms.CMSProcessableByteArray.new(ba)
        logger.debug "Given original data is a byte array"
      else
        raise PKCS7EngineException, "Failed to read original data. Given #{srcData}"
      end
    else
      logger.debug "Original data for signing is not given."
    end
  end

  case val
  when java.io.InputStream
    if data.nil?
      logger.debug "Attached signature with java.io.InputStream signature detected during verification"
      signed = org.bouncycastle.cms.CMSSignedData.new(val)
    else
      logger.debug "Detached signature with java.io.InputStream signature detected during verification"
      signed = org.bouncycastle.cms.CMSSignedData.new(data, val)
    end
  else
    if not_empty?(val)
      ba = to_java_bytes(val)
      if ba.is_a?(::Java::byte[])
        if data.nil?
          logger.debug "Attached signature with byte array signature detected during verification"
          signed = org.bouncycastle.cms.CMSSignedData.new(ba)
        else
          logger.debug "Detached signature with byte array signature detected during verification"
          signed = org.bouncycastle.cms.CMSSignedData.new(data, ba)
        end
      else
        raise PKCS7EngineException, "Failed to convert input to java byte array. Given #{val.class}"
      end
    else
      raise PKCS7EngineException, "Given signature to verify is empty."
    end
  end

  certs = signed.certificates
  signerInfo = signed.getSignerInfos
  signers = signerInfo.getSigners
  signatureVerified = false
  signers.each do |signer|

    certVerified = true
    certs.getMatches(signer.getSID).each do |c|
      begin

        if block
          certVerified = block.call(:verify_certificate, c)
          if certVerified.nil?
            logger.debug "Certificate with subject #{c.subject} / Issuer : #{c.issuer} / SN : #{c.serial_number.to_s(16)} passed through (no checking by application)"
            certVerified = true
          elsif is_bool?(certVerified)
            if certVerified
              logger.debug "Certificate with subject #{c.subject} / Issuer : #{c.issuer} / SN : #{c.serial_number.to_s(16)} accepted by application"
            else
              logger.debug "Certificate with subject #{c.subject} / Issuer : #{c.issuer} / SN : #{c.serial_number.to_s(16)} rejected by application"
            end
          else
            logger.debug "Certificate with subject #{c.subject} / Issuer : #{c.issuer} / SN : #{c.serial_number.to_s(16)} passed through (no checking by application. Given #{certVerified})"
          end
        else
          logger.debug "Certificate with subject #{c.subject} / Issuer : #{c.issuer} / SN : #{c.serial_number.to_s(16)} passed through (no checking by application)"
        end

        if certVerified

          logger.debug "Verifing signature against certificate '#{c.subject}'"
          verifier = org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder.new.setProvider(prov).build(c)
          if signer.verify(verifier)
            logger.debug "Signer with #{c.subject} verified!"
            if block
              block.call(:verification_result, true)
              if data.nil?
                block.call(:attached_data, signed.getSignedContent.getContent)
              end
            end

            signatureVerified = true

          else
            logger.debug "Signer with #{c.subject} failed. Retry with subsequent certificate"
            signatureVerified = false
          end

        end
      rescue ::Java::OrgBouncycastleCms::CMSSignerDigestMismatchException => ex
        logger.error "Signer digest mismatch exception : #{ex.message}" 
        signatureVerified = false
        break
      rescue Exception => ex
        logger.error ex
        logger.error ex.message
        logger.error ex.backtrace.join("\n")
      end
    end
    # end certs.getMatches

    break if signatureVerified

  end
  # end signers.each

  signatureVerified

end