PKCS7.swift 1.4 KB

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