Class: Ccrypto::Ruby::CipherEngine

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

Constant Summary collapse

NotAbleToFigureOutOnOpenSSLv2 =
[
  "aes-128-cbc-hmac-sha1",
  "aes-256-cbc-hmac-sha1",
  "aes-128-cbc-hmac-sha256",
  "aes-256-cbc-hmac-sha256",
  "aes-128-ccm",
  "aes-192-ccm",
  "aes-256-ccm",
  "aria-128-ccm",
  "aria-192-ccm",
  "aria-256-ccm",
  "rc4-hmac-md5"
]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DataConversion

#from_b64, #from_hex, included, #to_b64, #to_hex, #to_int_array

Constructor Details

#initialize(*args, &block) ⇒ CipherEngine

self.to_openssl_spec(spec)

Raises:

  • (Ccrypto::CipherEngineException)


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
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 193

def initialize(*args, &block)

  @spec = args.first

  raise Ccrypto::CipherEngineException, "Not supported cipher spec #{@spec.class}" if not @spec.is_a?(Ccrypto::CipherConfig)

  teLogger.debug "Cipher spec : #{@spec} (Native algo : #{@spec.native_config[:algo_str]})"

  @cipher = OpenSSL::Cipher.new(@spec.native_config[:algo_str])

  case @spec.cipherOps
  when :encrypt, :enc
    teLogger.debug "Operation encrypt"
    @cipher.encrypt
  when :decrypt, :dec
    teLogger.debug "Operation decrypt"
    @cipher.decrypt
  else
    raise Ccrypto::CipherEngineException, "Cipher operation (encrypt/decrypt) must be given"
  end


  if @spec.has_iv?
    teLogger.debug "IV from spec"
    @cipher.iv = @spec.iv
    teLogger.debug "IV : #{to_hex(@spec.iv)} / #{@spec.iv.length}"
  else
    teLogger.debug "Generate random IV"
    @spec.iv = @cipher.random_iv
    teLogger.debug "IV : #{to_hex(@spec.iv)} / #{@spec.iv.length}"
  end


  if @spec.has_key?
    teLogger.debug "Key from spec"
    case @spec.key
    when Ccrypto::SecretKey
      @cipher.key = @spec.key.to_bin
    when String
      @cipher.key = @spec.key
    else
      raise Ccrypto::CipherEngineException, "Unknown key type for processing #{@spec.key}"
    end
  else
    teLogger.debug "Generate random Key"
    @spec.key = @cipher.random_key
  end


  if @spec.is_mode?(:ccm)
    #if not_empty?(@spec.auth_data)
      if @spec.is_encrypt_cipher_mode?
        teLogger.debug "Setting ccm plaintext data length (ccm mode) [#{@spec.plaintext_length}]"
        @cipher.ccm_data_len = @spec.plaintext_length
        teLogger.debug "Setting auth data (ccm mode)"
        @cipher.auth_data = @spec.auth_data.nil? ? "" : @spec.auth_data
        teLogger.debug "Setting auth tag len (ccm mode)"
        @cipher.auth_tag_len = 12
      elsif @spec.is_decrypt_cipher_mode?
        teLogger.debug "Setting ccm cipher data length (ccm mode) #{@spec.ciphertext_length}"
        @cipher.ccm_data_len = @spec.ciphertext_length
        teLogger.debug "Setting auth data (ccm mode)"
        @cipher.auth_data = @spec.auth_data.nil? ? "" : @spec.auth_data
        teLogger.debug "Setting auth tag (ccm mode)"
        @cipher.auth_tag = @spec.auth_tag
      end
    #end


  elsif @spec.is_auth_mode_cipher?

    if not_empty?(@spec.auth_data) and not ((@spec.is_mode?("cbc-hmac-sha1") or @spec.is_mode?("cbc-hmac-sha256")))
      teLogger.debug "Setting auth data (generic mode)"
      @cipher.auth_data = @spec.auth_data

      if @spec.is_decrypt_cipher_mode?
        teLogger.debug "Setting auth tag (generic mode)"
        raise CipherEngineException, "Tag length of 16 bytes is expected" if @spec.auth_tag.bytesize != 16 and @spec.is_mode?(:gcm)
        @cipher.auth_tag = @spec.auth_tag
      end
    end

  end


end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mtd, *args, &block) ⇒ Object



319
320
321
322
323
324
325
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 319

def method_missing(mtd, *args, &block)
  if not @cipher.nil?
    @cipher.send(mtd, *args, &block)
  else
    super
  end
end

Class Method Details

.get_cipher(algo, keysize = nil, mode = nil) ⇒ Object Also known as: get_cipher_config



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 136

def self.get_cipher(algo, keysize = nil, mode = nil)
  supported_ciphers if Ccrypto::SupportedCipherList.instance.algo_count == 0

  if is_empty?(algo)
    []
  elsif is_empty?(keysize) and is_empty?(mode)
    teLogger.debug "get_cipher algo #{algo} only"
    Ccrypto::SupportedCipherList.instance.find_algo(algo)
  elsif is_empty?(mode) and not_empty?(keysize)
    teLogger.debug "get_cipher algo #{algo} keysize #{keysize}"
    Ccrypto::SupportedCipherList.instance.find_algo_keysize(algo, keysize)
  elsif not_empty?(mode) and is_empty?(keysize)
    teLogger.debug "get_cipher algo #{algo} mode #{mode}"
    Ccrypto::SupportedCipherList.instance.find_algo_mode(algo, mode)
  elsif not_empty?(keysize) and not_empty?(mode)
    teLogger.debug "get_cipher #{algo}/#{keysize}/#{mode}"
    Ccrypto::SupportedCipherList.instance.find_algo_keysize_mode(algo, keysize, mode)
  end
end

