Data+Extension.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //
  2. // PGPDataExtension.swift
  3. // SwiftPGP
  4. //
  5. // Created by Marcin Krzyzanowski on 05/07/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. import Foundation
  9. extension NSMutableData {
  10. /** Convenient way to append bytes */
  11. internal func appendBytes(_ arrayOfBytes: Array<UInt8>) {
  12. self.append(arrayOfBytes, length: arrayOfBytes.count)
  13. }
  14. }
  15. extension Data {
  16. /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536
  17. public func checksum() -> UInt16 {
  18. var s:UInt32 = 0
  19. var bytesArray = self.bytes
  20. for i in 0..<bytesArray.count {
  21. s = s + UInt32(bytesArray[i])
  22. }
  23. s = s % 65536
  24. return UInt16(s)
  25. }
  26. public func md5() -> Data {
  27. let result = Hash.md5(self.bytes).calculate()
  28. return Data(bytes: result)
  29. }
  30. public func sha1() -> Data? {
  31. let result = Hash.sha1(self.bytes).calculate()
  32. return Data(bytes: result)
  33. }
  34. public func sha224() -> Data? {
  35. let result = Hash.sha224(self.bytes).calculate()
  36. return Data(bytes: result)
  37. }
  38. public func sha256() -> Data? {
  39. let result = Hash.sha256(self.bytes).calculate()
  40. return Data(bytes: result)
  41. }
  42. public func sha384() -> Data? {
  43. let result = Hash.sha384(self.bytes).calculate()
  44. return Data(bytes: result)
  45. }
  46. public func sha512() -> Data? {
  47. let result = Hash.sha512(self.bytes).calculate()
  48. return Data(bytes: result)
  49. }
  50. public func crc32(seed: UInt32? = nil, reflect : Bool = true) -> Data? {
  51. let result = Hash.crc32(self.bytes, seed: seed, reflect: reflect).calculate()
  52. return Data(bytes: result)
  53. }
  54. public func crc16(seed: UInt16? = nil) -> Data? {
  55. let result = Hash.crc16(self.bytes, seed: seed).calculate()
  56. return Data(bytes: result)
  57. }
  58. public func encrypt(cipher: Cipher) throws -> Data {
  59. let encrypted = try cipher.encrypt(self.bytes)
  60. return Data(bytes: encrypted)
  61. }
  62. public func decrypt(cipher: Cipher) throws -> Data {
  63. let decrypted = try cipher.decrypt(self.bytes)
  64. return Data(bytes: decrypted)
  65. }
  66. public func authenticate(with authenticator: Authenticator) throws -> Data {
  67. let result = try authenticator.authenticate(self.bytes)
  68. return Data(bytes: result)
  69. }
  70. }
  71. extension Data {
  72. public var bytes: Array<UInt8> {
  73. return Array(self)
  74. }
  75. public func toHexString() -> String {
  76. return self.bytes.toHexString()
  77. }
  78. }