1

I started learning Swift for iOS development but I face a problem which didn't exist on Android.

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

With this I generate random bytes on Android.

then I use this to get a String from it.

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

How can I do the same with Swift 5 ?

maxh
  • 79
  • 4
  • 3
    Since you're talking about cryptography and you're working with iOS, I'd like to point out that most crypto operations in iOS require you to work with bytes, rather than strings. So you should be perfectly fine with creating a byte IV, instead of a string IV. Besides that, the output of the random function does not necessarily have to convert to a string, as it might not be the correct encoding, let alone any encoding. So it's very likely the conversion to a string will fail – Bram Jun 24 '20 at 08:26
  • 2
    [secRandomCopyBytes](https://stackoverflow.com/questions/39820602/using-secrandomcopybytes-in-swift) is probably better for cryptography than just random integers – Paulw11 Jun 24 '20 at 08:30

1 Answers1

-2
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)
nghiahoang
  • 538
  • 4
  • 10