Class: EzCrypto::Key

Inherits:
Object show all
Defined in:
lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb

Overview

The Key is the only class you need to understand for simple use.

Algorithms

The crypto algorithms default to aes-128-cbc however on any of the class methods you can change it to one of the standard openssl cipher names using the optional :algorithm=>alg name parameter.

Eg.

Key.new @raw, :algorithm=>"des"
Key.generate :algorithm=>"blowfish"
Key.with_password @pwd,@salt,:algorithm=>"aes256"

License

ActiveCrypto and EzCrypto are released under the MIT license.

Support

To contact the author, send mail to [email protected]

Also see my blogs at: stakeventures.com and neubia.com

This project was based on code used in my project StakeItOut, where you can securely share web services with your partners. stakeitout.com

© 2005 Pelle Braendgaard

Constant Summary collapse

@@block_size =
512

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw, options = {}) ⇒ Key

Initialize the key with raw unencoded binary key data. This needs to be at least 16 bytes long for the default aes-128 algorithm.



68
69
70
71
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 68

def initialize(raw,options = {})
  @raw=raw
  @algorithm=options[:algorithm]||"aes-128-cbc"
end

Instance Attribute Details

#algorithmObject (readonly)

Returns the value of attribute algorithm.



45
46
47
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 45

def algorithm
  @algorithm
end

#rawObject (readonly)

Returns the value of attribute raw.



45
46
47
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 45

def raw
  @raw
end

Class Method Details

.block_sizeObject

Return the block-size for IO-operations.



59
60
61
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 59

def self.block_size
  @@block_size
end

.block_size=(size) ⇒ Object

Set the block-size for IO-operations (default: 512 bytes)



52
53
54
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 52

def self.block_size=(size)
  @@block_size = size
end

.calculate_key_size(algorithm) ⇒ Object

Given an algorithm this calculates the keysize. This is used by both the generate and with_password methods. This is not yet 100% complete.



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
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 123

def self.calculate_key_size(algorithm)
  if !algorithm.nil?
    algorithm=~/^([[:alnum:]]+)(-(\d+))?/
    if $3
      size=($3.to_i)/8
    else
      case $1
        when "bf"
          size = 16
        when "blowfish"
          size = 16
        when "des"
          size = 8
        when "des3"
          size = 24
        when "aes128"
          size = 16
        when "aes192"
          size = 24
        when "aes256"
          size = 32
        when "rc2"
          size = 16
        when "rc4"
          size = 16
        else
          size = 16
        end
    end
  end
  if size.nil?
    size = 16
  end

  size
end

.decode(encoded, options = {}) ⇒ Object

Initialize the key with Base64 encoded key data.



90
91
92
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 90

def self.decode(encoded,options = {})
  Key.new(Base64.decode64(encoded),options)
end

.decrypt_with_password(password, salt, data, options = {}) ⇒ Object

Decrypts the data with the given password and a salt. Short hand for:

key=Key.with_password(password,salt,options)
key.decrypt(data)


114
115
116
117
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 114

def self.decrypt_with_password(password,salt,data,options = {})
  key=Key.with_password(password,salt,options)
  key.decrypt(data)
end

.encrypt_with_password(password, salt, data, options = {}) ⇒ Object

Encrypts the data with the given password and a salt. Short hand for:

key=Key.with_password(password,salt,options)
key.encrypt(data)


101
102
103
104
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 101

def self.encrypt_with_password(password,salt,data,options = {})
  key=Key.with_password(password,salt,options)
  key.encrypt(data)
end

.generate(options = {}) ⇒ Object

Generate random key.



76
77
78
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 76

def self.generate(options = {})
  Key.new(EzCrypto::Digester.generate_key(calculate_key_size(options[:algorithm])),options)
end

.load(filename) ⇒ Object

Load a key from a yaml_file generated via Key#store.



290
291
292
293
294
295
296
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 290

def self.load(filename)
  require 'yaml'
  hash = YAML::load_file(filename)
  req = proc { |k| hash[k] or raise "Missing element #{k} in #{filename}" }
  key = self.new Base64.decode64(req.call(:key)) , :algorithm => req.call(:algorithm)
  return key
end

.with_password(password, salt, options = {}) ⇒ Object

Create key generated from the given password and salt



83
84
85
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 83

def self.with_password(password,salt,options = {})
  Key.new(EzCrypto::Digester.get_key(password,salt,calculate_key_size(options[:algorithm])),options)
end

