PKCS7.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. import Foundation
  12. public struct PKCS7: Padding {
  13. public init() {
  14. }
  15. public func add(bytes: [UInt8] , blockSize:Int) -> [UInt8] {
  16. var padding = UInt8(blockSize - (bytes.count % blockSize))
  17. var withPadding = bytes
  18. if (padding == 0) {
  19. // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added.
  20. for i in 0..<blockSize {
  21. withPadding.extend([UInt8(blockSize)])
  22. }
  23. } else {
  24. // The value of each added byte is the number of bytes that are added
  25. for i in 0..<padding {
  26. withPadding.extend([UInt8(padding)])
  27. }
  28. }
  29. return withPadding
  30. }
  31. public func remove(bytes: [UInt8], blockSize:Int? = nil) -> [UInt8] {
  32. let lastByte = bytes.last!
  33. var padding = Int(lastByte) // last byte
  34. if padding >= 1 { //TODO: need test for that, what about empty padding
  35. return Array(bytes[0..<(bytes.count - padding)])
  36. }
  37. return bytes
  38. }
  39. }