Module: GcryptoBcCms::KeyPairCrypto

Included in:
Gcrypto::KeyPairCms, KeyPairCryptoEngine
Defined in:
lib/gcrypto_bc_cms/keypair_crypto.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.to_bc_cms_algo(algo) ⇒ Object

end to_enc_recipient_info



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
# File 'lib/gcrypto_bc_cms/keypair_crypto.rb', line 349

def KeyPairCrypto.to_bc_cms_algo(algo)
  case algo
  when Gcrypto::SecretKeyCryptoContext
    case algo.keyType
    when :aes
      case algo.keyLen
      when 128, 192, 256
        case algo.mode
        when "CBC", "CCM", "GCM"
          eval("org.bouncycastle.cms.CMSAlgorithm::AES#{algo.keyLen}_#{algo.mode}")
        else
          raise GcryptoBcCms::Error, "Unsupported mode '#{algo.mode}'"
        end
        # end case algo.mode
      else
        raise GcryptoBcCms::Error, "Unsupported key length '#{algo.keyLen}'"
      end
      # end case algo.keyLen
    else
      raise GcryptoBcCms::Error, "Unsupported key type '#{algo.keyType}'"
    end
    # end case algo.type
  else
    raise GcryptoBcCms::Error, "Unknown object to cms algo '#{algo.class}'"
  end
  # end case algo
end

.to_dec_recipient(obj, provider = GcryptoJce::Provider::DefProvider) ⇒ Object

end decrypt()



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
# File 'lib/gcrypto_bc_cms/keypair_crypto.rb', line 461

def KeyPairCrypto.to_dec_recipient(obj, provider = GcryptoJce::Provider::DefProvider)
  if obj.nil?
    raise GcryptoBcCms::Error, "Given object to convert to recipient info is nil"
  end

  if Pkernel::KeyPair.is_private_key?(obj)
    GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is private key"
    org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient.new(obj).setProvider(provider)
  elsif GcryptoJce::SecretKey.is_secret_key?(obj)
    GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is secret key"
    #w = org.bouncycastle.operator.jcajce.JceSymmetricKeyUnwrapper.new(obj).setProvider(provider)
    if provider.nil?
      org.bouncycastle.cms.jcajce.JceKEKEnvelopedRecipient.new(obj)
    else
      org.bouncycastle.cms.jcajce.JceKEKEnvelopedRecipient.new(obj).setProvider(provider)
    end
  elsif obj.is_a?(Gcrypto::SecretKeyCryptoContext)
    prov = obj.key_provider
    prov = provider if prov.nil?
    if prov.nil?
      GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is secret key crypto context."
      org.bouncycastle.cms.jcajce.JceKEKEnvelopedRecipient.new(obj.key)
    else
      GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is secret key crypto context. '#{prov.nil? ? '' : "Using provider #{prov.name}" }'"
      org.bouncycastle.cms.jcajce.JceKEKEnvelopedRecipient.new(obj.key).setProvider(prov)
    end
    #org.bouncycastle.operator.jcajce.JceSymmetricKeyUnwrapper.new(obj.key).setProvider(prov)
  elsif obj.is_a?(String)
    GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is string --> password recipient"
    org.bouncycastle.cms.jcajce.JcePasswordEnvelopedRecipient.new(obj.to_java.toCharArray).setPasswordConversionScheme(org.bouncycastle.cms.PasswordRecipient::PKCS5_SCHEME2)
  elsif obj.java_kind_of?(Java::byte[])
    GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is java byte array. Assume string --> password recipient"
    org.bouncycastle.cms.jcajce.JcePasswordEnvelopedRecipient.new(String.from_java_bytes(obj).to_java.toCharArray).setPasswordConversionScheme(org.bouncycastle.cms.PasswordRecipient::PKCS5_SCHEME2)
  elsif obj.java_kind_of?(Java::char[])
    GcryptoBcCms::GConf.instance.glog.debug "Given decryption artifacts is java char array. Assume string --> password recipient"
    org.bouncycastle.cms.jcajce.JcePasswordEnvelopedRecipient.new(obj).setPasswordConversionScheme(org.bouncycastle.cms.PasswordRecipient::PKCS5_SCHEME2)
  else
    raise GcryptoBcCms::Error, "Unsupported object for decryption recipient object conversion '#{obj.class}'"
  end
end

.to_enc_recipient_info(obj, provider = GcryptoJce::Provider::DefProvider) ⇒ Object

end encrypt()



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
# File 'lib/gcrypto_bc_cms/keypair_crypto.rb', line 303

