【问题标题】:How to generate random bytes and then convert them to String in Swift [duplicate]如何生成随机字节,然后在 Swift 中将它们转换为字符串 [重复]
【发布时间】:2020-10-14 10:46:36
【问题描述】:

我开始学习用于 iOS 开发的 Swift,但遇到了一个在 Android 上不存在的问题。

private static byte[] randomBytes(int length) {
        SecureRandom random = new SecureRandom();
        byte[] b = new byte[length];
        random.nextBytes(b);
        return b;
}

这样我在 Android 上生成随机字节。

然后我用它从中获取一个字符串。

byte[] byteV = randomBytes(16);
String IV_string = new String(byteV);

如何使用 Swift 5 做同样的事情?

【问题讨论】:

  • 既然您在谈论加密并且您正在使用 iOS,我想指出 iOS 中的大多数加密操作都需要您使用字节,而不是字符串。所以你应该完全可以创建一个字节 IV,而不是一个字符串 IV。除此之外,随机函数的输出不一定必须转换为字符串,因为它可能不是正确的编码,更不用说任何编码了。所以很可能转换成字符串会失败
  • secRandomCopyBytes 可能比随机整数更适合密码学

标签: java ios swift string cryptography


【解决方案1】:
func randomBytes(_ length: Int) -> Data {
    guard length > 0 else { return Data() }
    return Data(
        (1...length).map { _ in UInt8.random(in: 0...UInt8.max) }
    )
}

let string = String(data: randomBytes(16), encoding: .ascii)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2011-02-21
    • 2015-10-15
    相关资源
    最近更新 更多