Method: Ccrypto::Ruby::CipherEngine#initialize

Defined in:
lib/ccrypto/ruby/engines/cipher_engine.rb

#initialize(*args, &block) ⇒ CipherEngine

Returns a new instance of CipherEngine.



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

def initialize(*args, &block)
  @spec = args.first

  #teLogger = TteLogger.new
  teLogger.debug "Cipher spec : #{@spec}"

  begin
    case @spec
    #when String
    #  @cipher = OpenSSL::Cipher.new(@spec)
    when Ccrypto::CipherEngineConfig
      @cipher = OpenSSL::Cipher.new(@spec.provider_config)
    when Ccrypto::DirectCipherConfig
      @cipher = OpenSSL::Cipher.new(self.class.to_openssl_spec(@spec))
    else
      raise Ccrypto::CipherEngineException, "Not supported cipher init type #{@spec.class}"
    end
  rescue OpenSSL::Cipher::CipherError, RuntimeError => ex
    raise Ccrypto::CipherEngineException, ex
  end

  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)}"
  else
    teLogger.debug "Generate random IV"
    @spec.iv = @cipher.random_iv
    teLogger.debug "IV : #{to_hex(@spec.iv)}"
  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?(:gcm)

    if not_empty?(@spec.auth_data) 
      teLogger.debug "Setting auth data"
      @cipher.auth_data = @spec.auth_data
    end

    if not_empty?(@spec.auth_tag) 
      raise CipherEngineException, "Tag length of 16 bytes is expected" if @spec.auth_tag.bytesize != 16
      teLogger.debug "Setting auth tag"
      @cipher.auth_tag = @spec.auth_tag
    end

  end

end