SecureBytes.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // 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:
  10. //
  11. // - 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.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. #if canImport(Darwin)
  16. import Darwin
  17. #else
  18. import Glibc
  19. #endif
  20. typealias Key = SecureBytes
  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. private 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. self.bytes.endIndex
  43. }
  44. var startIndex: Int {
  45. self.bytes.startIndex
  46. }
  47. subscript(position: Index) -> UInt8 {
  48. self.bytes[position]
  49. }
  50. subscript(bounds: Range<Index>) -> ArraySlice<UInt8> {
  51. 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. 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. }