Class: ShadowsocksRuby::Cipher::RbNaCl

Inherits:
Object
  • Object
show all
Defined in:
lib/shadowsocks_ruby/cipher/rbnacl.rb

Overview

Encapsulate RbNaCl ruby library, cipher methods provided by this Class are:

  • chacha20 – ChaCha20Poly1305Legacy without ad

  • chacha2-ietf – ChaCha20Poly1305IETF without ad

  • salsa20 – XSalsa20Poly1305 without ad

Normally you should use #build to get an instance of this class.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method, password) ⇒ Object

Parameters:

  • method (String)

    Cipher methods

  • password (String)

    Password



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/shadowsocks_ruby/cipher/rbnacl.rb', line 18

def initialize method, password
  klass = case method
    when 'chacha20'
      ::RbNaCl::AEAD::ChaCha20Poly1305Legacy
    when 'chacha20-ietf'
      ::RbNaCl::AEAD::ChaCha20Poly1305IETF
    when 'salsa20'
      ::RbNaCl::SecretBoxes::XSalsa20Poly1305
    else
      raise CipherError, "unsupported method: " + method
    end
  key_len = klass.key_bytes
  iv_len = klass.nonce_bytes
  @key = ShadowsocksRuby::Cipher.bytes_to_key(password, key_len, iv_len)
  @cipher = klass.new(@key)
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



16
17
18
# File 'lib/shadowsocks_ruby/cipher/rbnacl.rb', line 16

def key
  @key
end

Instance Method Details

#decrypt(message, iv) ⇒ String

Decrypt message by provided IV

Parameters:

  • message (String)
  • iv (String)

Returns:

  • (String)

    Decrypted Message



50
51
52
53
54
55
56
# File 'lib/shadowsocks_ruby/cipher/rbnacl.rb', line 50

def decrypt(message, iv)
  if @cipher.class == ::RbNaCl::SecretBoxes::XSalsa20Poly1305
    @cipher.decrypt(iv, message)
  else
    @cipher.decrypt(iv, message, nil)
  end
end

#encrypt(message, iv) ⇒ String

Encrypt message by provided IV

Parameters:

  • message (String)
  • iv (String)

Returns:

  • (String)

    Encrypted Message



41
42
43
44
45
46
47
# File 'lib/shadowsocks_ruby/cipher/rbnacl.rb', line 41

def encrypt(message, iv)
  if @cipher.class == ::RbNaCl::SecretBoxes::XSalsa20Poly1305
    @cipher.encrypt(iv, message)
  else
    @cipher.encrypt(iv, message, nil)
  end
end

#iv_lenInteger

Get the cipher object’s IV length

Returns:

  • (Integer)


59
60
61
# File 'lib/shadowsocks_ruby/cipher/rbnacl.rb', line 59

def iv_len
  @cipher.iv_bytes
end

#random_ivString

Generate a random IV for the cipher method

Returns:

  • (String)

    random IV of the length of the cipher method



36
37
38
# File 'lib/shadowsocks_ruby/cipher/rbnacl.rb', line 36

def random_iv
  ::RbNaCl::Random.random_bytes(@cipher.nonce_bytes)
end