PKCS7.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // PKCS7.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 28/02/15.
  6. // Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. // PKCS is a group of public-key cryptography standards devised
  9. // and published by RSA Security Inc, starting in the early 1990s.
  10. //
  11. public struct PKCS7: Padding {
  12. public enum Error: Swift.Error {
  13. case invalidPaddingValue
  14. }
  15. public init() {
  16. }
  17. public func add(to bytes: Array<UInt8> , blockSize:Int) -> Array<UInt8> {
  18. let padding = UInt8(blockSize - (bytes.count % blockSize))
  19. var withPadding = bytes
  20. if (padding == 0) {
  21. // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added.
  22. for _ in 0..<blockSize {
  23. withPadding += [UInt8(blockSize)]
  24. }
  25. } else {
  26. // The value of each added byte is the number of bytes that are added
  27. for _ in 0..<padding {
  28. withPadding += [UInt8(padding)]
  29. }
  30. }
  31. return withPadding
  32. }
  33. public func remove(from bytes: Array<UInt8>, blockSize:Int?) -> Array<UInt8> {
  34. guard !bytes.isEmpty, let lastByte = bytes.last else {
  35. return bytes
  36. }
  37. assert(!bytes.isEmpty, "Need bytes to remove padding")
  38. let padding = Int(lastByte) // last byte
  39. let finalLength = bytes.count - padding
  40. if finalLength < 0 {
  41. return bytes
  42. }
  43. if padding >= 1 {
  44. return Array(bytes[0..<finalLength])
  45. }
  46. return bytes
  47. }
  48. }