Utils.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // Utils.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 26/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. func rotateLeft(v:UInt8, _ n:UInt8) -> UInt8 {
  9. return ((v << n) & 0xFF) | (v >> (8 - n))
  10. }
  11. func rotateLeft(v:UInt16, _ n:UInt16) -> UInt16 {
  12. return ((v << n) & 0xFFFF) | (v >> (16 - n))
  13. }
  14. func rotateLeft(v:UInt32, _ n:UInt32) -> UInt32 {
  15. return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
  16. }
  17. func rotateLeft(x:UInt64, _ n:UInt64) -> UInt64 {
  18. return (x << n) | (x >> (64 - n))
  19. }
  20. func rotateRight(x:UInt16, n:UInt16) -> UInt16 {
  21. return (x >> n) | (x << (16 - n))
  22. }
  23. func rotateRight(x:UInt32, n:UInt32) -> UInt32 {
  24. return (x >> n) | (x << (32 - n))
  25. }
  26. func rotateRight(x:UInt64, n:UInt64) -> UInt64 {
  27. return ((x >> n) | (x << (64 - n)))
  28. }
  29. func reverseBytes(value: UInt32) -> UInt32 {
  30. return ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24);
  31. }
  32. func toUInt32Array(slice: ArraySlice<UInt8>) -> Array<UInt32> {
  33. var result = Array<UInt32>()
  34. result.reserveCapacity(16)
  35. for idx in slice.startIndex.stride(to: slice.endIndex, by: sizeof(UInt32)) {
  36. let val1:UInt32 = (UInt32(slice[idx.advancedBy(3)]) << 24)
  37. let val2:UInt32 = (UInt32(slice[idx.advancedBy(2)]) << 16)
  38. let val3:UInt32 = (UInt32(slice[idx.advancedBy(1)]) << 8)
  39. let val4:UInt32 = UInt32(slice[idx])
  40. let val:UInt32 = val1 | val2 | val3 | val4
  41. result.append(val)
  42. }
  43. return result
  44. }
  45. func toUInt64Array(slice: ArraySlice<UInt8>) -> Array<UInt64> {
  46. var result = Array<UInt64>()
  47. result.reserveCapacity(32)
  48. for idx in slice.startIndex.stride(to: slice.endIndex, by: sizeof(UInt64)) {
  49. var val:UInt64 = 0
  50. val |= UInt64(slice[idx.advancedBy(7)]) << 56
  51. val |= UInt64(slice[idx.advancedBy(6)]) << 48
  52. val |= UInt64(slice[idx.advancedBy(5)]) << 40
  53. val |= UInt64(slice[idx.advancedBy(4)]) << 32
  54. val |= UInt64(slice[idx.advancedBy(3)]) << 24
  55. val |= UInt64(slice[idx.advancedBy(2)]) << 16
  56. val |= UInt64(slice[idx.advancedBy(1)]) << 8
  57. val |= UInt64(slice[idx.advancedBy(0)]) << 0
  58. result.append(val)
  59. }
  60. return result
  61. }
  62. func xor(a: [UInt8], _ b:[UInt8]) -> [UInt8] {
  63. var xored = [UInt8](count: min(a.count, b.count), repeatedValue: 0)
  64. for i in 0..<xored.count {
  65. xored[i] = a[i] ^ b[i]
  66. }
  67. return xored
  68. }