Data+Extension.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 Data {
  10. /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536
  11. public func checksum() -> UInt16 {
  12. var s:UInt32 = 0
  13. var bytesArray = self.bytes
  14. for i in 0..<bytesArray.count {
  15. s = s + UInt32(bytesArray[i])
  16. }
  17. s = s % 65536
  18. return UInt16(s)
  19. }
  20. public func md5() -> Data {
  21. let result = Digest.md5(self.bytes)
  22. return Data(bytes: result)
  23. }
  24. public func sha1() -> Data {
  25. return Data(bytes: Digest.sha1(self.bytes))
  26. }
  27. public func sha224() -> Data {
  28. return Data(bytes: Digest.sha224(self.bytes))
  29. }
  30. public func sha256() -> Data {
  31. return Data(bytes: Digest.sha256(self.bytes))
  32. }
  33. public func sha384() -> Data {
  34. return Data(bytes: Digest.sha384(self.bytes))
  35. }
  36. public func sha512() -> Data {
  37. return Data(bytes: Digest.sha512(self.bytes))
  38. }
  39. public func sha3(_ variant: SHA3.Variant) -> Data {
  40. return Data(bytes: Digest.sha3(self.bytes, variant: variant))
  41. }
  42. public func crc32(seed: UInt32? = nil, reflect : Bool = true) -> Data {
  43. return Data(bytes: Checksum.crc32(self.bytes, seed: seed, reflect: reflect).bytes())
  44. }
  45. public func crc16(seed: UInt16? = nil) -> Data {
  46. return Data(bytes: Checksum.crc16(self.bytes, seed: seed).bytes())
  47. }
  48. public func encrypt(cipher: Cipher) throws -> Data {
  49. return Data(bytes: try cipher.encrypt(self.bytes))
  50. }
  51. public func decrypt(cipher: Cipher) throws -> Data {
  52. return Data(bytes: try cipher.decrypt(self.bytes))
  53. }
  54. public func authenticate(with authenticator: Authenticator) throws -> Data {
  55. return Data(bytes: try authenticator.authenticate(self.bytes))
  56. }
  57. }
  58. extension Data {
  59. public var bytes: Array<UInt8> {
  60. return Array(self)
  61. }
  62. public func toHexString() -> String {
  63. return self.bytes.toHexString()
  64. }
  65. }