PKCS7.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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: ErrorType {
  13. case InvalidPaddingValue
  14. }
  15. public init() {
  16. }
  17. public func add(bytes: [UInt8] , blockSize:Int) -> [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.appendContentsOf([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.appendContentsOf([UInt8(padding)])
  29. }
  30. }
  31. return withPadding
  32. }
  33. public func remove(bytes: [UInt8], blockSize:Int?) -> [UInt8] {
  34. let lastByte = bytes.last!
  35. let padding = Int(lastByte) // last byte
  36. let finalLength = bytes.count - padding
  37. if finalLength < 0 {
  38. return bytes
  39. }
  40. if padding >= 1 {
  41. return Array(bytes[0..<finalLength])
  42. }
  43. return bytes
  44. }
  45. }