PKCS7.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. //
  2. // PKCS7.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 27/12/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. import Foundation
  9. public struct PKCS7 {
  10. let data:NSData
  11. public init(data:NSData) {
  12. self.data = data;
  13. }
  14. public func addPadding(blockSizeBytes:UInt8) -> NSData {
  15. var padding = blockSizeBytes - (data.length % Int(blockSizeBytes))
  16. var withPadding = NSMutableData(data: data)
  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 i in 0..<blockSizeBytes {
  20. withPadding.appendBytes([blockSizeBytes])
  21. }
  22. } else {
  23. // The value of each added byte is the number of bytes that are added
  24. for i in 0..<padding {
  25. withPadding.appendBytes([padding])
  26. }
  27. }
  28. return withPadding
  29. }
  30. public func removePadding() -> NSData {
  31. if let padding = data.bytes().last {
  32. if (padding >= 1 && padding <= 8) {
  33. return data.subdataWithRange(NSRange(location: 0, length: data.length - Int(padding)))
  34. }
  35. return data;
  36. }
  37. return data
  38. }
  39. }