my goal is to implement a random number generator based on AES Counter Mode in Ruby.
I have implemented the counter mode myself as follows:
require './aes_helpers'
require 'openssl'
class AES_CTR_Random
# Setup basic aes, since a mode is required ecb is used,
# which constructs same cipher text blocks for same plain text blocks
def intialize_openssl_aes(encrypt_or_decrypt, mode, key, iv, data, bits)
key_s = byte_array_to_byte_string(key)
data_s = byte_array_to_byte_string(data)
aes = OpenSSL::Cipher::AES.new(bits, mode)
aes.send(encrypt_or_decrypt)
aes.padding = 0
aes.key = key_s
aes.iv = byte_array_to_byte_string(iv) if iv
encrypted = aes.update(data_s) + aes.final
byte_string_to_byte_array(encrypted)
end
# Encrypt or decrypt one AES block
def process_aes_block(encrypt_or_decrypt, key, block)
intialize_openssl_aes(encrypt_or_decrypt, 'ECB', key, nil, block, 128)
end
# Generate a stream cipher key using given AES key and initialization vector
def generate_aes_ctr_stream_key(key, iv, length)
iv = byte_array_to_integer(iv)
stream_key = []
while stream_key.length < length
stream_key += process_aes_block(:encrypt, key, integer_to_byte_array(iv))
iv += 1
end
stream_key.take(length)
end
# Run Cipher Counter Mode
def run_ctr(key, iv, data)
# Get a properly sized stream cipher key using aes cipher counter mode
stream_key = generate_aes_ctr_stream_key(key, iv, data.length)
# Stream cipher decryption
byte_array_xor_byte_array(stream_key, data)
end
# Encrypt plaintext with aes 128 ctr using given key and iv
def encrypt_ctr(key, iv, plaintext)
key = hexadecimal_string_to_byte_buffer(key)
iv = hexadecimal_string_to_byte_buffer(iv)
plaintext = byte_string_to_byte_array(plaintext)
encrypted = run_ctr(key, iv, plaintext)
byte_buffer_to_hexadecimal_string(iv + encrypted)
end
# Decrypt aes 128 ctr encrypted ciphertext
def decrypt_ctr(key, ciphertext)
key = hexadecimal_string_to_byte_buffer(key)
ciphertext = hexadecimal_string_to_byte_buffer(ciphertext)
iv = ciphertext.take(16)
ciphertext = ciphertext.drop(16)
plaintext = run_ctr(key, iv, ciphertext)
byte_array_to_byte_string(plaintext)
end
end
But now I do not quite understand how to get random numbers out of this implementation.
Can anyone guide me to an solution?
Aucun commentaire:
Enregistrer un commentaire