Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions lib/aes/aes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def random_iv

# Generate a random key
def random_key(length=256)
_random_seed.unpack('H*')[0][0..((length/8)-1)]
_random_seed.unpack('H*')[0][0..((length/4)-1)]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The key as generated by _random_seed is a hex string. In a hex string, each character encodes 4 bits.

end

private
Expand All @@ -94,8 +94,7 @@ def _random_seed(size=32)
if defined? OpenSSL::Random
return OpenSSL::Random.random_bytes(size)
else
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
(1..size).collect{|a| chars[rand(chars.size)] }.join
(1..size).collect{ rand(256).chr }.join
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When using a modulo based upon a-z,A-Z,0-9 which comprises 62 characters, this effectively yields log2(62) (about 5.95) bits per character of randomness. rand(256) will yield a full 8 bits per character, inline with what OpenSSL::Random.random_bytes would return.

end
end

Expand Down
4 changes: 2 additions & 2 deletions test/test_aes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ class TestAES < Test::Unit::TestCase
end

should "generate a new key when AES#key" do
assert_equal 32, AES.key.length
assert_equal 44, AES.key(256, :base_64).length
assert_equal 64, AES.key.length
assert_equal 89, AES.key(256, :base_64).length
end

end