使用SecRandomCopyBytes生成范围内的随机数

时间:2021-02-22 04:19:21

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

我使用SecRandomCopyBytes来生成一个安全的随机数。

Is there a way to specify a "range"?

是否有一种方法来指定“范围”?

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

我需要获得这段Java代码的相同行为:

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:

看到我做了一个愚蠢的问题,我觉得有必要分享这个解决方案,并扩展了Int类型:

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
  }
}

2 个解决方案

#1


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


1  

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

iOS 9引入了GameplayKit,它提供了SecureRandom.nextInt() Java等价物。

To use it in Swift 3:

在Swift 3中使用:

import GameplayKit

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

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

更多信息请参见此答案:https://*.com/a/312159/1245231

#1


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


1  

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

iOS 9引入了GameplayKit,它提供了SecureRandom.nextInt() Java等价物。

To use it in Swift 3:

在Swift 3中使用:

import GameplayKit

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

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

更多信息请参见此答案:https://*.com/a/312159/1245231