user2974739
user2974739

Reputation: 639

Generate random string from key

What's the best way to create a random alphanumeric string given a key? I am using this

(0...50).map { ('a'..'z').to_a[rand(26)] }.join

but, I want a string based on a string such as "mysecretkey". I don't want to use encryption gems or Cipher, etc. I want to keep it simple like what I have, but adding a key to it.

Upvotes: 0

Views: 1147

Answers (2)

Neil Slater
Neil Slater

Reputation: 27207

I am assuming from your question that you want for some reason to associate an input string to a random-looking output, and to have it be the same output if the same key is presented.

The code below will generate the same "random" string for the same input secret key, accepting keys up to 8 * 624 = 4992 bytes long. Technically this is not random, but using Ruby's built in random number generator to hash the input string.

def rand_hash secret_key
  int_key = secret_key.unpack("C*").each_with_index.inject(0) do |sum, (byte, index)|
    sum + byte * (256 ** index)
  end
  r = Random.new( int_key )
 (0...50).map { ('a'..'z').to_a[ r.rand(26) ] }.join
end

rand_hash "Hi, how are you today?"
# => "mwerzokwwtlqepizuqimbhxmzexmovzrwgvarjlfbkcqpffhoq"

rand_hash "Hi, how are you today?"
# => "mwerzokwwtlqepizuqimbhxmzexmovzrwgvarjlfbkcqpffhoq"

rand_hash "Hi, how are you today!"
# => "zeudwqltlozjdebamemplwllqftmyhdzapatqhdsbnrzfcrmss"

See How do I unpack a number larger than 64 bits in ruby? for how the secret_key is unpacked from a string into a BigNum called int_key.

We then use that key to seed a Ruby Random object (based on Mersenne Twister)

Then use the new Random object to generate the string, same as you do originally.

Note this is not cryptographically secure. If you want security, such as impossibility to reverse the output and find the secret, then you should use a secure hash mechanism (from an appropriate gem such as openssl), and convert that to the character set you require.

Upvotes: 1

sawa
sawa

Reputation: 168101

What about this?

Random.rand("mysecretkey".hash).to_s(36)[0, 10]
# => "1lc1em343y"

Upvotes: 2

Related Questions