Debian Codegraph @

plugin/world/blowfish_ecb/lib/cipher.rb

raw symbols SCIP
1 require_relative 'ecb'
2 require_relative 'key'
3
4 module Blowfish::ECB
5 class Cipher
6 # call-seq:
7 # Blowfish::ECB::Cipher.new(string) -> Cipher
8 #
9 # Creates a Cipher instance with given key.
10 def initialize(key)
11 @key = Blowfish::ECB::Key.new(key)
12 end
13
14 # call-seq:
15 # cipher.encrypt(string) -> string
16 #
17 # Encrypts given data.
18 def encrypt(data)
19 bytes = data.unpack('C*')
20 pad_len = 8 - (bytes.size % 8)
21 bytes.push(*([pad_len] * pad_len))
22 Blowfish::ECB.encrypt(bytes.pack('C*'), @key)
23 end
24
25 # call-seq:
26 # cipher.decrypt(string) -> string
27 #
28 # Decrypts given data. The data must be in ASCII-8BIT encoding, since the
29 # encrypted data consists of arbitrary bytes. It is a sign of a bug if the
30 # encrypted data is encoded as if it was a human-readable text.
31 def decrypt(data)
32 if data.encoding != Encoding::ASCII_8BIT
33 raise "data.encoding must be ASCII-8BIT, but got: #{data.encoding}"
34 end
35
36 decoded = Blowfish::ECB.decrypt(data, @key)
37
38 # Last byte indicates the size of padding.
39 # Strip the padding from res accordingly.
40 pad_len = decoded[-1].unpack1('C')
41 decoded[0...-pad_len]
42 end
43 end
44 end