Instance Method Details

#decrypt(data) ⇒ Object

Decrypts the data passed to it in binary format.



196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 196

def decrypt(data)
  if data==nil || data==""
    nil
  else
    decrypter("")
    @cipher.gulp(data)
  end
#    rescue
#      puts @algorithm
#      puts self.encode
#      puts data.size
#      throw $!
end

#decrypt64(data) ⇒ Object

Decrypts a Base64 formatted string



213
214
215
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 213

def decrypt64(data)
  decrypt(Base64.decode64(data))
end

#decrypt_file(src, tgt = nil, options = {}) ⇒ Object

Decrypt a file ‘inplace’ and remove a suffix see #cipher_file IMPORTANT: The inputfile will be deleted by default.



383
384
385
386
387
388
389
390
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 383

def decrypt_file(src, tgt=nil, options = {} )
  options = { :suffix => '.ez', :autoclean => 'true' }.update(options)
  unless tgt
    tgt = src
    tgt = tgt.gsub(/#{options[:suffix]}$/, '')
  end
  cipher_file :on_decrypter, src, tgt, options[:autoclean]
end

#decrypter(target = '') ⇒ Object

Get a Decrypter object. You have to call #final on it by yourself!



327
328
329
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 327

def decrypter(target='')
  @cipher = EzCrypto::Decrypter.new(self,target,@algorithm)
end

#encodeObject

returns the Base64 encoded key.



163
164
165
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 163

def encode
  Base64.encode64(@raw).chop
end

#encrypt(data) ⇒ Object

Encrypts the data and returns it in encrypted binary form.



177
178
179
180
181
182
183
184
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 177

def encrypt(data)
  if data==nil || data==""
    nil
  else
    encrypter("")
    @cipher.encrypt(data)
  end
end

#encrypt64(data) ⇒ Object

Encrypts the data and returns it in encrypted Base64 encoded form.



189
190
191
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 189

def encrypt64(data)
  Base64.encode64(encrypt(data))
end

#encrypt_file(src, tgt = nil, options = {}) ⇒ Object

Encrypt a file ‘inplace’ and add a suffix see #cipher_file. IMPORTANT: The inputfile will be deleted by default.



371
372
373
374
375
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 371

def encrypt_file(src, tgt=nil, options = {} )
  options = { :suffix => '.ez', :autoclean => 'true' }.update(options)
  tgt = "#{src}#{options[:suffix]}" unless tgt
  cipher_file :on_encrypter, src, tgt, options[:autoclean]
end

#encrypter(target = '') ⇒ Object

Get a Encrypter object. You have to call #final on it by yourself!



319
320
321
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 319

def encrypter(target='')
  @cipher = EzCrypto::Encrypter.new(self,target,@algorithm)
end

#marshal_dumpObject

Allows keys to be marshalled



220
221
222
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 220

def marshal_dump
   "#{self.algorithm}$$$#{self.encode}"
end

#marshal_load(s) ⇒ Object

Allows keys to be unmarshalled



227
228
229
230
231
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 227

def marshal_load(s) 
   a, r = s.split '$$$'
   @algorithm = a
   @raw = Base64.decode64(r)
end

#on_decrypter(target = '', &block) ⇒ Object

Create a Decrypter object and yield it to a block. You must not call #final by yourself, the method does this.



336
337
338
339
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 336

def on_decrypter(target='', &block)
  decrypter(target)
  on_cipher(&block)
end

#on_encrypter(target = '', &block) ⇒ Object

Create an Encrypter object and yield it to a block. You must not call #final by yourself, the method does this.



346
347
348
349
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 346

def on_encrypter(target='', &block)
  encrypter(target)
  on_cipher(&block)
end

#store(filename) ⇒ Object

Save the key data into a file, try to do this in a secure manner. NOTE: YAML::store & friends are not used to encance control over the generated file format.



304
305
306
307
308
309
310
311
312
313
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 304

def store(filename)
  safe_create(filename) do |f|
    selfenc = self.encode
    f.puts "---"
    f.puts ":EZCRYPTO KEY FILE: KEEP THIS SECURE !"
    f.puts ":created: #{Time.now}"
    f.puts ":algorithm: #{@algorithm}"
    f.puts ":key: #{selfenc}"
  end
end

#to_sObject

returns the Base64 encoded key. Synonym for encode.



170
171
172
# File 'lib/extensions/ezcrypto/ezcrypto/ezcrypto.rb', line 170

def to_s
  encode
end