RSA+Cipher.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2021 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  10. //
  11. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. import Foundation
  16. // MARK: Cipher
  17. extension RSA: Cipher {
  18. @inlinable
  19. public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  20. return try self.encrypt(Array<UInt8>(bytes), variant: .pksc1v15)
  21. }
  22. @inlinable
  23. public func encrypt(_ bytes: Array<UInt8>, variant: RSAEncryptionVariant) throws -> Array<UInt8> {
  24. // Prepare the data for the specified variant
  25. let preparedData = try variant.prepare(bytes, blockSize: self.keySizeBytes)
  26. // Encrypt the prepared data
  27. return try variant.formatEncryptedBytes(self.encryptPreparedBytes(preparedData), blockSize: self.keySizeBytes)
  28. }
  29. @inlinable
  30. internal func encryptPreparedBytes(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
  31. // Calculate encrypted data
  32. return BigUInteger(Data(bytes)).power(self.e, modulus: self.n).serialize().bytes
  33. }
  34. @inlinable
  35. public func decrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  36. return try self.decrypt(Array<UInt8>(bytes), variant: .pksc1v15)
  37. }
  38. @inlinable
  39. public func decrypt(_ bytes: Array<UInt8>, variant: RSAEncryptionVariant) throws -> Array<UInt8> {
  40. // Decrypt the data
  41. let decrypted = try self.decryptPreparedBytes(bytes)
  42. // Remove padding / unstructure data and return the raw plaintext
  43. return variant.removePadding(decrypted, blockSize: self.keySizeBytes)
  44. }
  45. @inlinable
  46. internal func decryptPreparedBytes(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
  47. // Check for Private Exponent presence
  48. guard let d = d else { throw RSA.Error.noPrivateKey }
  49. // Calculate decrypted data
  50. return BigUInteger(Data(bytes)).power(d, modulus: self.n).serialize().bytes
  51. }
  52. }
  53. extension RSA {
  54. /// RSA Encryption Block Types
  55. /// - [RFC2313 8.1 - Encryption block formatting](https://datatracker.ietf.org/doc/html/rfc2313#section-8.1)
  56. public enum RSAEncryptionVariant {
  57. /// The `unsafe` encryption variant, is fully deterministic and doesn't format the inbound data in any way.
  58. ///
  59. /// - Warning: This is considered an unsafe method of encryption.
  60. case unsafe
  61. /// The `raw` encryption variant formats the inbound data with a deterministic padding scheme.
  62. ///
  63. /// - Warning: This is also considered to be an unsafe method of encryption, but matches the `Security` frameworks functionality.
  64. case raw
  65. /// The `pkcs1v15` encryption variant formats the inbound data with a non deterministic pseudo random padding scheme.
  66. ///
  67. /// [EME PKCS1v1.5 Padding Scheme Spec](https://datatracker.ietf.org/doc/html/rfc2313#section-8.1)
  68. case pksc1v15
  69. @inlinable
  70. internal func prepare(_ bytes: Array<UInt8>, blockSize: Int) throws -> Array<UInt8> {
  71. switch self {
  72. case .unsafe:
  73. return bytes
  74. case .raw:
  75. // We need at least 11 bytes of padding in order to safely encrypt messages
  76. // - block types 1 and 2 have this minimum padding requirement, block type 0 isn't specified, but we enforce the minimum padding length here to be safe.
  77. guard blockSize >= bytes.count + 11 else { throw RSA.Error.invalidMessageLengthForEncryption }
  78. return Array(repeating: 0x00, count: blockSize - bytes.count) + bytes
  79. case .pksc1v15:
  80. // The `Security` framework refuses to encrypt a zero byte message using the pkcs1v15 padding scheme, so we do the same
  81. guard !bytes.isEmpty else { throw RSA.Error.invalidMessageLengthForEncryption }
  82. // We need at least 11 bytes of random padding in order to safely encrypt messages (RFC2313 Section 8.1 - Note 6)
  83. guard blockSize >= bytes.count + 11 else { throw RSA.Error.invalidMessageLengthForEncryption }
  84. return Padding.eme_pkcs1v15.add(to: bytes, blockSize: blockSize)
  85. @unknown default:
  86. assertionFailure()
  87. return [UInt8](repeating: UInt8.random(in: 0..<UInt8.max), count: bytes.count)
  88. }
  89. }
  90. @inlinable
  91. internal func formatEncryptedBytes(_ bytes: Array<UInt8>, blockSize: Int) -> Array<UInt8> {
  92. switch self {
  93. case .unsafe:
  94. return bytes
  95. case .raw, .pksc1v15:
  96. // Format the encrypted bytes before returning
  97. return Array<UInt8>(repeating: 0x00, count: blockSize - bytes.count) + bytes
  98. @unknown default:
  99. assertionFailure()
  100. return [UInt8](repeating: UInt8.random(in: 0..<UInt8.max), count: bytes.count)
  101. }
  102. }
  103. @inlinable
  104. internal func removePadding(_ bytes: Array<UInt8>, blockSize: Int) -> Array<UInt8> {
  105. switch self {
  106. case .unsafe:
  107. return bytes
  108. case .raw:
  109. return bytes
  110. case .pksc1v15:
  111. // Convert the Octet String into an Integer Primitive using the BigInteger `serialize` method
  112. // (this effectively just prefixes the data with a 0x00 byte indicating that its a positive integer)
  113. return Padding.eme_pkcs1v15.remove(from: [0x00] + bytes, blockSize: blockSize)
  114. @unknown default:
  115. assertionFailure()
  116. return [UInt8](repeating: UInt8.random(in: 0..<UInt8.max), count: bytes.count)
  117. }
  118. }
  119. }
  120. }