RSA+Cipher.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2025 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. @frozen
  57. public enum RSAEncryptionVariant {
  58. /// The `unsafe` encryption variant, is fully deterministic and doesn't format the inbound data in any way.
  59. ///
  60. /// - Warning: This is considered an unsafe method of encryption.
  61. case unsafe
  62. /// The `raw` encryption variant formats the inbound data with a deterministic padding scheme.
  63. ///
  64. /// - Warning: This is also considered to be an unsafe method of encryption, but matches the `Security` frameworks functionality.
  65. case raw
  66. /// The `pkcs1v15` encryption variant formats the inbound data with a non deterministic pseudo random padding scheme.
  67. ///
  68. /// [EME PKCS1v1.5 Padding Scheme Spec](https://datatracker.ietf.org/doc/html/rfc2313#section-8.1)
  69. case pksc1v15
  70. @inlinable
  71. internal func prepare(_ bytes: Array<UInt8>, blockSize: Int) throws -> Array<UInt8> {
  72. switch self {
  73. case .unsafe:
  74. return bytes
  75. case .raw:
  76. // We need at least 11 bytes of padding in order to safely encrypt messages
  77. // - 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.
  78. guard blockSize >= bytes.count + 11 else { throw RSA.Error.invalidMessageLengthForEncryption }
  79. return Array(repeating: 0x00, count: blockSize - bytes.count) + bytes
  80. case .pksc1v15:
  81. // The `Security` framework refuses to encrypt a zero byte message using the pkcs1v15 padding scheme, so we do the same
  82. guard !bytes.isEmpty else { throw RSA.Error.invalidMessageLengthForEncryption }
  83. // We need at least 11 bytes of random padding in order to safely encrypt messages (RFC2313 Section 8.1 - Note 6)
  84. guard blockSize >= bytes.count + 11 else { throw RSA.Error.invalidMessageLengthForEncryption }
  85. return Padding.eme_pkcs1v15.add(to: bytes, blockSize: blockSize)
  86. }
  87. }
  88. @inlinable
  89. internal func formatEncryptedBytes(_ bytes: Array<UInt8>, blockSize: Int) -> Array<UInt8> {
  90. switch self {
  91. case .unsafe:
  92. return bytes
  93. case .raw, .pksc1v15:
  94. // Format the encrypted bytes before returning
  95. return Array<UInt8>(repeating: 0x00, count: blockSize - bytes.count) + bytes
  96. }
  97. }
  98. @inlinable
  99. internal func removePadding(_ bytes: Array<UInt8>, blockSize: Int) -> Array<UInt8> {
  100. switch self {
  101. case .unsafe:
  102. return bytes
  103. case .raw:
  104. return bytes
  105. case .pksc1v15:
  106. // Convert the Octet String into an Integer Primitive using the BigInteger `serialize` method
  107. // (this effectively just prefixes the data with a 0x00 byte indicating that its a positive integer)
  108. return Padding.eme_pkcs1v15.remove(from: [0x00] + bytes, blockSize: blockSize)
  109. }
  110. }
  111. }
  112. }