我的目标是在Ruby中实现基于AES计数器模式的随机数生成器。
我自己实施了计数器模式如下:
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
但现在我不太明白如何从这个实现中获取随机数。
有人可以指导我找到解决方案吗?
答案 0 :(得分:3)
您可以使用AES构建CTR_DRBG,如NIST Special Publication 800-90A第10.2节:10.2基于分组密码的DRBG机制中所述,它使用CTR分组密码操作模式作为基础原语。
流密码的缺点是它不会重复块,这可能会略微偏向输出。之前的回答提到了AES-CTR,它有这个缺点。