Module: SagepayProtocol3::Encryption

Extended by:
Encryption
Included in:
Encryption
Defined in:
lib/sagepay_protocol3/encryption.rb

Instance Method Summary collapse

Instance Method Details

#cipher(operation, cipher, cipher_key) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/sagepay_protocol3/encryption.rb', line 8

def cipher(operation, cipher, cipher_key)
  lambda do |data, padding|
    c = OpenSSL::Cipher.new(cipher)
    c.send(operation)
    c.padding = padding
    c.key = cipher_key
    c.iv = cipher_key
    c.update(data) + c.final
  end
end

#decrypt(cipher_key, data, cipher = "AES-128-CBC") ⇒ Object



19
20
21
22
23
24
# File 'lib/sagepay_protocol3/encryption.rb', line 19

def decrypt(cipher_key, data, cipher = "AES-128-CBC")
  hex = data.gsub(/\A(@)/, '')
  input = [hex].pack('H*')
  output = cipher(:decrypt, cipher, cipher_key)[input, 0]
  sanitize_payload output
end

#encrypt(cipher_key, data, cipher = "AES-128-CBC") ⇒ Object



26
27
28
29
# File 'lib/sagepay_protocol3/encryption.rb', line 26

def encrypt(cipher_key, data, cipher = "AES-128-CBC")
  _encrypted = cipher(:encrypt, cipher, cipher_key)[data, 1]
  "@#{_encrypted.unpack('H*').first.upcase}"
end

#sanitize_payload(string) ⇒ Object



31
32
33
# File 'lib/sagepay_protocol3/encryption.rb', line 31

def sanitize_payload(string)
  string.gsub(/\005/, '').gsub("\r", '').gsub("\n", '')
end

#to_h(crypt_string) ⇒ Object



35
36
37
# File 'lib/sagepay_protocol3/encryption.rb', line 35

def to_h(crypt_string)
  Hash[*crypt_string.split(/[=&]/)]
end