SecureBytes.swift 921 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. //
  2. // SecureBytes.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 15/04/16.
  6. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. // SecureBytes keeps bytes in memory. Because this is class, bytes are not copied
  9. // and memory area is locked as long as referenced, then unlocked on deinit
  10. //
  11. #if os(Linux)
  12. import Glibc
  13. #else
  14. import Darwin
  15. #endif
  16. class SecureBytes {
  17. private let bytes: Array<UInt8>
  18. let count: Int
  19. init(bytes: Array<UInt8>) {
  20. self.bytes = bytes
  21. self.count = bytes.count
  22. self.bytes.withUnsafeBufferPointer { (pointer) -> Void in
  23. mlock(pointer.baseAddress, pointer.count)
  24. }
  25. }
  26. deinit {
  27. self.bytes.withUnsafeBufferPointer { (pointer) -> Void in
  28. munlock(pointer.baseAddress, pointer.count)
  29. }
  30. }
  31. subscript(index: Int) -> UInt8 {
  32. return self.bytes[index]
  33. }
  34. }