Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/lib/rex/crypto/chacha20.rb
Views: 11779
# -*- coding: binary -*-12module Rex3module Crypto4class Chacha205attr_reader :chacha_ctx67def initialize(key, iv)8raise TypeError unless key.is_a? String9raise TypeError unless iv.is_a? String1011@chacha_ctx = chacha20_ctx_setup(key, iv)12end1314def reset_cipher(key, iv)15@chacha_ctx = chacha20_ctx_setup(key, iv)16end1718def chacha20_update_ctx19@chacha_ctx[12] = (@chacha_ctx[12] + 1) & 0xffffffff20end2122def chacha20_ctx_setup(key, iv, position=1)23chacha_constants = [1634760805, 857760878, 2036477234, 1797285236]24chacha_ctx = chacha_constants2526chacha_ctx += key.unpack('V8')27chacha_ctx[12] = position28chacha_ctx += iv.unpack('VVV')2930chacha_ctx31end3233def chacha20_crypt(data)34num_blocks = data.length / 6435if data.length % 64 != 036num_blocks += 137end3839keystream = []40(1..num_blocks).each do |block|41keystream << chacha20_block_func42chacha20_update_ctx43end44keystream = keystream.flatten4546enc = []47i = 048data.unpack("c*").each do |a|49enc << (a.ord ^ keystream[i])50i += 151end52enc.pack("c*").force_encoding('ASCII-8BIT')53end5455def chacha20_block_func56chacha_state = @chacha_ctx.dup5758(1..10).each do |round|59quarter_round(chacha_state, 0, 4, 8, 12)60quarter_round(chacha_state, 1, 5, 9, 13)61quarter_round(chacha_state, 2, 6, 10, 14)62quarter_round(chacha_state, 3, 7, 11, 15)63quarter_round(chacha_state, 0, 5, 10, 15)64quarter_round(chacha_state, 1, 6, 11, 12)65quarter_round(chacha_state, 2, 7, 8, 13)66quarter_round(chacha_state, 3, 4, 9, 14)67end6869keystream_arr = []70(0..15).each do |index|71keystream_ch = (chacha_state[index] + @chacha_ctx[index]) & 0xffffffff72keystream_arr << (keystream_ch & 0xff)73keystream_arr << (keystream_ch >> 8 & 0xff)74keystream_arr << (keystream_ch >> 16 & 0xff)75keystream_arr << (keystream_ch >> 24 & 0xff)76end7778keystream_arr79end8081def rotate(v, c)82((v << c) & 0xffffffff) | v >> (32 - c)83end8485def quarter_round(x, a, b, c, d)86x[a] = (x[a] + x[b]) & 0xffffffff87x[d] = rotate(x[d] ^ x[a], 16)88x[c] = (x[c] + x[d]) & 0xffffffff89x[b] = rotate(x[b] ^ x[c], 12)90x[a] = (x[a] + x[b]) & 0xffffffff91x[d] = rotate(x[d] ^ x[a], 8)92x[c] = (x[c] + x[d]) & 0xffffffff93x[b] = rotate(x[b] ^ x[c], 7)94end95end96end97end9899100