RandomBytesSequence.swift 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // RandomBytesSequence.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 10/10/16.
  6. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. #if os(Linux) || os(Android) || os(FreeBSD)
  9. import Glibc
  10. #else
  11. import Darwin
  12. #endif
  13. struct RandomBytesSequence: Sequence {
  14. let size: Int
  15. func makeIterator() -> AnyIterator<UInt8> {
  16. var count = 0
  17. return AnyIterator<UInt8>.init({ () -> UInt8? in
  18. if count >= self.size {
  19. return nil
  20. }
  21. count = count + 1
  22. #if os(Linux) || os(Android) || os(FreeBSD)
  23. let fd = open("/dev/urandom", O_RDONLY)
  24. if fd <= 0 {
  25. return nil
  26. }
  27. var value: UInt8 = 0
  28. let result = read(fd, &value, MemoryLayout<UInt8>.size)
  29. precondition(result == 1)
  30. close(fd)
  31. return value
  32. #else
  33. return UInt8(arc4random_uniform(UInt32(UInt8.max) + 1))
  34. #endif
  35. })
  36. }
  37. }