[英]Generate random number in range with SecRandomCopyBytes
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
}
}
Edit: Swift 4.2 allows to generate random numbers using Int
class:编辑:Swift 4.2允许使用Int
类生成随机数:
let randomNumber = Int.random(in: 0 ..< 26)
The random source should be cryptographically secure SystemRandomNumberGenerator随机源应该是加密安全的SystemRandomNumberGenerator
See also:也可以看看:
Old answer: 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://stackoverflow.com/a/31215189/1245231有关更多信息,请参阅此答案: https : //stackoverflow.com/a/31215189/1245231
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.