Generate random number in range with SecRandomCopyBytes

安稳与你 提交于 2019-12-24 03:47:09

问题


I'm using SecRandomCopyBytes for generate a secure random number.

Is there a way to specify a "range"?

I need to obtain the same behaviour of this Java piece of code:

SecureRandom r = new SecureRandom();
char x = (char)(r.nextInt(26) + 'a');

Any tips will appreciate!

UPDATE

Seeing that I made a silly question I feel compelled to share the solution, made extending Int type:

public extension Int {
  /**
  Create a random num Int in range
  :param: lower number Int
  :param: upper number Int
  :return: random number Int
  */
  public static func random(#min: Int, max: Int) -> Int {
     return Int(arc4random_uniform(UInt32(max - min + 1))) + min
  }

  /**
  Create a secure random num Int in range
  :param: lower number Int
  :param: upper number Int
  :return: random number Int
  */
  public static func secureRandom(#min: Int, max: Int) -> Int {
    if max == 0 {
        NSException(name: "secureRandom", reason: "max number must be > 0", userInfo: nil).raise()
    }
    var randomBytes = UnsafeMutablePointer<UInt8>.alloc(8)
    SecRandomCopyBytes(kSecRandomDefault, 8, randomBytes)
    let randomNumber = unsafeBitCast(randomBytes, UInt.self)
    return Int(randomNumber) % max + min
  }
}

回答1:


You can always specify a range by applying modulo and addition, check this pseudocode:

// random number in the range 1985-2014 
r = rand() % 30 + 1985



回答2:


Edit: Swift 4.2 allows to generate random numbers using Int class:

let randomNumber = Int.random(in: 0 ..< 26)

The random source should be cryptographically secure SystemRandomNumberGenerator

See also:

  • Generating random numbers in Swift
  • How to generate random numbers in Swift 4.2 and later

Old answer: iOS 9 introduced GameplayKit which provides SecureRandom.nextInt() Java equivalent.

To use it in Swift 3:

import GameplayKit

// get random Int
let randomInt = GKRandomSource.sharedRandom().nextInt(upperBound: 26)

See this answer for more info: https://stackoverflow.com/a/31215189/1245231



来源:https://stackoverflow.com/questions/30783640/generate-random-number-in-range-with-secrandomcopybytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!