HashProtocol.swift 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. //
  2. // HashProtocol.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 17/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. import Foundation
  9. internal protocol HashProtocol {
  10. var message: NSData { get }
  11. /** Common part for hash calculation. Prepare header data. */
  12. func prepare(len:Int) -> NSMutableData
  13. }
  14. extension HashProtocol {
  15. func prepare(len:Int) -> NSMutableData {
  16. let tmpMessage: NSMutableData = NSMutableData(data: self.message)
  17. // Step 1. Append Padding Bits
  18. tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
  19. // append "0" bit until message length in bits ≡ 448 (mod 512)
  20. var msgLength = tmpMessage.length
  21. var counter = 0
  22. while msgLength % len != (len - 8) {
  23. counter++
  24. msgLength++
  25. }
  26. let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
  27. tmpMessage.appendBytes(bufZeros, length: counter)
  28. bufZeros.destroy()
  29. bufZeros.dealloc(1)
  30. return tmpMessage
  31. }
  32. }