String+Hash.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // String+Hash.swift
  3. // Swifter
  4. //
  5. // Copyright 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. extension String {
  9. public func sha1() -> String {
  10. var message = [UInt8](self.utf8)
  11. let h0 = 0x67452301
  12. let h1 = 0xEFCDAB89
  13. let h2 = 0x98BADCFE
  14. let h3 = 0x10325476
  15. let h4 = 0xC3D2E1F0
  16. // ml = message length in bits (always a multiple of the number of bits in a character).
  17. let ml = UInt64(message.count * 8)
  18. // append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.
  19. message.append(0x80)
  20. // append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512)
  21. var padBytesCount = message.count % 64
  22. while padBytesCount + 4 < 64 {
  23. message.append(0x00)
  24. padBytesCount = padBytesCount + 1
  25. }
  26. // append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
  27. var bigEndian = ml.bigEndian
  28. let bytePtr = withUnsafePointer(&bigEndian) {
  29. UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: sizeofValue(bigEndian))
  30. }
  31. let byteArray = Array(bytePtr)
  32. message.appendContentsOf(byteArray)
  33. // Process the message in successive 512-bit chunks:
  34. return "//TODO"
  35. }
  36. }