LoginSignup
94

More than 5 years have passed since last update.

[Ruby 2.x] SecureRandom を利用した乱数の生成方法

Posted at

利用イメージ

$ irb
irb(main):001:0> require 'securerandom'
=> true
irb(main):002:0> SecureRandom.hex(64)
=> "string------------------------"

SecureRandomの使い方

base64(n=nil)

  • nはbase64文字列の長さのバイト数 ** 実際に出力される文字列の長さはnの4/3程度
  • 生成される文字列に含まれる文字: A-Z, a-z, 0-9, “+”, “/” and “=”
使い方
p SecureRandom.base64
p SecureRandom.base64(10)
p SecureRandom.base64(12)
ソース
def self.base64(n=nil)
  [random_bytes(n)].pack("m*").delete("\n")
end

hex(n=nil)

  • nは16進数文字列の長さのバイト数
  • 生成される文字列に含まれる文字: 0-9 and a-f
使い方
p SecureRandom.hex
p SecureRandom.hex(10)
ソース
def self.hex(n=nil)
  random_bytes(n).unpack("H*")[0]
end

random_bytes(n=nil)

  • nはバイナリ文字列の長さのバイト数
  • 生成される文字列に含まれる文字: “x00” - “xff”
使い方
p SecureRandom.random_bytes
ソース
参照 => http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html

random_number(n=0)

  • nはバイナリ文字列の長さ ** n が指定された場合 *** nはinteger *** 0 <= ::random_number < n ** n が指定されなかった場合 *** nはfloat *** 0.0 <= ::random_number < 1.0
使い方
p SecureRandom.random_number
p SecureRandom.random_number(10000)
ソース
参照 => http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html

urlsafe_base64(n=nil, padding=false)

  • nはURL-safe base64文字列の長さのバイト数 ** 実際に出力される文字列の長さはnの4/3程度
  • 生成される文字列に含まれる文字: A-Z, a-z, 0-9, “-” and “_” ** (paddingがfalseの時は、"="も含まれる)
使い方
p SecureRandom.urlsafe_base64 #=> "U87nfSb70Ddx-IJR0ABg"
p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
ソース
def self.urlsafe_base64(n=nil, padding=false)
  s = [random_bytes(n)].pack("m*")
  s.delete!("\n")
  s.tr!("+/", "-_")
  s.delete!("=") unless padding
  s
end

uuid()

  • v4 random UUID
使い方
p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
ソース
def self.uuid
  ary = self.random_bytes(16).unpack("NnnnnN")
  ary[2] = (ary[2] & 0x0fff) | 0x4000
  ary[3] = (ary[3] & 0x3fff) | 0x8000
  "%08x-%04x-%04x-%04x-%04x%08x" % ary
end

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
94