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