gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:39:58 26 4
gpt4 key购买 nike

我正在使用 SecRandomCopyBytes用于生成安全的随机数。

有没有办法指定“范围”?

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

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

任何提示将不胜感激!

更新

看到我提出了一个愚蠢的问题,我觉得有必要分享解决方案,扩展 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
}
}

最佳答案

编辑:Swift 4.2 允许使用 Int 类生成随机数:

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

随机源应该是加密安全的SystemRandomNumberGenerator

另见:

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

要在 Swift 3 中使用它:

import GameplayKit

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

有关详细信息,请参阅此答案:https://stackoverflow.com/a/31215189/1245231

关于java - 使用 SecRandomCopyBytes 生成范围内的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com