CryptoUtils.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import CryptoKit
  15. import Foundation
  16. /// Set of utility APIs for generating cryptographical artifacts.
  17. enum CryptoUtils {
  18. enum NonceGenerationError: Error {
  19. case generationFailure(status: OSStatus)
  20. }
  21. static func randomNonceString(length: Int = 32) throws -> String {
  22. precondition(length > 0)
  23. var randomBytes = [UInt8](repeating: 0, count: length)
  24. let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
  25. if errorCode != errSecSuccess {
  26. throw NonceGenerationError.generationFailure(status: errorCode)
  27. }
  28. let charset: [Character] =
  29. Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
  30. let nonce = randomBytes.map { byte in
  31. // Pick a random character from the set, wrapping around if needed.
  32. charset[Int(byte) % charset.count]
  33. }
  34. return String(nonce)
  35. }
  36. static func sha256(_ input: String) -> String {
  37. let inputData = Data(input.utf8)
  38. let hashedData = SHA256.hash(data: inputData)
  39. let hashString = hashedData.compactMap {
  40. String(format: "%02x", $0)
  41. }.joined()
  42. return hashString
  43. }
  44. }