def KeyPairCrypto.to_enc_recipient_info(obj, provider = GcryptoJce::Provider::DefProvider)
  if obj.nil?
    raise GcryptoBcCms::Error, "Given object to convert to recipient info is nil"
  end

  if Pkernel::Certificate.is_cert_object?(obj)
    GcryptoBcCms::GConf.instance.glog.debug "Given recipient info is certificate"
    cert = Pkernel::Certificate.ensure_java_cert(obj)
    org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator.new(cert).setProvider(provider)
  elsif GcryptoJce::SecretKey.is_secret_key?(obj)
    GcryptoBcCms::GConf.instance.glog.debug "Given recipient info is secret key"
    #org.bouncycastle.operator.jcajce.JceSymmetricKeyWrapper.new(obj).setProvider(provider)
    org.bouncycastle.cms.jcajce.JceKEKRecipientInfoGenerator.new(SecureRandom.hex(8).to_java.getBytes, obj).setProvider(provider)
  elsif obj.is_a?(Gcrypto::SecretKeyCryptoContext)
    GcryptoBcCms::GConf.instance.glog.debug "Given recipient info is secret key crypto context"
    prov = obj.key_provider
    prov = provider if prov.nil?
    #wrapper = org.bouncycastle.operator.jcajce.JceSymmetricKeyWrapper.new(obj.key).setProvider(prov)
    org.bouncycastle.cms.jcajce.JceKEKRecipientInfoGenerator.new(obj.name.to_java.getBytes, obj.key).setProvider(prov)
  elsif obj.is_a?(String)
    GcryptoBcCms::GConf.instance.glog.debug "Given recipient info is string --> password recipient"
    #algo = org.bouncycastle.cms.CMSAlgorithm::AES256_GCM
    algo = org.bouncycastle.cms.CMSAlgorithm::AES256_CBC
    salt = GcryptoJce::SecureRandomEngine.generate
    iter = rand(1000...3000)
    org.bouncycastle.cms.jcajce.JcePasswordRecipientInfoGenerator.new(algo, obj.to_java.toCharArray).setPasswordConversionScheme(org.bouncycastle.cms.PasswordRecipient::PKCS5_SCHEME2).setSaltAndIterationCount(salt,iter)
  elsif obj.java_kind_of?(Java::byte[])
    GcryptoBcCms::GConf.instance.glog.debug "Given recipient info is java byte array. Assume string --> password recipient"
    #algo = org.bouncycastle.cms.CMSAlgorithm::AES256_GCM
    algo = org.bouncycastle.cms.CMSAlgorithm::AES256_CBC
    salt = GcryptoJce::SecureRandomEngine.generate
    iter = rand(1000...3000)
    org.bouncycastle.cms.jcajce.JcePasswordRecipientInfoGenerator.new(algo, String.from_java_bytes(obj).toCharArray).setPasswordConversionScheme(org.bouncycastle.cms.PasswordRecipient::PKCS5_SCHEME2).setSaltAndIterationCount(salt,iter)
  elsif obj.java_kind_of?(Java::char[])
    GcryptoBcCms::GConf.instance.glog.debug "Given recipient info is java char array. Assume string --> password recipient"
    #algo = org.bouncycastle.cms.CMSAlgorithm::AES256_GCM
    algo = org.bouncycastle.cms.CMSAlgorithm::AES256_CBC
    salt = GcryptoJce::SecureRandomEngine.generate
    iter = rand(1000...3000)
    org.bouncycastle.cms.jcajce.JcePasswordRecipientInfoGenerator.new(algo, obj).setPasswordConversionScheme(org.bouncycastle.cms.PasswordRecipient::PKCS5_SCHEME2).setSaltAndIterationCount(salt,iter)
  else
    raise GcryptoBcCms::Error, "Unsupported object for encryption recipient info conversion '#{obj.class}'"
  end
end

Instance Method Details

#decrypt(opts = { }) ⇒ Object

end to_be_cms_algo



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
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
# File 'lib/gcrypto_bc_cms/keypair_crypto.rb', line 378

