RSA+Signature.swift 8.7 KB

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