Class: Encrypted::CBC

Inherits:
Object
  • Object
show all
Defined in:
lib/encrypted/cbc.rb

Constant Summary collapse

Use_getbyte =

YARV (1.9) compat

"".respond_to?(:getbyte)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cipher) ⇒ CBC

Returns a new instance of CBC.



29
30
31
# File 'lib/encrypted/cbc.rb', line 29

def initialize(cipher)
    @cipher=cipher
end

Class Method Details

.pad_pkcs5(string, to_length) ⇒ Object

:nodoc:



9
10
11
12
13
# File 'lib/encrypted/cbc.rb', line 9

def CBC.pad_pkcs5(string, to_length) #:nodoc:
    diff= to_length - (string.length % to_length)
    string+=[diff].pack("C") * diff
    return string
end

.unpad_pkcs5(string) ⇒ Object

:nodoc:



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/encrypted/cbc.rb', line 15

def CBC.unpad_pkcs5(string) #:nodoc:
    return unless string.length > 0
    
    if(Use_getbyte) # 1.9 returns a string from []
      pad_len = string.getbyte(-1)
    else
      pad_len = string[-1]
    end
    unless(string.slice!(-pad_len .. -1) == [pad_len].pack("C") * pad_len)
        raise "Unpad failure: trailing junk found"
    end
    return string
end

Instance Method Details

#decrypt(iv, ciphertext) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/encrypted/cbc.rb', line 49

def decrypt(iv, ciphertext)
    block_size=iv.length

    last_block_e=Encrypted::ByteStream.new(iv)

    unless(ciphertext.length % block_size==0)
        raise "Bad IV: doesn't match ciphertext length"
    end
    
    r_data="-" * ciphertext.length
    j=0
    ct_l = ciphertext.length
    current_block = "-" * block_size
    while(j<ct_l)
        current_block=ciphertext[j, block_size]

        r_data[j, block_size]=last_block_e^@cipher.decrypt(current_block)
        last_block_e[0,block_size]=current_block
        j+=block_size
    end
    r_data=CBC.unpad_pkcs5(r_data)
    return r_data
end

#encrypt(iv, plaintext) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/encrypted/cbc.rb', line 32

def encrypt(iv, plaintext)
    block_size=iv.length
            
    last_block_e=Encrypted::ByteStream.new(iv)
    
    plaintext=CBC.pad_pkcs5(plaintext, iv.length)
    r_data="-" * plaintext.length
    
    j=0
    pt_l = plaintext.length
    while(j<pt_l)
        last_block_e[0,block_size]=@cipher.encrypt(last_block_e^plaintext[j, block_size])
        r_data[j, block_size]=last_block_e
        j+=block_size
    end
    return r_data
end