Array+Extensions.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // Array+Extensions.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // 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:
  11. //
  12. // - 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.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. public extension Array where Element == UInt8 {
  17. public func toHexString() -> String {
  18. return `lazy`.reduce("") {
  19. var s = String($1, radix: 16)
  20. if s.count == 1 {
  21. s = "0" + s
  22. }
  23. return $0 + s
  24. }
  25. }
  26. }
  27. public extension Array where Element == UInt8 {
  28. public func md5() -> [Element] {
  29. return Digest.md5(self)
  30. }
  31. public func sha1() -> [Element] {
  32. return Digest.sha1(self)
  33. }
  34. public func sha224() -> [Element] {
  35. return Digest.sha224(self)
  36. }
  37. public func sha256() -> [Element] {
  38. return Digest.sha256(self)
  39. }
  40. public func sha384() -> [Element] {
  41. return Digest.sha384(self)
  42. }
  43. public func sha512() -> [Element] {
  44. return Digest.sha512(self)
  45. }
  46. public func sha2(_ variant: SHA2.Variant) -> [Element] {
  47. return Digest.sha2(self, variant: variant)
  48. }
  49. public func sha3(_ variant: SHA3.Variant) -> [Element] {
  50. return Digest.sha3(self, variant: variant)
  51. }
  52. public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 {
  53. return Checksum.crc32(self, seed: seed, reflect: reflect)
  54. }
  55. public func crc16(seed: UInt16? = nil) -> UInt16 {
  56. return Checksum.crc16(self, seed: seed)
  57. }
  58. public func encrypt(cipher: Cipher) throws -> [Element] {
  59. return try cipher.encrypt(slice)
  60. }
  61. public func decrypt(cipher: Cipher) throws -> [Element] {
  62. return try cipher.decrypt(slice)
  63. }
  64. public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Element] {
  65. return try authenticator.authenticate(self)
  66. }
  67. }