Sha256: bb4f26f2857f980558decef99edb2e56a0f4baf3b04f874bf71aeae76297841e

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

require "openssl"
require "base64"
require "digest/sha2"

class KVM::Wallet 
  attr_accessor :data

  def initialize(file, rsa_key)
    @file = file
    @rsa_key = rsa_key
    # create a 256-bit key out of private key data
    @key = Digest::SHA256.digest(File.read(rsa_key))
    self.load
  end
  
  def load
    @data ||= Marshal.load(decrypt)
  end
  
  def save
    encrypt(Marshal.dump(@data))
  end
  
  protected
 
  def encrypt(data)
    cipher = OpenSSL::Cipher::Cipher.new('aes-256-ecb')
    cipher.encrypt
    cipher.key = @key

    encrypted_data = cipher.update(data) # Encrypt the data.
    encrypted_data << cipher.final

    File.open(@file, "w") do |f|
      f << strict_encode64(encrypted_data)
    end
  end
  
  def decrypt
    return Marshal.dump({}) unless File.file?(@file)
  
    encrypted_data = strict_decode64(File.open(@file, "rb").read)

    cipher = OpenSSL::Cipher::Cipher.new('aes-256-ecb')
    cipher.decrypt
    cipher.key = @key

    data = cipher.update(encrypted_data)
    data << cipher.final
    
    data
  end
  
  protected
  
  # re-implement, jruby does not have this
  # http://jira.codehaus.org/browse/JRUBY-4717
  def strict_decode64(str)
    str.unpack("m0").first
  end
  def strict_encode64(bin)
    [bin].pack("m0")
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kvm-0.0.1.pre lib/kvm/wallet.rb