Class: ChaCha20
- Inherits:
-
Object
- Object
- ChaCha20
- Defined in:
- lib/chacha20/chacha20.rb,
ext/chacha20/chacha20_bindings.c
Instance Method Summary collapse
- #encrypt(input) ⇒ Object (also: #decrypt)
- #init_nonce(nonce) ⇒ Object
-
#initialize(key, nonce = nil) ⇒ ChaCha20
constructor
A new instance of ChaCha20.
- #initialized? ⇒ Boolean
- #nonce ⇒ Object
- #seek(position) ⇒ Object
Constructor Details
#initialize(key, nonce = nil) ⇒ ChaCha20
Returns a new instance of ChaCha20.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/chacha20/chacha20.rb', line 2 def initialize(key, nonce = nil) if nonce.nil? @nonce_initialized = false nonce = "\x00".b * 8 else @nonce_initialized = true end raise TypeError, "key must be a String" unless key.is_a? String raise TypeError, "nonce must be a String" unless nonce.is_a? String raise ArgumentError, "key must be 32 bytes" unless key.bytesize == 32 raise ArgumentError, "nonce must be 8 bytes" unless nonce.bytesize == 8 @block_offset = 0 init_context(key, nonce) end |
Instance Method Details
#encrypt(input) ⇒ Object Also known as: decrypt
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/chacha20/chacha20.rb', line 47 def encrypt(input) raise "nonce has not been initialized" unless @nonce_initialized raise ArgumentError, "plaintext must be a string" unless input.is_a?(String) length = input.bytesize result = "\x00".b * @block_offset + input result = encrypt_or_decrypt(result) result = result.slice(@block_offset, length) @block_offset = (@block_offset + length) % 64 set_counter(get_counter - 1) unless @block_offset.zero? result end |
#init_nonce(nonce) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/chacha20/chacha20.rb', line 21 def init_nonce(nonce) raise "nonce has already been initialized" if @nonce_initialized raise TypeError, "nonce must be a String" unless nonce.is_a? String raise ArgumentError, "nonce must be 8 bytes" unless nonce.bytesize == 8 @nonce_initialized = true set_nonce(nonce) end |
#initialized? ⇒ Boolean
35 36 37 |
# File 'lib/chacha20/chacha20.rb', line 35 def initialized? @nonce_initialized end |
#nonce ⇒ Object
30 31 32 33 |
# File 'lib/chacha20/chacha20.rb', line 30 def nonce raise "nonce has not been initialized" unless @nonce_initialized get_nonce end |
#seek(position) ⇒ Object
39 40 41 42 43 44 45 |
# File 'lib/chacha20/chacha20.rb', line 39 def seek(position) raise "nonce has not been initialized" unless @nonce_initialized raise ArgumentError, "position must be a non-negative integer" unless position.is_a?(Integer) && position >= 0 set_counter(position / 64) @block_offset = position % 64 end |