Class: Ccrypto::Java::CipherEngine

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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DataConversion

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

Constructor Details

#initialize(*args, &block) ⇒ CipherEngine

Returns a new instance of CipherEngine.


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

def initialize(*args, &block)

  @spec = args.first

  case @spec
  when String, java.lang.String, Hash
    @spec = Ccrypto::DirectCipherConfig.new(@spec)
  when Ccrypto::CipherConfig
  else
    raise Ccrypto::CipherEngineException, "Unsupported config type #{@spec.class}"
  end


  if block
    @cipherJceProvider = block.call(:cipher_jceProvider)
    @keygenJceProvider = block.call(:keygen_jceProvider)
  end

  cSpec = to_cipher_spec(@spec)
  if @cipherJceProvider.nil?
    begin
      teLogger.debug "Cipher instance #{cSpec} with null provider"
      @cipher = javax.crypto.Cipher.getInstance(cSpec)
    rescue Exception => ex
      teLogger.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
    teLogger.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?
    teLogger.debug "Using given cipher key"

  else
    
    teLogger.debug "Generating cipher key"
    if @keygenJceProvider.nil?
      kg = javax.crypto.KeyGenerator.getInstance(to_algo(@spec.algo))
    else
      kg = javax.crypto.KeyGenerator.getInstance(to_algo(@spec.algo), @keygenJceProvider)
    end

    kg.init(@spec.keysize.to_i)
    @spec.key = kg.generateKey

  end

  if @spec.iv.is_a?(String)
    @spec.iv = to_java_bytes(@spec.iv)
  end

  if @spec.is_mode?(:gcm) or @spec.is_algo?(:chacha20)
    if is_empty?(@spec.iv)
      teLogger.debug "Generating 12 bytes of IV"
      @spec.iv = Ccrypto::Java::SecureRandomEngine.random_bytes(12)
    else
      teLogger.debug "Using given IV"
    end

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

  elsif @spec.is_algo?(:blowfish)
    if is_empty?(@spec.iv)
      teLogger.debug "Generating 8 bytes of IV"
      @spec.iv = Ccrypto::Java::SecureRandomEngine.random_bytes(8)
    else
      teLogger.debug "Using given IV"
    end
    ivParam = javax.crypto.spec.IvParameterSpec.new(@spec.iv)

  elsif @spec.is_mode?(:cbc) or @spec.is_mode?(:ctr) or @spec.is_mode?(:cfb) or @spec.is_mode?(:ofb)
    if is_empty?(@spec.iv)
      teLogger.debug "Generating 16 bytes of IV" 
      @spec.iv = Ccrypto::Java::SecureRandomEngine.random_bytes(16)
    else
      teLogger.debug "Using given IV"
    end
    ivParam = javax.crypto.spec.IvParameterSpec.new(@spec.iv)

  end

  #teLogger.debug "IV : #{@spec.iv}"

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

  #teLogger.debug "SKey : #{skey.encoded}"

  case @spec.cipherOps
  when :encrypt, :enc
    if ivParam.nil?
      teLogger.debug "Encryption mode"
      @cipher.init(javax.crypto.Cipher::ENCRYPT_MODE, skey)
    else
      teLogger.debug "Encryption mode with IV"
      @cipher.init(javax.crypto.Cipher::ENCRYPT_MODE, skey, ivParam)
    end

  when :decrypt, :dec
    if ivParam.nil?
      teLogger.debug "Decryption mode"
      @cipher.init(javax.crypto.Cipher::DECRYPT_MODE, skey)
    else
      teLogger.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_mode?(:gcm) and not_empty?(@spec.auth_data)
    teLogger.debug "Adding additional authenticated data for GCM mode"
    @cipher.updateAAD(to_java_bytes(@spec.auth_data))
  end

end

Class Method Details

.is_supported_cipher?(c) ⇒ Boolean

Returns:

  • (Boolean)

18
19
20
21
22
23
24
25
26
27
28
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 18

def self.is_supported_cipher?(c)
  case c
  when String, java.lang.String
    javax.crypto.Cipher.getInstance(c)
  when Hash
    spec = to_spec(c)
    javax.crypto.Cipher.getInstance(spec)
  else
    raise CipherEngineException, "Unsupported input #{c} to check supported cipher"
  end
end

.supported_ciphersObject


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

def self.supported_ciphers
  res = java.security.Security.getAlgorithms("Cipher").to_a.delete_if { |e| e.include?(".") }.sort
end

.to_spec(hash) ⇒ Object


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

def self.to_spec(hash)
  res = []
  res << hash[:algo].to_s
  res << hash[:mode].to_s
  res << hash[:padding].to_s
  res.join("/")
end

Instance Method Details

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


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

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

  begin
    res = @cipher.doFinal

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

    if @spec.is_mode?(:gcm) and @spec.is_encrypt_cipher_mode?
      # extract auth_tag
      @spec.auth_tag = res[-16..-1]
      @spec.auth_tag = String.from_java_bytes(@spec.auth_tag) if not_empty?(@spec.auth_tag)
    end 

    baos.write(res) if not_empty?(res)
    baos.toByteArray

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

#resetObject


214
215
216
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 214

def reset
  #@cipher.reset
end

#supported_ciphersObject


38
39
40
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 38

def supported_ciphers
  self.class.supported_ciphers
end

#update(val) ⇒ Object


177
178
179
180
181
182
183
184
185
186
# File 'lib/ccrypto/java/engines/cipher_engine.rb', line 177

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