RSA+Signature.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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: Signatures & Verification
  17. extension RSA: Signature {
  18. public func sign(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  19. try self.sign(Array(bytes), variant: .message_pkcs1v15_SHA256)
  20. }
  21. /// Signs the data using the Private key and the specified signature variant
  22. /// - Parameters:
  23. /// - bytes: The data to be signed
  24. /// - variant: The variant to use (`digest` variants expect a pre-hashed digest matching that of the specified hash function, `message` variants will hash the data using the specified hash function before signing it)
  25. /// - Returns: The signature of the data
  26. public func sign(_ bytes: Array<UInt8>, variant: SignatureVariant) throws -> Array<UInt8> {
  27. // Check for Private Exponent presence
  28. guard let d = d else { throw RSA.Error.noPrivateKey }
  29. // Hash & Encode Message
  30. let hashedAndEncoded = try RSA.hashedAndEncoded(bytes, variant: variant, keySizeInBytes: self.keySize / 8)
  31. /// Calculate the Signature
  32. let signedData = BigUInteger(Data(hashedAndEncoded)).power(d, modulus: self.n).serialize().bytes
  33. return signedData
  34. }
  35. public func verify(signature: ArraySlice<UInt8>, for expectedData: ArraySlice<UInt8>) throws -> Bool {
  36. try self.verify(signature: Array(signature), for: Array(expectedData), variant: .message_pkcs1v15_SHA256)
  37. }
  38. /// Verifies whether a Signature is valid for the provided data
  39. /// - Parameters:
  40. /// - signature: The signature to verify
  41. /// - expectedData: The original data that you expected to have been signed
  42. /// - variant: The variant used to sign the data
  43. /// - Returns: `True` when the signature is valid for the expected data, `False` otherwise.
  44. ///
  45. /// [IETF Verification Spec](https://datatracker.ietf.org/doc/html/rfc8017#section-8.2.2)
  46. public func verify(signature: Array<UInt8>, for bytes: Array<UInt8>, variant: SignatureVariant) throws -> Bool {
  47. /// Step 1: Ensure the signature is the same length as the key's modulus
  48. guard signature.count == (self.keySize / 8) || (signature.count - 1) == (self.keySize / 8) else { throw Error.invalidSignatureLength }
  49. let expectedData = try Array<UInt8>(RSA.hashedAndEncoded(bytes, variant: variant, keySizeInBytes: self.keySize / 8).dropFirst())
  50. /// Step 2: 'Decrypt' the signature
  51. let signatureResult = BigUInteger(Data(signature)).power(self.e, modulus: self.n).serialize().bytes
  52. /// Step 3: Compare the 'decrypted' signature with the prepared / encoded expected message....
  53. guard signatureResult == expectedData else { return false }
  54. return true
  55. }
  56. /// Hashes and Encodes a message for signing and verifying
  57. ///
  58. /// - Note: [EMSA-PKCS1-v1_5](https://datatracker.ietf.org/doc/html/rfc8017#section-9.2)
  59. fileprivate static func hashedAndEncoded(_ bytes: [UInt8], variant: SignatureVariant, keySizeInBytes: Int) throws -> Array<UInt8> {
  60. /// 1. Apply the hash function to the message M to produce a hash
  61. let hashedMessage = variant.calculateHash(bytes)
  62. guard variant.enforceLength(hashedMessage) else { throw RSA.Error.invalidMessageLengthForSigning }
  63. /// 2. Encode the algorithm ID for the hash function and the hash value into an ASN.1 value of type DigestInfo
  64. /// PKCS#1_15 DER Structure (OID == sha256WithRSAEncryption)
  65. let asn: ASN1.Node = .sequence(nodes: [
  66. .sequence(nodes: [
  67. .objectIdentifier(data: Data(variant.identifier)),
  68. .null
  69. ]),
  70. .octetString(data: Data(hashedMessage))
  71. ])
  72. let t = ASN1.Encoder.encode(asn)
  73. /// 3. If emLen < tLen + 11, output "intended encoded message length too short" and stop
  74. //print("Checking Key Size: \(keySizeInBytes) < \(t.count + 11)")
  75. if keySizeInBytes < t.count + 11 { throw RSA.Error.invalidMessageLengthForSigning }
  76. /// 4. Generate an octet string PS consisting of emLen - tLen - 3
  77. /// octets with hexadecimal value 0xff. The length of PS will be
  78. /// at least 8 octets.
  79. /// 5. Concatenate PS, the DER encoding T, and other padding to form
  80. /// the encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || T.
  81. let padded = variant.pad(bytes: t, to: keySizeInBytes)
  82. /// Ensure the signature is of the correct length
  83. guard padded.count == keySizeInBytes else { throw RSA.Error.invalidMessageLengthForSigning }
  84. return padded
  85. }
  86. }
  87. extension RSA {
  88. public enum SignatureVariant {
  89. /// Hashes the raw message using MD5 before signing the data
  90. case message_pkcs1v15_MD5
  91. /// Hashes the raw message using SHA1 before signing the data
  92. case message_pkcs1v15_SHA1
  93. /// Hashes the raw message using SHA224 before signing the data
  94. case message_pkcs1v15_SHA224
  95. /// Hashes the raw message using SHA256 before signing the data
  96. case message_pkcs1v15_SHA256
  97. /// Hashes the raw message using SHA384 before signing the data
  98. case message_pkcs1v15_SHA384
  99. /// Hashes the raw message using SHA512 before signing the data
  100. case message_pkcs1v15_SHA512
  101. /// Hashes the raw message using SHA512-224 before signing the data
  102. case message_pkcs1v15_SHA512_224
  103. /// Hashes the raw message using SHA512-256 before signing the data
  104. case message_pkcs1v15_SHA512_256
  105. /// This variant isn't supported yet
  106. case digest_pkcs1v15_RAW
  107. /// This variant expects that the data to be signed is a valid MD5 Hash Digest
  108. case digest_pkcs1v15_MD5
  109. /// This variant expects that the data to be signed is a valid SHA1 Hash Digest
  110. case digest_pkcs1v15_SHA1
  111. /// This variant expects that the data to be signed is a valid SHA224 Hash Digest
  112. case digest_pkcs1v15_SHA224
  113. /// This variant expects that the data to be signed is a valid SHA256 Hash Digest
  114. case digest_pkcs1v15_SHA256
  115. /// This variant expects that the data to be signed is a valid SHA384 Hash Digest
  116. case digest_pkcs1v15_SHA384
  117. /// This variant expects that the data to be signed is a valid SHA512 Hash Digest
  118. case digest_pkcs1v15_SHA512
  119. /// This variant expects that the data to be signed is a valid SHA512-224 Hash Digest
  120. case digest_pkcs1v15_SHA512_224
  121. /// This variant expects that the data to be signed is a valid SHA512-256 Hash Digest
  122. case digest_pkcs1v15_SHA512_256
  123. internal var identifier: Array<UInt8> {
  124. switch self {
  125. case .digest_pkcs1v15_RAW: return []
  126. case .message_pkcs1v15_MD5, .digest_pkcs1v15_MD5: return Array<UInt8>(arrayLiteral: 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05)
  127. case .message_pkcs1v15_SHA1, .digest_pkcs1v15_SHA1: return Array<UInt8>(arrayLiteral: 0x2b, 0x0e, 0x03, 0x02, 0x1a)
  128. case .message_pkcs1v15_SHA256, .digest_pkcs1v15_SHA256: return Array<UInt8>(arrayLiteral: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01)
  129. case .message_pkcs1v15_SHA384, .digest_pkcs1v15_SHA384: return Array<UInt8>(arrayLiteral: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02)
  130. case .message_pkcs1v15_SHA512, .digest_pkcs1v15_SHA512: return Array<UInt8>(arrayLiteral: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03)
  131. case .message_pkcs1v15_SHA224, .digest_pkcs1v15_SHA224: return Array<UInt8>(arrayLiteral: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04)
  132. case .message_pkcs1v15_SHA512_224, .digest_pkcs1v15_SHA512_224: return Array<UInt8>(arrayLiteral: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x05)
  133. case .message_pkcs1v15_SHA512_256, .digest_pkcs1v15_SHA512_256: return Array<UInt8>(arrayLiteral: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06)
  134. }
  135. }
  136. internal func calculateHash(_ bytes: Array<UInt8>) -> Array<UInt8> {
  137. switch self {
  138. case .message_pkcs1v15_MD5:
  139. return Digest.md5(bytes)
  140. case .message_pkcs1v15_SHA1:
  141. return Digest.sha1(bytes)
  142. case .message_pkcs1v15_SHA224:
  143. return Digest.sha224(bytes)
  144. case .message_pkcs1v15_SHA256:
  145. return Digest.sha256(bytes)
  146. case .message_pkcs1v15_SHA384:
  147. return Digest.sha384(bytes)
  148. case .message_pkcs1v15_SHA512:
  149. return Digest.sha512(bytes)
  150. case .message_pkcs1v15_SHA512_224:
  151. return Digest.sha2(bytes, variant: .sha224)
  152. case .message_pkcs1v15_SHA512_256:
  153. return Digest.sha2(bytes, variant: .sha256)
  154. case .digest_pkcs1v15_RAW,
  155. .digest_pkcs1v15_MD5,
  156. .digest_pkcs1v15_SHA1,
  157. .digest_pkcs1v15_SHA224,
  158. .digest_pkcs1v15_SHA256,
  159. .digest_pkcs1v15_SHA384,
  160. .digest_pkcs1v15_SHA512,
  161. .digest_pkcs1v15_SHA512_224,
  162. .digest_pkcs1v15_SHA512_256:
  163. return bytes
  164. }
  165. }
  166. internal func enforceLength(_ bytes: Array<UInt8>) -> Bool {
  167. switch self {
  168. case .digest_pkcs1v15_MD5:
  169. return bytes.count <= 16
  170. case .digest_pkcs1v15_SHA1:
  171. return bytes.count <= 20
  172. case .digest_pkcs1v15_SHA224:
  173. return bytes.count <= 28
  174. case .digest_pkcs1v15_SHA256:
  175. return bytes.count <= 32
  176. case .digest_pkcs1v15_SHA384:
  177. return bytes.count <= 48
  178. case .digest_pkcs1v15_SHA512:
  179. return bytes.count <= 64
  180. case .digest_pkcs1v15_SHA512_224:
  181. return bytes.count <= 28
  182. case .digest_pkcs1v15_SHA512_256:
  183. return bytes.count <= 32
  184. case .message_pkcs1v15_MD5,
  185. .message_pkcs1v15_SHA1,
  186. .message_pkcs1v15_SHA224,
  187. .message_pkcs1v15_SHA256,
  188. .message_pkcs1v15_SHA384,
  189. .message_pkcs1v15_SHA512,
  190. .message_pkcs1v15_SHA512_224,
  191. .message_pkcs1v15_SHA512_256:
  192. return true
  193. default:
  194. return false
  195. }
  196. }
  197. /// Right now the only Padding Scheme supported is [EMCS-PKCS1v15](https://www.rfc-editor.org/rfc/rfc8017#section-9.2) (others include [EMSA-PSS](https://www.rfc-editor.org/rfc/rfc8017#section-9.1))
  198. internal func pad(bytes: Array<UInt8>, to blockSize: Int) -> Array<UInt8> {
  199. return Padding.emsa_pkcs1v15.add(to: bytes, blockSize: blockSize)
  200. }
  201. }
  202. }