Array+Extensions.swift 2.5 KB

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