UNPKG

895 BPlain TextView Raw
1// Copyright 2022-present 650 Industries. All rights reserved.
2
3import Security
4import ExpoModulesCore
5
6public class RandomModule: Module {
7 public func definition() -> ModuleDefinition {
8 name("ExpoRandom")
9
10 function("getRandomBase64StringAsync", getRandomBase64String)
11
12 function("getRandomBase64String", getRandomBase64String)
13 .runSynchronously()
14 }
15}
16
17private func getRandomBase64String(length: Int) throws -> String {
18 var bytes = [UInt8](repeating: 0, count: length)
19 let status = SecRandomCopyBytes(kSecRandomDefault, length, &bytes)
20
21 guard status == errSecSuccess else {
22 throw FailedGeneratingRandomBytesException(status)
23 }
24 return Data(bytes).base64EncodedString()
25}
26
27private class FailedGeneratingRandomBytesException: GenericException<OSStatus> {
28 override var reason: String {
29 "Generating random bytes has failed with OSStatus code: \(param)"
30 }
31}