def decrypt(opts = { })
  
  id = opts[:identity]
  sk = opts[:secret_key]
  skcc = opts[:secret_key_cc]
  pass = opts[:password]

  if not id.nil?
    cred = id.privKey
    provider = id.provider
  elsif not sk.nil?
    cred = sk
    provider = opts[:secret_key_provider]
  elsif not skcc.nil?
    cred = skcc
    provider = skcc.key_provider
  elsif not (pass.nil? or pass.empty?)
    cred = pass
  else
    raise GcryptoBcCms::Error, "No decryption credential given to decrypt data"
  end
  
  is = IoUtils.load_input(opts)
  envp = org.bouncycastle.cms.CMSEnvelopedData.new(is)
  
  outFile = opts[:outFile]
  if outFile.nil? or outFile.empty?
    out = java.io.ByteArrayOutputStream.new
  else 
    out = java.io.FileOutputStream.new(outFile)
  end
 
  kt = KeyPairCrypto.to_dec_recipient(cred, provider)
  
  lastEx = nil
  recipients = envp.getRecipientInfos.getRecipients
  recipients.each do |r|
    
    begin
      encIs = r.getContentStream(kt).getContentStream
    #rescue Java::OrgBouncycastleCms::CMSException => ex
    rescue Exception => ex
      lastEx = ex
      #if ex.message =~ /Decryption error/
        next
      #end
    end
    
    begin
      bufConf = opts[:int_buf] || { }
      total = 0
      IoUtils.read_chunk(encIs, bufConf) do |buf, from, len|
        out.write(buf, from, len)
        total += len
        GcryptoJce::GConf.instance.glog.debug "Processed #{NumberHelper.number_to_human_size(total)}"
      end
    rescue Exception
    ensure
      begin
        encIs.close
      rescue Exception
      end
      begin
        out.close
      rescue Exception
      end
    end

    lastEx = nil
    break
  end

  if not lastEx.nil?
    raise GcryptoBcCms::Error, lastEx
  elsif outFile.nil? or outFile.empty?
    out.toByteArray
  end

end

#encrypt(opts = { }) ⇒ Object

end verify()



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
# File 'lib/gcrypto_bc_cms/keypair_crypto.rb', line 242

def encrypt(opts = { })
  
  is = IoUtils.load_input(opts)
  rcpts = opts[:recipients]
  if rcpts.nil? or rcpts.empty?
    raise GcryptoBcCms::Error, "No recipients given to encrypt" 
  end
  
  gen = org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator.new
  rcpts.each do |re|
    gen.addRecipientInfoGenerator(KeyPairCrypto.to_enc_recipient_info(re))
  end
  
  outFile = opts[:outFile]
  if outFile.nil? or outFile.empty?
    out = java.io.ByteArrayOutputStream.new
  else
    out = java.io.FileOutputStream.new(outFile)
  end

  skCc = opts[:crypto_context]
  if skCc.nil?
    raise GcryptoBcCms::Error, "Crypto context is not available for CMS encrypt"
  end
  
  prov = GcryptoJce::Provider.handle_options(opts)
  encOut = gen.open(out, org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder.new(KeyPairCrypto.to_bc_cms_algo(skCc)).setProvider(prov).build())
  
  begin
    bufConf = opts[:int_buf] || { }
    total = 0
    IoUtils.read_chunk(is, bufConf) do |buf, from, len|
      encOut.write(buf, from, len)
      total += len
      GcryptoJce::GConf.instance.glog.debug "Processed #{NumberHelper.number_to_human_size(total)}"
    end
  rescue Exception
  ensure
    begin
      is.close
    rescue Exception
    end
    begin
      out.close
    rescue Exception
    end
    begin
      encOut.close
    rescue Exception
    end
  end

  if outFile.nil? or outFile.empty?
    out.toByteArray
  end
  
end

#sign(opts = { }) ⇒ Object

gen.addCertificates(store)

attachedSign = opts[:attachedSign]
attachedSign = true if attachedSign.nil?
gen.generate(msg, attachedSign)

end

end sign()



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/gcrypto_bc_cms/keypair_crypto.rb', line 63

