SecureBytes.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // SecureBytes.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  11. //
  12. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. #if os(Linux) || os(Android) || os(FreeBSD)
  17. import Glibc
  18. #else
  19. import Darwin
  20. #endif
  21. /// Keeps bytes in memory. Because this is class, bytes are not copied
  22. /// and memory area is locked as long as referenced, then unlocked on deinit
  23. final class SecureBytes {
  24. fileprivate let bytes: Array<UInt8>
  25. let count: Int
  26. init(bytes: Array<UInt8>) {
  27. self.bytes = bytes
  28. self.count = bytes.count
  29. self.bytes.withUnsafeBufferPointer { (pointer) -> Void in
  30. mlock(pointer.baseAddress, pointer.count)
  31. }
  32. }
  33. deinit {
  34. self.bytes.withUnsafeBufferPointer { (pointer) -> Void in
  35. munlock(pointer.baseAddress, pointer.count)
  36. }
  37. }
  38. }
  39. extension SecureBytes: Collection {
  40. typealias Index = Int
  41. var endIndex: Int {
  42. return self.bytes.endIndex
  43. }
  44. var startIndex: Int {
  45. return self.bytes.startIndex
  46. }
  47. subscript(position: Index) -> UInt8 {
  48. return self.bytes[position]
  49. }
  50. subscript(bounds: Range<Index>) -> ArraySlice<UInt8> {
  51. return self.bytes[bounds]
  52. }
  53. func formIndex(after i: inout Int) {
  54. self.bytes.formIndex(after: &i)
  55. }
  56. func index(after i: Int) -> Int {
  57. return self.bytes.index(after: i)
  58. }
  59. }
  60. extension SecureBytes: ExpressibleByArrayLiteral {
  61. public convenience init(arrayLiteral elements: UInt8...) {
  62. self.init(bytes: elements)
  63. }
  64. }