A completely random identifier of a given length

I would like to generate a completely random “unique” (I will ensure that using my model) the identifier of the given (length may vary) length containing numbers, letters and special characters

For instance:

161551960578281|2.AQAIPhEcKsDLOVJZ.3600.1310065200.0-514191032|

Can anyone suggest the most efficient way to do this in Ruby on Rails?

EDIT: IMPORTANT:   If possible, comment on how effective your proposed solution is, because it will be used every time a user logs into the website!

thank

+5
source share
6 answers

- , UUID. , PRNG. , ( ), - , Base64 . URL- , URL-, , - Java: "http://www.bla.com/jsessionid=". Base64 , URL-.

require 'securerandom'

def produce_token(length=32)
  token = SecureRandom.urlsafe_base64(length)
end

2 ^ (- length). Base64, 4/3 *. , OpenSSL PRNG, . OpenSSL , /dev/urandom , , , , Windows, CryptGenRandom . . , produce_token ~ 6 .

+12

- UUID ;-) - , uuid4r gem UUID4R::uuid(1). uuid (MAC- ). , , .

uuid4r - ossp-uuid c library, (apt-get install libossp-uuid libossp-uuid-dev debian brew install ossp-uuid mac homebrew ) , .

uuid4r ( ?) , , " , " b) ( uuid ) c

require 'rubygems'
require 'uuid4r'
UUID4R::uuid(1) #=> "67074ea4-a8c3-11e0-8a8c-2b12e1ad57c3"
UUID4R::uuid(1) #=> "68ad5668-a8c3-11e0-b5b7-370d85fa740d"

: , . ( !) 50 .

      user     system      total        real
version 1  0.600000   1.370000   1.970000 (  1.980516)
version 4  0.500000   1.360000   1.860000 (  1.855086)

uuid ~ 0,4 (, 50000 ). ,

( "" )

require 'rubygems'
require 'uuid4r'
require 'benchmark'

n = 50000
Benchmark.bm do |bm|
  bm.report("version 1") { n.times { UUID4R::uuid(1) } }
  bm.report("version 4") { n.times { UUID4R::uuid(4) } }
end

heroku:

+3

:

require 'active_support/secure_random'
ActiveSupport::SecureRandom.hex(16) # => "00c62d9820d16b52740ca6e15d142854"

(.. )

, UUID, . ( 4) , .

, , - ( , . !:-). , tybro0103:

require 'digest/sha1'
ALPHABET = "|,.!-0123456789".split(//) + ('a'..'z').to_a + ('A'..'Z').to_a

def random_string
    not_quite_secure = Array.new(32){ ALPHABET.sample }.join
    secure = Digest::SHA1.hexdigest(not_quite_secure)
end

random_string # => "2555265b2ff3ecb0a13d65a3d177b326733bc143"

, , . .

+3
def random_string(length=32)
    chars = (0..9).to_a.concat(('a'..'z').to_a).concat(('A'..'Z').to_a).concat(['|',',','.','!','-'])
    str = ""; length.times {str += chars.sample.to_s}
    str
end

:

>> random_string(42)
=> "a!,FEv,g3HptLCImw0oHnHNNj1drzMFM,1tptMS|rO"
+2

It's a little harder to generate random letters in Ruby 1.9 vs 1.8 due to changing character behavior. The easiest way to do this in 1.9 is to create an array of characters that you want to use, and then randomly grab characters from this array. See http://snippets.dzone.com/posts/show/491

0
source

You can check the implementations here. I used this one

0
source

All Articles