def sign(opts = { })
  raise GcryptoBcCms::Error, "Insufficient parameters for CMS signature generation" if opts.nil? or opts.empty?
  
  ids = opts[:identities]
  if ids.nil?
    raise GcryptoBcCms::Error, "Identity to sign the data is not available"
  end
  ids = [ids] if not ids.is_a?(Array)

  is = IoUtils.load_input(opts)
 
  lst = java.util.ArrayList.new 

  ids.each do |id|
    lst.add(id.certificate)
  end

  store = org.bouncycastle.cert.jcajce.JcaCertStore.new(lst)
  gen = org.bouncycastle.cms.CMSSignedDataStreamGenerator.new
 
  signHash = opts[:signHash] || "SHA256" 
  ids.each do |id|
    GcryptoBcCms::GConf.instance.glog.debug "Adding signer #{id.certificate.subjectDN}"
    prov = GcryptoJce::Provider.handle_options({ provider: id.provider })
    signer = org.bouncycastle.operator.jcajce.JcaContentSignerBuilder.new(Pkernel::KeyPair.derive_signing_algo(id.privKey, signHash)).setProvider(prov).build(id.privKey)
    infoGen = org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder.new(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder.new.setProvider(prov).build()).build(signer, id.certificate)
    gen.addSignerInfoGenerator(infoGen)
  end

  gen.addCertificates(store)
  #gen.addCRLs(crlStore)
  
  outFile = opts[:outFile]
  if not (outFile.nil? or outFile.empty?)
    os = java.io.FileOutputStream.new(outFile)
  else
    os = java.io.ByteArrayOutputStream.new
  end

  attachedSign = opts[:attachedSign]
  attachedSign = true if attachedSign.nil?

  sos = gen.open(os, attachedSign)
  
  begin
    bufConf = opts[:int_buf] || { }
    total = 0
    IoUtils.read_chunk(is, bufConf) do |buf, from, len|
      sos.write(buf, from, len)
      total += len
      GcryptoJce::GConf.instance.glog.debug "Signed #{NumberHelper.number_to_human_size(total)}"
    end
  rescue Exception
  ensure
    begin
      is.close
    rescue Exception
    end
    begin
      os.close
    rescue Exception
    end
    begin
      sos.close
    rescue Exception
    end
  end

  if outFile.nil? or outFile.empty?
    os.toByteArray
  end

end

#verify(opts = { }) ⇒ Object



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
# File 'lib/gcrypto_bc_cms/keypair_crypto.rb', line 141

def verify(opts = { })
  
  if opts.nil? or opts.empty?
    raise GcryptoBcCms::Error, "Insufficient parameters for CMS signature verification"
  end

  prov = GcryptoJce::Provider.handle_options(opts)
  
  attachedSign = false
  dataFile = opts[:file]
  dataBin = opts[:bin]
  if not (dataFile.nil? or dataFile.empty?)
    data = org.bouncycastle.cms.CMSProcessableFile.new(java.io.File.new(dataFile))
  elsif not dataBin.nil?
    data = org.bouncycastle.cms.CMSProcessableByteArray.new(IoUtils.ensure_java_bytes(dataBin))
  else
    attachedSign = true
  end

  file = opts[:sign_file]
  bin = opts[:sign_bin]
  if not (file.nil? or file.empty?)
    if attachedSign
      signed = org.bouncycastle.cms.CMSSignedData.new(java.io.FileInputStream.new(file))
    else
      signed = org.bouncycastle.cms.CMSSignedData.new(data, java.io.FileInputStream.new(file))
    end
  elsif not bin.nil?
    if attachedSign
      signed = org.bouncycastle.cms.CMSSignedData.new(IoUtils.ensure_java_bytes(bin))
    else
      signed = org.bouncycastle.cms.CMSSignedData.new(data, IoUtils.ensure_java_bytes(bin))
    end
  else
    raise GcryptoBcCms::Error, "Neither signature in file or memory buffer given for signatur verification"
  end

  outFile = opts[:out_file]
  if not (outFile.nil? or outFile.empty?)
    dataOs = java.io.FileOutputStream.new(outFile)
  end
  
  result = []
  certs = signed.certificates
  signerInfo = signed.getSignerInfos
  signers = signerInfo.getSigners
  signers.each do |signer|
    
    certs.getMatches(signer.getSID).each do |c|
      begin

        GcryptoBcCms::GConf.instance.glog.debug "Verifying #{c.subject}..."
        verifier = org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder.new.setProvider(prov).build(c)
        if signer.verify(verifier)
          GcryptoBcCms::GConf.instance.glog.debug "Signer #{c.subject} verified"
          result << true
          detail = { }
          detail[:certificate] = c
          if attachedSign
            if dataOs.nil?
              detail[:data] = signed.getSignedContent.getContent
            else
              begin
                signed.getSignedContent.write(dataOs)
                dataOs.flush
              rescue Exception
              ensure
                begin
                  dataOs.close
                rescue Exception
                end
              end
              
              detail[:data_file] = outFile
            end
            # end if dataOs.nil?
          end
          
          result << detail

          break
        end
        
      rescue Exception => ex
        GcryptoBcCms::GConf.instance.glog.debug "#{c.subject} #{ex.message}"
      end
    end
    # end certs.getMatches
    
    break if not result.empty?
  end
  # end signers.each
  
  result = [false] if result.empty?
  
  result
end