.is_supported_cipher?(c) ⇒ Boolean

Returns:

  • (Boolean)


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 164

def self.is_supported_cipher?(c)
  case c
  when String
    supported_ciphers if @sCipherStr.nil?

    if not @sCipherStr.nil?
      @sCipherStr.include?(C)
    else
      false
    end
  when Ccrypto::CipherConfig
    @sCipher.include?(c)
  else
    raise Ccrypto::CipherEngineException, "Unsupported input #{c} to check supported cipher"
  end
end

.supported_cipher_listObject



159
160
161
162
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 159

def self.supported_cipher_list
  supported_ciphers if Ccrypto::SupportedCipherList.instance.algo_count == 0
  Ccrypto::SupportedCipherList.instance
end

.supported_ciphersObject

CherryPick = [

"aes-128-cbc", "aes-192-cbc", "aes-256-cbc",
"aes-128-gcm", "aes-192-gcm", "aes-256-gcm",
"aria-128-cbc","aria-192-cbc", "aria-256-cbc",
"aria-128-gcm","aria-192-gcm", "aria-256-gcm",
"camellia-128-cbc","camellia-192-cbc", "camellia-256-cbc",
"camellia-128-ctr","camellia-192-ctr", "camellia-256-ctr",
"chacha20-poly1305"

]



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

def self.supported_ciphers
  if @sCipher.nil?
    @sCipherStr = []
    @sCipher = []

    OpenSSL::Cipher.ciphers.each do |c|
      
      teLogger.debug "found cipher : #{c}"
      next if c =~ /^id-\w*/ 
      teLogger.debug "loading cipher : #{c}"

      if OpenSSL::VERSION < "3.0.0" and NotAbleToFigureOutOnOpenSSLv2.include?(c)
        teLogger.debug "Running on OpenSSL < v3. Skipping cipher #{c}"
        next
      end

      begin
        co = OpenSSL::Cipher.new(c)
        #teLogger.debug "Algo #{c} : authenticated? #{co.authenticated?}"
        #p co.methods.sort
        cc = c.split("-")
        @sCipherStr << c
        
        algo = cc.first
        exclusion = ["chacha20","sm4"]
        # to find string like aes128, aes256 from openssl
        if not exclusion.include?(algo) and (algo =~ /[0-9]/) != nil
          # match the one before the numbers
          algo = $` 
        end

        native = { algo_str: c }
        keysize = co.key_len*8
        opts = { keysize: keysize, ivLength: co.iv_len, authMode: co.authenticated? }

        if c.downcase =~ /\w*(gcm|ecb|cbc|cfb|cfb1|cfb8|ofb|ctr|ccm|xts|wrap|poly1305)/
          teLogger.debug "Mode extraction : #{$&} / #{$'}"
          # after the match
          if not_empty?($')
            opts[:mode] = "#{$&}#{$'}"
          else
            # the match
            opts[:mode] = $&.downcase
          end
        else
          # no mode defined. Seems defaulted to cbc according to document
          if co.authenticated?
            opts[:mode] = "gcm"
          else
            opts[:mode] = "cbc"
          end
        end

        teLogger.debug "Mode : #{opts[:mode]}"
        if opts[:mode] == :xts.to_s
          opts[:min_input_length] = 16
        elsif opts[:mode] == "cbc-hmac-sha1"
          opts[:min_input_length] = 16
          opts[:mandatory_block_size] = 16
        elsif opts[:mode] == "cbc-hmac-sha256"
          opts[:min_input_length] = 32
          opts[:mandatory_block_size] = 32
        elsif opts[:mode] == "wrap"
          case algo
          when "aes"
            case keysize
            when 128
              opts[:min_input_length] = 16
              opts[:mandatory_block_size] = 8
            when 192
              opts[:min_input_length] = 24
              opts[:mandatory_block_size] = 8
            when 256
              opts[:min_input_length] = 32
              opts[:mandatory_block_size] = 8
            end
          when "des3", "des"
            opts[:min_input_length] = 8
            opts[:mandatory_block_size] = 8
          end
        end

        conf = Ccrypto::CipherConfig.new(algo, opts)
        conf.native_config = native

        Ccrypto::SupportedCipherList.instance.register(conf)

        @sCipher << conf
      rescue OpenSSL::Cipher::CipherError => ex
        teLogger.debug "Algo '#{c}' hit error : #{ex.message}"
      end
    end
  end

  @sCipher

end

.to_openssl_spec(spec) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 181

def self.to_openssl_spec(spec)

  case spec
  when Ccrypto::CipherConfig
    spec.native_config[:algo_str]
    #@sCipher[spec]
  else
    raise Ccrypto::Error, "Unknown spec #{spec.inspect}"
  end

end

Instance Method Details

#final(val = nil) ⇒ Object



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

def final(val = nil)
  res = []

  begin

    if not_empty?(val)
      teLogger.debug "(final) Written #{val.length} bytes"
      res << @cipher.update(val) 
    end

    res << @cipher.final
    teLogger.debug "(final) cipher finalized"

  rescue Exception => ex
    teLogger.error self
    teLogger.error ex.backtrace.join("\n")
    raise CipherEngineException, ex
  end

  #if @spec.is_mode?(:gcm)
  if @spec.is_auth_mode_cipher? and @spec.is_encrypt_cipher_mode?
    @spec.auth_tag = @cipher.auth_tag
  end

  res.join
end

#resetObject



315
316
317
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 315

def reset
  @cipher.reset
end

#update(val) ⇒ Object

initialize



280
281
282
283
284
285
286
# File 'lib/ccrypto/ruby/engines/cipher_engine.rb', line 280

def update(val)
  if not_empty?(val)
    res = @cipher.update(val) 
    teLogger.debug "(update) Written #{val.length} bytes"
    res
  end
end