Module: ShadowsocksRuby::Cipher

Extended by:
Cipher
Included in:
Cipher
Defined in:
lib/shadowsocks_ruby/cipher/cipher.rb,
lib/shadowsocks_ruby/cipher/table.rb,
lib/shadowsocks_ruby/cipher/rbnacl.rb,
lib/shadowsocks_ruby/cipher/openssl.rb,
lib/shadowsocks_ruby/cipher/rc4_md5.rb

Overview

This module provide classes to encapsulate different underlying crypto library, and use them with an unique interface.

It also provide some useful utility functions like #hmac_sha1_digest and #bytes_to_key.

Note: All instance methods in this namespace can be used as class methods.

Examples:

# Demonstrate how to build a cipher object and it's typical use case.
cipher = ShadowsocksRuby::Cipher.build('aes-256-cfb', 'secret123')
iv = cipher.random_iv
encrypted_text = cipher.encrypt("hello world!", iv)
puts cipher.decrypt(encrypted_text, iv) # hello world!

Defined Under Namespace

Classes: OpenSSL, RC4_MD5, RbNaCl, Table

Instance Method Summary collapse

Instance Method Details

#build(method, password) ⇒ OpenSSL, ...

Builder for cipher object

Supported methods are:

  • table

  • rc4-md5

  • chacha20, chacha2-ietf, salsa20 which are provided by RbNaCl

  • All cipher methods supported by openssl (aes-256-cfb, aes-256-ctr, etc.)

    # To get a full list of all cipher methods supported by ruby gems OpenSSL, use
    ruby -e "require 'openssl'; puts OpenSSL::Cipher.ciphers"
    

Parameters:

  • method (String)

    Cipher methods

  • password (String)

    Password

Returns:


35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/shadowsocks_ruby/cipher/cipher.rb', line 35

def build method, password
  case method
  when 'table'
    ShadowsocksRuby::Cipher::Table.new password
  when 'rc4-md5'
    ShadowsocksRuby::Cipher::RC4_MD5.new password
  when 'chacha20','chacha20-ietf','salsa20'
    ShadowsocksRuby::Cipher::RbNaCl.new method, password
  else
    ShadowsocksRuby::Cipher::OpenSSL.new method, password
  end
end

#bytes_to_key(password, key_len, iv_len) ⇒ String

Equivalent to OpenSSL's EVP_BytesToKey() with count = 1

Parameters:

  • password (String)

    Password bytes

  • key_len (Integer)

    Key length, the length of key bytes to generate

  • iv_len (Integer)

    IV length, needed by internal algorithm

Returns:

  • (String)

    Key bytes, of key_len length


64
65
66
# File 'lib/shadowsocks_ruby/cipher/cipher.rb', line 64

def bytes_to_key(password, key_len, iv_len)
  bytes_to_key1(nil, password, 1, key_len, iv_len)[0]
end

#hmac_sha1_digest(key, message) ⇒ String

Generate first 10 bytes of HMAC using sha1 Digest

Parameters:

  • key (String)

    Key, use #bytes_to_key to convert a password to key if you need

  • message (String)

    Message to digest

Returns:

  • (String)

    Digest, only first 10 bytes


53
54
55
56
# File 'lib/shadowsocks_ruby/cipher/cipher.rb', line 53

def hmac_sha1_digest(key, message)
  @digest ||= ::OpenSSL::Digest.new('sha1')
  ::OpenSSL::HMAC.digest(@digest, key, message)[0,10]
end