From 1c0b32af3c06834cd8869ff8e743361416d8fd57 Mon Sep 17 00:00:00 2001 From: nielsandriesse Date: Thu, 12 Nov 2020 10:41:45 +1100 Subject: [PATCH] Fix ECKeyPair usage --- Podfile | 21 +- Podfile.lock | 26 +- Session/Configuration.swift | 2 +- Session/Meta/Signal-Bridging-Header.h | 12 +- Session/Meta/Signal-Prefix.pch | 4 +- Session/Signal/AppDelegate.m | 4 +- .../Cells/OWSGenericAttachmentView.m | 1 + .../Cells/OWSMessageTimerView.m | 2 +- .../Cells/OWSQuotedMessageView.m | 1 + .../ConversationInputTextView.m | 1 + .../ConversationViewController.m | 5 +- .../ConversationView/ConversationViewModel.m | 2 +- Session/Signal/DateUtil.m | 2 +- Session/Signal/FingerprintViewController.m | 2 +- Session/Signal/MainAppContext.m | 2 +- Session/Signal/OWSBackup.m | 2 +- Session/Signal/OWSBackupExportJob.m | 6 +- Session/Signal/OWSBackupIO.m | 2 +- Session/Signal/OWSBackupImportJob.m | 2 +- Session/Signal/OWSBackupJob.m | 2 +- .../OWSConversationSettingsViewController.m | 2 +- .../Signal/OWSDeviceProvisioningURLParser.m | 2 +- Session/Signal/OWSOrphanDataCleaner.m | 2 +- Session/Signal/Pastelog.m | 2 +- .../PrivacySettingsTableViewController.m | 1 + Session/Signal/RemoteVideoView.m | 2 +- Session/Signal/SignalApp.m | 2 +- Session/Signal/UIViewController+Permissions.m | 2 +- Session/Signal/UpdateGroupViewController.m | 3 +- Session/Storage+Shared.swift | 2 +- Session/Utilities/KeyPairUtilities.swift | 2 +- Session/View Controllers/LandingVC.swift | 4 +- .../View Controllers/NewClosedGroupVC.swift | 2 +- .../Open Groups/OpenGroupAPI.swift | 4 +- .../Open Groups/OpenGroupMessage.swift | 6 +- .../MessageReceiver+Decryption.swift | 3 +- SessionMessagingKit/Utilities/DotNetAPI.swift | 9 +- SessionProtocolKit/Meta/SessionProtocolKit.h | 8 - .../ClosedGroupCiphertextMessage.m | 2 +- .../CipherMessage/PreKeyWhisperMessage.m | 4 +- .../Signal/CipherMessage/WhisperMessage.m | 7 +- SessionProtocolKit/Signal/Crypto/AES-CBC.m | 2 +- SessionProtocolKit/Signal/ECPrivateKey.swift | 34 - SessionProtocolKit/Signal/ECPublicKey.swift | 61 - .../Signal/FallbackSessionCipher.swift | 3 +- .../Signal/Prekeys/PreKeyBundle.m | 2 +- .../Signal/Prekeys/PreKeyRecord.m | 2 +- .../Signal/Prekeys/SignedPrekeyRecord.m | 2 +- .../Signal/Ratchet/AliceAxolotlParameters.m | 2 +- .../Signal/Ratchet/BobAxolotlParameters.m | 2 +- SessionProtocolKit/Signal/Ratchet/ChainKey.m | 2 +- .../Signal/Ratchet/MessageKeys.m | 2 +- SessionProtocolKit/Signal/Ratchet/RKCK.m | 2 +- .../Signal/Ratchet/RatchetingSession.m | 36 +- .../Signal/Ratchet/ReceivingChain.m | 2 +- SessionProtocolKit/Signal/Ratchet/RootKey.m | 4 +- .../Signal/Ratchet/SendingChain.m | 2 +- .../Signal/Ratchet/TSDerivedSecrets.m | 2 +- .../Signal/SMKCertificateValidator.swift | 1 + .../Signal/SMKSecretSessionCipher.swift | 39 +- .../Signal/SMKUDAccessKey.swift | 3 +- .../Signal/SMKUnidentifiedSenderMessage.swift | 1 + SessionProtocolKit/Signal/SessionCipher.m | 5 +- .../Signal/Sessions/SessionBuilder.m | 12 +- .../Signal/Sessions/SessionRecord.m | 2 +- .../Signal/Sessions/SessionState.m | 2 +- .../Signal/Utility/Cryptography.h | 161 --- .../Signal/Utility/Cryptography.m | 1074 ----------------- .../Signal/Utility/Data+OWS.swift | 22 - .../Signal/Utility/Logger.swift | 77 -- .../Signal/Utility/NSData+OWS.h | 37 - .../Signal/Utility/NSData+OWS.m | 147 --- .../Signal/Utility/NSData+keyVersionByte.m | 4 +- .../Signal/Utility/NSDate+OWS.h | 44 - .../Signal/Utility/NSDate+OWS.mm | 59 - .../Signal/Utility/NSObject+OWS.h | 21 - .../Signal/Utility/NSObject+OWS.m | 36 - .../Signal/Utility/NSString+OWS.h | 28 - .../Signal/Utility/NSString+OWS.m | 453 ------- .../Signal/Utility/OWSAsserts.h | 210 ---- .../Signal/Utility/OWSAsserts.m | 17 - .../Signal/Utility/OWSDataParser.swift | 48 - SessionProtocolKit/Signal/Utility/OWSLogs.h | 91 -- SessionProtocolKit/Signal/Utility/OWSLogs.m | 43 - .../Signal/Utility/OWSSwiftUtils.swift | 70 -- .../Signal/Utility/SCKExceptionWrapper.h | 95 -- .../Signal/Utility/SCKExceptionWrapper.m | 46 - .../Signal/Utility/SerializationUtilities.m | 2 +- .../Signal/Utility/String+OWS.swift | 72 -- SessionProtocolKit/Signal/Utility/Threading.h | 19 - SessionProtocolKit/Signal/Utility/Threading.m | 36 - .../Signal/Utility/iOSVersions.h | 8 - .../SignalShareExtension-Bridging-Header.h | 6 +- .../Meta/SignalShareExtension-Prefix.pch | 4 +- SessionUtilitiesKit/AESGCM.swift | 8 +- SessionUtilitiesKit/DiffieHellman.swift | 6 +- SessionUtilitiesKit/ECKeyPair+Utilities.h | 13 - SessionUtilitiesKit/ECKeyPair+Utilities.m | 22 - .../Meta/SessionUtilitiesKit.h | 1 - Signal.xcodeproj/project.pbxproj | 114 +- SignalUtilitiesKit/ClosedGroupUtilities.swift | 3 +- SignalUtilitiesKit/ClosedGroupsProtocol.swift | 6 +- SignalUtilitiesKit/Contact.m | 4 +- SignalUtilitiesKit/ContactDiscoveryService.m | 4 +- SignalUtilitiesKit/ContactsUpdater.m | 4 +- SignalUtilitiesKit/DataSource.m | 2 +- SignalUtilitiesKit/DeviceNames.swift | 9 +- .../ECKeyPair+Hexadecimal.swift | 4 +- SignalUtilitiesKit/EncryptionUtilities.swift | 8 +- SignalUtilitiesKit/LKDeviceLinkMessage.m | 4 +- SignalUtilitiesKit/LKUnlinkDeviceMessage.m | 2 +- .../Meta/SignalUtilitiesKit-Prefix.pch | 1 + SignalUtilitiesKit/NSString+SSK.h | 2 - SignalUtilitiesKit/OWSAnalytics.m | 2 +- SignalUtilitiesKit/OWSAttachmentDownloads.m | 2 +- SignalUtilitiesKit/OWSBatchMessageProcessor.m | 2 +- SignalUtilitiesKit/OWSChunkedOutputStream.m | 2 +- .../OWSContactDiscoveryOperation.swift | 2 + SignalUtilitiesKit/OWSContactsOutputStream.m | 4 +- SignalUtilitiesKit/OWSDevice.m | 2 +- ...DisappearingMessagesConfigurationMessage.m | 2 +- .../OWSDisappearingMessagesFinder.m | 2 +- .../OWSDisappearingMessagesJob.m | 2 +- .../OWSDynamicOutgoingMessage.m | 2 +- SignalUtilitiesKit/OWSEndSessionMessage.m | 2 +- SignalUtilitiesKit/OWSFingerprint.m | 2 +- SignalUtilitiesKit/OWSIdentityManager.m | 2 +- SignalUtilitiesKit/OWSIncompleteCallsJob.m | 2 +- SignalUtilitiesKit/OWSMessageDecrypter.m | 6 +- SignalUtilitiesKit/OWSMessageManager.m | 4 +- SignalUtilitiesKit/OWSMessageReceiver.m | 4 +- SignalUtilitiesKit/OWSMessageSender.m | 8 +- SignalUtilitiesKit/OWSMessageServiceParams.m | 2 +- SignalUtilitiesKit/OWSOutgoingCallMessage.m | 2 +- SignalUtilitiesKit/OWSOutgoingNullMessage.m | 4 +- SignalUtilitiesKit/OWSOutgoingSyncMessage.m | 4 +- SignalUtilitiesKit/OWSPrimaryStorage+Loki.m | 2 +- .../OWSPrimaryStorage+SignedPreKeyStore.m | 2 +- SignalUtilitiesKit/OWSProvisioningCipher.m | 2 +- .../OWSReceiptsForSenderMessage.m | 2 +- SignalUtilitiesKit/OWSRecipientIdentity.m | 2 +- SignalUtilitiesKit/OWSRequestFactory.m | 4 +- SignalUtilitiesKit/OWSStorage.m | 4 +- SignalUtilitiesKit/OWSSyncContactsMessage.m | 2 +- SignalUtilitiesKit/OWSSyncGroupsMessage.m | 2 +- .../OWSSyncGroupsRequestMessage.m | 2 +- SignalUtilitiesKit/OWSUploadOperation.m | 4 +- .../OWSVerificationStateSyncMessage.m | 2 +- SignalUtilitiesKit/OWSWebSocket.m | 4 +- SignalUtilitiesKit/ProtoUtils.m | 2 +- SignalUtilitiesKit/SSKAsserts.h | 4 +- .../SharedSenderKeysImplementation.swift | 2 +- SignalUtilitiesKit/SignalKeyingStorage.m | 2 +- SignalUtilitiesKit/TSAccountManager.m | 4 +- SignalUtilitiesKit/TSAttachmentStream.m | 2 +- SignalUtilitiesKit/TSErrorMessage.m | 2 +- SignalUtilitiesKit/TSGroupThread.m | 2 +- SignalUtilitiesKit/TSInteraction.m | 2 +- SignalUtilitiesKit/TSMessage.m | 2 +- SignalUtilitiesKit/TSOutgoingMessage.m | 2 +- SignalUtilitiesKit/TSPreKeyManager.m | 2 +- SignalUtilitiesKit/TSThread.m | 4 +- SignalUtilitiesKit/UIColor+OWS.m | 2 +- 163 files changed, 261 insertions(+), 3419 deletions(-) delete mode 100644 SessionProtocolKit/Signal/ECPrivateKey.swift delete mode 100644 SessionProtocolKit/Signal/ECPublicKey.swift delete mode 100644 SessionProtocolKit/Signal/Utility/Cryptography.h delete mode 100644 SessionProtocolKit/Signal/Utility/Cryptography.m delete mode 100644 SessionProtocolKit/Signal/Utility/Data+OWS.swift delete mode 100644 SessionProtocolKit/Signal/Utility/Logger.swift delete mode 100644 SessionProtocolKit/Signal/Utility/NSData+OWS.h delete mode 100644 SessionProtocolKit/Signal/Utility/NSData+OWS.m delete mode 100644 SessionProtocolKit/Signal/Utility/NSDate+OWS.h delete mode 100644 SessionProtocolKit/Signal/Utility/NSDate+OWS.mm delete mode 100644 SessionProtocolKit/Signal/Utility/NSObject+OWS.h delete mode 100644 SessionProtocolKit/Signal/Utility/NSObject+OWS.m delete mode 100644 SessionProtocolKit/Signal/Utility/NSString+OWS.h delete mode 100644 SessionProtocolKit/Signal/Utility/NSString+OWS.m delete mode 100644 SessionProtocolKit/Signal/Utility/OWSAsserts.h delete mode 100644 SessionProtocolKit/Signal/Utility/OWSAsserts.m delete mode 100644 SessionProtocolKit/Signal/Utility/OWSDataParser.swift delete mode 100644 SessionProtocolKit/Signal/Utility/OWSLogs.h delete mode 100644 SessionProtocolKit/Signal/Utility/OWSLogs.m delete mode 100644 SessionProtocolKit/Signal/Utility/OWSSwiftUtils.swift delete mode 100644 SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.h delete mode 100644 SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.m delete mode 100644 SessionProtocolKit/Signal/Utility/String+OWS.swift delete mode 100644 SessionProtocolKit/Signal/Utility/Threading.h delete mode 100644 SessionProtocolKit/Signal/Utility/Threading.m delete mode 100644 SessionProtocolKit/Signal/Utility/iOSVersions.h delete mode 100644 SessionUtilitiesKit/ECKeyPair+Utilities.h delete mode 100644 SessionUtilitiesKit/ECKeyPair+Utilities.m diff --git a/Podfile b/Podfile index 3ed7a3250..79bdddf9d 100644 --- a/Podfile +++ b/Podfile @@ -24,27 +24,29 @@ end target 'SessionShareExtension' do pod 'AFNetworking', inhibit_warnings: true pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'Mantle', git: 'https://github.com/signalapp/Mantle', branch: 'signal-master', :inhibit_warnings => true pod 'PromiseKit', :inhibit_warnings => true pod 'PureLayout', '~> 3.1.4', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true pod 'YapDatabase/SQLCipher', :git => 'https://github.com/signalapp/YapDatabase.git', branch: 'signal-release', :inhibit_warnings => true end target 'SessionPushNotificationExtension' do pod 'AFNetworking', inhibit_warnings: true pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'Mantle', git: 'https://github.com/signalapp/Mantle', branch: 'signal-master', :inhibit_warnings => true pod 'PromiseKit', :inhibit_warnings => true pod 'PureLayout', '~> 3.1.4', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true pod 'YapDatabase/SQLCipher', :git => 'https://github.com/signalapp/YapDatabase.git', branch: 'signal-release', :inhibit_warnings => true end target 'SignalUtilitiesKit' do pod 'AFNetworking', inhibit_warnings: true pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'GRKOpenSSLFramework', :inhibit_warnings => true pod 'HKDFKit', :inhibit_warnings => true pod 'libPhoneNumber-iOS', :inhibit_warnings => true @@ -53,6 +55,7 @@ target 'SignalUtilitiesKit' do pod 'PureLayout', '~> 3.1.4', :inhibit_warnings => true pod 'Reachability', :inhibit_warnings => true pod 'SAMKeychain', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true pod 'Starscream', git: 'https://github.com/signalapp/Starscream.git', branch: 'signal-release', :inhibit_warnings => true pod 'SwiftProtobuf', '~> 1.5.0', :inhibit_warnings => true pod 'YapDatabase/SQLCipher', :git => 'https://github.com/signalapp/YapDatabase.git', branch: 'signal-release', :inhibit_warnings => true @@ -66,31 +69,35 @@ end target 'SessionMessagingKit' do pod 'AFNetworking', inhibit_warnings: true pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'PromiseKit', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true pod 'SwiftProtobuf', '~> 1.5.0', :inhibit_warnings => true end target 'SessionProtocolKit' do pod 'CocoaLumberjack', :inhibit_warnings => true pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'GRKOpenSSLFramework', :inhibit_warnings => true pod 'HKDFKit', :inhibit_warnings => true pod 'PromiseKit', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true pod 'SwiftProtobuf', '~> 1.5.0', :inhibit_warnings => true end target 'SessionSnodeKit' do pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'PromiseKit', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true end target 'SessionUtilitiesKit' do pod 'CryptoSwift', :inhibit_warnings => true - pod 'Curve25519Kit', :inhibit_warnings => true + pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit.git', :inhibit_warnings => true pod 'PromiseKit', :inhibit_warnings => true + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', :inhibit_warnings => true end post_install do |installer| diff --git a/Podfile.lock b/Podfile.lock index 2eb06dd20..3ff7141db 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -18,7 +18,9 @@ PODS: - CocoaLumberjack/Core (= 3.6.2) - CocoaLumberjack/Core (3.6.2) - CryptoSwift (1.3.2) - - Curve25519Kit (2.1.0) + - Curve25519Kit (2.1.0): + - CocoaLumberjack + - SignalCoreKit - FeedKit (8.1.1) - GRKOpenSSLFramework (1.0.2.20) - HKDFKit (0.0.3) @@ -41,6 +43,9 @@ PODS: - PureLayout (3.1.6) - Reachability (3.2) - SAMKeychain (1.5.3) + - SignalCoreKit (1.0.0): + - CocoaLumberjack + - GRKOpenSSLFramework - Sodium (0.8.0) - SQLCipher (4.4.0): - SQLCipher/standard (= 4.4.0) @@ -123,7 +128,7 @@ DEPENDENCIES: - AFNetworking - CocoaLumberjack - CryptoSwift - - Curve25519Kit + - Curve25519Kit (from `https://github.com/signalapp/Curve25519Kit.git`) - FeedKit - GRKOpenSSLFramework - HKDFKit @@ -134,6 +139,7 @@ DEPENDENCIES: - PureLayout (~> 3.1.4) - Reachability - SAMKeychain + - SignalCoreKit (from `https://github.com/signalapp/SignalCoreKit.git`) - Sodium - SSZipArchive - Starscream (from `https://github.com/signalapp/Starscream.git`, branch `signal-release`) @@ -147,7 +153,6 @@ SPEC REPOS: - AFNetworking - CocoaLumberjack - CryptoSwift - - Curve25519Kit - FeedKit - GRKOpenSSLFramework - HKDFKit @@ -164,9 +169,13 @@ SPEC REPOS: - ZXingObjC EXTERNAL SOURCES: + Curve25519Kit: + :git: https://github.com/signalapp/Curve25519Kit.git Mantle: :branch: signal-master :git: https://github.com/signalapp/Mantle + SignalCoreKit: + :git: https://github.com/signalapp/SignalCoreKit.git Starscream: :branch: signal-release :git: https://github.com/signalapp/Starscream.git @@ -177,9 +186,15 @@ EXTERNAL SOURCES: :git: https://github.com/signalapp/YYImage CHECKOUT OPTIONS: + Curve25519Kit: + :commit: 4fc1c10e98fff2534b5379a9bb587430fdb8e577 + :git: https://github.com/signalapp/Curve25519Kit.git Mantle: :commit: b72c2d1e6132501db906de2cffa8ded7803c54f4 :git: https://github.com/signalapp/Mantle + SignalCoreKit: + :commit: 21c092e94b307690957b50f2305e5e65d28fa89e + :git: https://github.com/signalapp/SignalCoreKit.git Starscream: :commit: b09ea163c3cb305152c65b299cb024610f52e735 :git: https://github.com/signalapp/Starscream.git @@ -194,7 +209,7 @@ SPEC CHECKSUMS: AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 CocoaLumberjack: bd155f2dd06c0e0b03f876f7a3ee55693122ec94 CryptoSwift: 093499be1a94b0cae36e6c26b70870668cb56060 - Curve25519Kit: 76d0859ecb34704f7732847812363f83b23a6a59 + Curve25519Kit: e63f9859ede02438ae3defc5e1a87e09d1ec7ee6 FeedKit: 3418eed25f0b493b205b4de1b8511ac21d413fa9 GRKOpenSSLFramework: dc635b0a9d4cd8af2a9ff80a61e779e21b69dfd8 HKDFKit: c058305d6f64b84f28c50bd7aa89574625bcb62a @@ -205,6 +220,7 @@ SPEC CHECKSUMS: PureLayout: bd3c4ec3a3819ad387c99ebb72c6b129c3ed4d2d Reachability: 33e18b67625424e47b6cde6d202dce689ad7af96 SAMKeychain: 483e1c9f32984d50ca961e26818a534283b4cd5c + SignalCoreKit: 4562b2bbd9830077439ca003f952a798457d4ea5 Sodium: 63c0ca312a932e6da481689537d4b35568841bdc SQLCipher: e434ed542b24f38ea7b36468a13f9765e1b5c072 SSZipArchive: 62d4947b08730e4cda640473b0066d209ff033c9 @@ -214,6 +230,6 @@ SPEC CHECKSUMS: YYImage: 6db68da66f20d9f169ceb94dfb9947c3867b9665 ZXingObjC: fdbb269f25dd2032da343e06f10224d62f537bdb -PODFILE CHECKSUM: db9bd6df7d17f8926d13475263d89cd767f7eea2 +PODFILE CHECKSUM: 1aad5fbd49d168d2f50da0b3b3e515247f1ce291 COCOAPODS: 1.10.0.rc.1 diff --git a/Session/Configuration.swift b/Session/Configuration.swift index 4ff7101f6..a30b8c684 100644 --- a/Session/Configuration.swift +++ b/Session/Configuration.swift @@ -4,7 +4,7 @@ import SessionSnodeKit @objc(SNConfiguration) final class Configuration : NSObject { - @objc func performMainSetup() { + @objc static func performMainSetup() { SessionProtocolKit.configure(storage: Storage.shared, sharedSenderKeysDelegate: UIApplication.shared.delegate as! AppDelegate) SessionSnodeKit.configure(storage: Storage.shared) } diff --git a/Session/Meta/Signal-Bridging-Header.h b/Session/Meta/Signal-Bridging-Header.h index 517bbc064..30d99c14c 100644 --- a/Session/Meta/Signal-Bridging-Header.h +++ b/Session/Meta/Signal-Bridging-Header.h @@ -45,12 +45,12 @@ #import #import #import -#import -#import -#import -#import -#import -#import +#import +#import +#import +#import +#import +#import #import #import #import diff --git a/Session/Meta/Signal-Prefix.pch b/Session/Meta/Signal-Prefix.pch index 18f22e08c..9faa8fd63 100644 --- a/Session/Meta/Signal-Prefix.pch +++ b/Session/Meta/Signal-Prefix.pch @@ -15,8 +15,8 @@ static const NSUInteger ddLogLevel = DDLogLevelInfo; #endif - #import - #import + #import + #import #import #import #import diff --git a/Session/Signal/AppDelegate.m b/Session/Signal/AppDelegate.m index e728fc236..3c7474414 100644 --- a/Session/Signal/AppDelegate.m +++ b/Session/Signal/AppDelegate.m @@ -14,7 +14,7 @@ #import "SignalsNavigationController.h" #import "ViewControllerUtils.h" #import -#import +#import #import #import #import @@ -240,6 +240,8 @@ static NSTimeInterval launchStartedAt; [self versionMigrationsDidComplete]; }]; + [SNConfiguration performMainSetup]; + [LKAppearanceUtilities switchToSessionAppearance]; if (CurrentAppContext().isRunningTests) { diff --git a/Session/Signal/ConversationView/Cells/OWSGenericAttachmentView.m b/Session/Signal/ConversationView/Cells/OWSGenericAttachmentView.m index 0dc63ab42..b6b695c43 100644 --- a/Session/Signal/ConversationView/Cells/OWSGenericAttachmentView.m +++ b/Session/Signal/ConversationView/Cells/OWSGenericAttachmentView.m @@ -13,6 +13,7 @@ #import #import #import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/Session/Signal/ConversationView/Cells/OWSMessageTimerView.m b/Session/Signal/ConversationView/Cells/OWSMessageTimerView.m index 6e85ec4d8..67921dc3a 100644 --- a/Session/Signal/ConversationView/Cells/OWSMessageTimerView.m +++ b/Session/Signal/ConversationView/Cells/OWSMessageTimerView.m @@ -8,7 +8,7 @@ #import "UIColor+OWS.h" #import "UIView+OWS.h" #import -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/Session/Signal/ConversationView/Cells/OWSQuotedMessageView.m b/Session/Signal/ConversationView/Cells/OWSQuotedMessageView.m index 847f3df45..475a78faf 100644 --- a/Session/Signal/ConversationView/Cells/OWSQuotedMessageView.m +++ b/Session/Signal/ConversationView/Cells/OWSQuotedMessageView.m @@ -7,6 +7,7 @@ #import "Environment.h" #import "OWSBubbleView.h" #import "Session-Swift.h" +#import #import #import #import diff --git a/Session/Signal/ConversationView/ConversationInputTextView.m b/Session/Signal/ConversationView/ConversationInputTextView.m index 4d02bbd9e..406d8c9cd 100644 --- a/Session/Signal/ConversationView/ConversationInputTextView.m +++ b/Session/Signal/ConversationView/ConversationInputTextView.m @@ -5,6 +5,7 @@ #import "ConversationInputTextView.h" #import "Session-Swift.h" #import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/Session/Signal/ConversationView/ConversationViewController.m b/Session/Signal/ConversationView/ConversationViewController.m index 4479d1eca..c9081489b 100644 --- a/Session/Signal/ConversationView/ConversationViewController.m +++ b/Session/Signal/ConversationView/ConversationViewController.m @@ -26,6 +26,7 @@ #import "OWSMath.h" #import "OWSMessageCell.h" #import "OWSSystemMessageCell.h" +#import #import "Session-Swift.h" #import #import "TSAttachmentPointer.h" @@ -45,8 +46,8 @@ #import #import #import -#import -#import +#import +#import #import #import #import diff --git a/Session/Signal/ConversationView/ConversationViewModel.m b/Session/Signal/ConversationView/ConversationViewModel.m index a8342ba01..1833020b6 100644 --- a/Session/Signal/ConversationView/ConversationViewModel.m +++ b/Session/Signal/ConversationView/ConversationViewModel.m @@ -8,7 +8,7 @@ #import "OWSMessageBubbleView.h" #import "OWSQuotedReplyModel.h" #import "Session-Swift.h" -#import +#import #import #import #import diff --git a/Session/Signal/DateUtil.m b/Session/Signal/DateUtil.m index 99b9e6f45..530a700c8 100644 --- a/Session/Signal/DateUtil.m +++ b/Session/Signal/DateUtil.m @@ -3,7 +3,7 @@ // #import "DateUtil.h" -#import +#import #import #import diff --git a/Session/Signal/FingerprintViewController.m b/Session/Signal/FingerprintViewController.m index 913d90f97..8c185f364 100644 --- a/Session/Signal/FingerprintViewController.m +++ b/Session/Signal/FingerprintViewController.m @@ -9,7 +9,7 @@ #import "UIColor+OWS.h" #import "UIFont+OWS.h" #import "UIView+OWS.h" -#import +#import #import #import #import diff --git a/Session/Signal/MainAppContext.m b/Session/Signal/MainAppContext.m index ba91b7a35..a6c020904 100644 --- a/Session/Signal/MainAppContext.m +++ b/Session/Signal/MainAppContext.m @@ -4,7 +4,7 @@ #import "MainAppContext.h" #import "Session-Swift.h" -#import +#import #import #import #import diff --git a/Session/Signal/OWSBackup.m b/Session/Signal/OWSBackup.m index 6caba8c6e..2ab57d41b 100644 --- a/Session/Signal/OWSBackup.m +++ b/Session/Signal/OWSBackup.m @@ -8,7 +8,7 @@ #import "OWSBackupImportJob.h" #import "Session-Swift.h" #import -#import +#import #import #import diff --git a/Session/Signal/OWSBackupExportJob.m b/Session/Signal/OWSBackupExportJob.m index c72df4259..54669197c 100644 --- a/Session/Signal/OWSBackupExportJob.m +++ b/Session/Signal/OWSBackupExportJob.m @@ -7,9 +7,9 @@ #import "OWSDatabaseMigration.h" #import "Session-Swift.h" #import -#import -#import -#import +#import +#import +#import #import #import #import diff --git a/Session/Signal/OWSBackupIO.m b/Session/Signal/OWSBackupIO.m index 73f499c70..ed581e2dd 100644 --- a/Session/Signal/OWSBackupIO.m +++ b/Session/Signal/OWSBackupIO.m @@ -3,7 +3,7 @@ // #import "OWSBackupIO.h" -#import +#import #import @import Compression; diff --git a/Session/Signal/OWSBackupImportJob.m b/Session/Signal/OWSBackupImportJob.m index 58c9c9b4c..fb11e8e43 100644 --- a/Session/Signal/OWSBackupImportJob.m +++ b/Session/Signal/OWSBackupImportJob.m @@ -8,7 +8,7 @@ #import "OWSDatabaseMigrationRunner.h" #import "Session-Swift.h" #import -#import +#import #import #import #import diff --git a/Session/Signal/OWSBackupJob.m b/Session/Signal/OWSBackupJob.m index 4c3494c88..92aab7714 100644 --- a/Session/Signal/OWSBackupJob.m +++ b/Session/Signal/OWSBackupJob.m @@ -6,7 +6,7 @@ #import "OWSBackupIO.h" #import "Session-Swift.h" #import -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/Session/Signal/OWSConversationSettingsViewController.m b/Session/Signal/OWSConversationSettingsViewController.m index 457d1cf12..1d53d98d8 100644 --- a/Session/Signal/OWSConversationSettingsViewController.m +++ b/Session/Signal/OWSConversationSettingsViewController.m @@ -16,7 +16,7 @@ #import "UIView+OWS.h" #import "UpdateGroupViewController.h" #import -#import +#import #import #import #import diff --git a/Session/Signal/OWSDeviceProvisioningURLParser.m b/Session/Signal/OWSDeviceProvisioningURLParser.m index a89200ec1..832e847d3 100644 --- a/Session/Signal/OWSDeviceProvisioningURLParser.m +++ b/Session/Signal/OWSDeviceProvisioningURLParser.m @@ -4,7 +4,7 @@ #import "OWSDeviceProvisioningURLParser.h" #import -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/Session/Signal/OWSOrphanDataCleaner.m b/Session/Signal/OWSOrphanDataCleaner.m index c8aab23f6..f21ba3aff 100644 --- a/Session/Signal/OWSOrphanDataCleaner.m +++ b/Session/Signal/OWSOrphanDataCleaner.m @@ -4,7 +4,7 @@ #import "OWSOrphanDataCleaner.h" #import "DateUtil.h" -#import +#import #import #import #import diff --git a/Session/Signal/Pastelog.m b/Session/Signal/Pastelog.m index 3bb77d2d0..b774ab1fc 100644 --- a/Session/Signal/Pastelog.m +++ b/Session/Signal/Pastelog.m @@ -8,7 +8,7 @@ #import "zlib.h" #import #import -#import +#import #import #import #import diff --git a/Session/Signal/PrivacySettingsTableViewController.m b/Session/Signal/PrivacySettingsTableViewController.m index de1262614..3a904983a 100644 --- a/Session/Signal/PrivacySettingsTableViewController.m +++ b/Session/Signal/PrivacySettingsTableViewController.m @@ -5,6 +5,7 @@ #import "PrivacySettingsTableViewController.h" #import "BlockListViewController.h" #import "Session-Swift.h" +#import #import #import #import diff --git a/Session/Signal/RemoteVideoView.m b/Session/Signal/RemoteVideoView.m index c94118a76..4104d5ad0 100644 --- a/Session/Signal/RemoteVideoView.m +++ b/Session/Signal/RemoteVideoView.m @@ -7,7 +7,7 @@ #import "UIView+OWS.h" #import #import -#import +#import #import #import #import diff --git a/Session/Signal/SignalApp.m b/Session/Signal/SignalApp.m index c6693b17e..cfa9e745c 100644 --- a/Session/Signal/SignalApp.m +++ b/Session/Signal/SignalApp.m @@ -7,7 +7,7 @@ #import "ConversationViewController.h" #import "Session-Swift.h" #import "SignalsNavigationController.h" -#import +#import #import #import #import diff --git a/Session/Signal/UIViewController+Permissions.m b/Session/Signal/UIViewController+Permissions.m index 1f581b23f..bed8a8800 100644 --- a/Session/Signal/UIViewController+Permissions.m +++ b/Session/Signal/UIViewController+Permissions.m @@ -6,7 +6,7 @@ #import "Session-Swift.h" #import #import -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/Session/Signal/UpdateGroupViewController.m b/Session/Signal/UpdateGroupViewController.m index 8a5ea62d9..26ffdd171 100644 --- a/Session/Signal/UpdateGroupViewController.m +++ b/Session/Signal/UpdateGroupViewController.m @@ -8,7 +8,8 @@ #import "OWSNavigationController.h" #import "Session-Swift.h" #import "ViewControllerUtils.h" -#import +#import +#import #import #import #import diff --git a/Session/Storage+Shared.swift b/Session/Storage+Shared.swift index f1ed25812..10741e332 100644 --- a/Session/Storage+Shared.swift +++ b/Session/Storage+Shared.swift @@ -8,6 +8,6 @@ extension Storage { } public func getUserPublicKey() -> String? { - return OWSIdentityManager.shared().identityKeyPair()?.publicKey()?.toHexString() + return OWSIdentityManager.shared().identityKeyPair()?.publicKey.toHexString() } } diff --git a/Session/Utilities/KeyPairUtilities.swift b/Session/Utilities/KeyPairUtilities.swift index e42a35336..d5858ea38 100644 --- a/Session/Utilities/KeyPairUtilities.swift +++ b/Session/Utilities/KeyPairUtilities.swift @@ -8,7 +8,7 @@ enum KeyPairUtilities { let ed25519KeyPair = Sodium().sign.keyPair(seed: (seed + padding).bytes)! let x25519PublicKey = Sodium().sign.toX25519(ed25519PublicKey: ed25519KeyPair.publicKey)! let x25519SecretKey = Sodium().sign.toX25519(ed25519SecretKey: ed25519KeyPair.secretKey)! - let x25519KeyPair = ECKeyPair(publicKey: Data(x25519PublicKey), privateKey: Data(x25519SecretKey)) + let x25519KeyPair = try! ECKeyPair(publicKeyData: Data(x25519PublicKey), privateKeyData: Data(x25519SecretKey)) return (ed25519KeyPair: ed25519KeyPair, x25519KeyPair: x25519KeyPair) } diff --git a/Session/View Controllers/LandingVC.swift b/Session/View Controllers/LandingVC.swift index 928384a4f..f7f2a52c7 100644 --- a/Session/View Controllers/LandingVC.swift +++ b/Session/View Controllers/LandingVC.swift @@ -132,9 +132,9 @@ final class LandingVC : BaseVC, LinkDeviceVCDelegate, DeviceLinkingModalDelegate alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), accessibilityIdentifier: nil, style: .default, handler: nil)) return present(alert, animated: true, completion: nil) } - let seed = Randomness.generateRandomBytes(16)! + let seed = Randomness.generateRandomBytes(16) preconditionFailure("This code path shouldn't be invoked.") - let keyPair = Curve25519.generateKeyPair()! + let keyPair = Curve25519.generateKeyPair() let identityManager = OWSIdentityManager.shared() let databaseConnection = identityManager.value(forKey: "dbConnection") as! YapDatabaseConnection databaseConnection.setObject(seed.toHexString(), forKey: "LKLokiSeed", inCollection: OWSPrimaryStorageIdentityKeyStoreCollection) diff --git a/Session/View Controllers/NewClosedGroupVC.swift b/Session/View Controllers/NewClosedGroupVC.swift index 468d4fb24..b550b1edd 100644 --- a/Session/View Controllers/NewClosedGroupVC.swift +++ b/Session/View Controllers/NewClosedGroupVC.swift @@ -222,7 +222,7 @@ final class NewClosedGroupVC : BaseVC, UITableViewDataSource, UITableViewDelegat } let members = selectedContacts + [ masterPublicKey ] let admins = [ masterPublicKey ] - let groupID = LKGroupUtilities.getEncodedClosedGroupIDAsData(Randomness.generateRandomBytes(kGroupIdLength)!.toHexString()) + let groupID = LKGroupUtilities.getEncodedClosedGroupIDAsData(Randomness.generateRandomBytes(kGroupIdLength).toHexString()) let group = TSGroupModel(title: name, memberIds: members, image: nil, groupId: groupID, groupType: .closedGroup, adminIds: admins) let thread = TSGroupThread.getOrCreateThread(with: group) OWSProfileManager.shared().addThread(toProfileWhitelist: thread) diff --git a/SessionMessagingKit/Open Groups/OpenGroupAPI.swift b/SessionMessagingKit/Open Groups/OpenGroupAPI.swift index 7b582952f..6690066e2 100644 --- a/SessionMessagingKit/Open Groups/OpenGroupAPI.swift +++ b/SessionMessagingKit/Open Groups/OpenGroupAPI.swift @@ -146,7 +146,7 @@ public final class OpenGroupAPI : DotNetAPI { guard let userKeyPair = storage.getUserKeyPair() else { return Promise(error: Error.generic) } guard let userDisplayName = storage.getUserDisplayName() else { return Promise(error: Error.generic) } let (promise, seal) = Promise.pending() - DispatchQueue.global(qos: .userInitiated).async { [privateKey = userKeyPair.privateKey()] in + DispatchQueue.global(qos: .userInitiated).async { [privateKey = userKeyPair.privateKey] in guard let signedMessage = message.sign(with: privateKey) else { return seal.reject(Error.signingFailed) } attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global(qos: .default)) { getOpenGroupServerPublicKey(for: server).then(on: DispatchQueue.global(qos: .default)) { serverPublicKey in @@ -166,7 +166,7 @@ public final class OpenGroupAPI : DotNetAPI { throw Error.parsingFailed } let timestamp = UInt64(date.timeIntervalSince1970) * 1000 - return OpenGroupMessage(serverID: serverID, senderPublicKey: userKeyPair.publicKey()!.toHexString(), displayName: displayName, profilePicture: signedMessage.profilePicture, body: body, type: openGroupMessageType, timestamp: timestamp, quote: signedMessage.quote, attachments: signedMessage.attachments, signature: signedMessage.signature, serverTimestamp: timestamp) + return OpenGroupMessage(serverID: serverID, senderPublicKey: userKeyPair.publicKey.toHexString(), displayName: displayName, profilePicture: signedMessage.profilePicture, body: body, type: openGroupMessageType, timestamp: timestamp, quote: signedMessage.quote, attachments: signedMessage.attachments, signature: signedMessage.signature, serverTimestamp: timestamp) } } }.handlingInvalidAuthTokenIfNeeded(for: server) diff --git a/SessionMessagingKit/Open Groups/OpenGroupMessage.swift b/SessionMessagingKit/Open Groups/OpenGroupMessage.swift index 29034606d..b562f4a58 100644 --- a/SessionMessagingKit/Open Groups/OpenGroupMessage.swift +++ b/SessionMessagingKit/Open Groups/OpenGroupMessage.swift @@ -117,8 +117,8 @@ public final class OpenGroupMessage : NSObject { SNLog("Failed to sign open group message.") return nil } - let userKeyPair = Configuration.shared.storage.getUserKeyPair() - guard let signatureData = Ed25519.sign(data, with: userKeyPair) else { + let userKeyPair = Configuration.shared.storage.getUserKeyPair()! + guard let signatureData = try? Ed25519.sign(data, with: userKeyPair) else { SNLog("Failed to sign open group message.") return nil } @@ -130,7 +130,7 @@ public final class OpenGroupMessage : NSObject { guard let signature = signature else { return false } guard let data = getValidationData(for: signature.version) else { return false } let publicKey = Data(hex: self.senderPublicKey.removing05PrefixIfNeeded()) - return Ed25519.verifySignature(signature.data, publicKey: publicKey, data: data) + return (try? Ed25519.verifySignature(signature.data, publicKey: publicKey, data: data)) ?? false } // MARK: JSON diff --git a/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift b/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift index 1ab2b7570..df64a9062 100644 --- a/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift +++ b/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift @@ -28,13 +28,12 @@ internal extension MessageReceiver { throw Error.noGroupPrivateKey } let groupPrivateKey = Data(hex: hexEncodedGroupPrivateKey) - let groupKeyPair = ECKeyPair(publicKey: Data(hex: groupPublicKey), privateKey: groupPrivateKey) // 2. ) Parse the wrapper let wrapper = try SNProtoClosedGroupCiphertextMessageWrapper.parseData(data) let ivAndCiphertext = wrapper.ciphertext let ephemeralPublicKey = wrapper.ephemeralPublicKey // 3. ) Decrypt the data inside - guard let ephemeralSharedSecret = Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey, andKeyPair: groupKeyPair) else { + guard let ephemeralSharedSecret = try? Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey, privateKey: groupPrivateKey) else { throw Error.sharedSecretGenerationFailed } let salt = "LOKI" diff --git a/SessionMessagingKit/Utilities/DotNetAPI.swift b/SessionMessagingKit/Utilities/DotNetAPI.swift index 34f67d6d5..1baf4b7d5 100644 --- a/SessionMessagingKit/Utilities/DotNetAPI.swift +++ b/SessionMessagingKit/Utilities/DotNetAPI.swift @@ -4,6 +4,7 @@ import PromiseKit import SessionProtocolKit import SessionSnodeKit import SessionUtilitiesKit +import SignalCoreKit /// Base class for `FileServerAPI` and `OpenGroupAPI`. public class DotNetAPI : NSObject { @@ -40,7 +41,7 @@ public class DotNetAPI : NSObject { private static func requestNewAuthToken(for server: String) -> Promise { SNLog("Requesting auth token for server: \(server).") guard let userKeyPair = Configuration.shared.storage.getUserKeyPair() else { return Promise(error: Error.generic) } - let queryParameters = "pubKey=\(userKeyPair.publicKey().toHexString())" + let queryParameters = "pubKey=\(userKeyPair.publicKey.toHexString())" let url = URL(string: "\(server)/loki/v1/get_challenge?\(queryParameters)")! let request = TSRequest(url: url) let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.publicKey) @@ -56,10 +57,10 @@ public class DotNetAPI : NSObject { if serverPublicKey.count == 33 { let hexEncodedServerPublicKey = serverPublicKey.toHexString() let startIndex = hexEncodedServerPublicKey.index(hexEncodedServerPublicKey.startIndex, offsetBy: 2) - serverPublicKey = Data.data(fromHex: String(hexEncodedServerPublicKey[startIndex.. #import #import -#import #import #import #import -#import -#import -#import -#import -#import -#import #import #import #import #import -#import diff --git a/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m b/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m index 9ad1b9c42..9720923b3 100644 --- a/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m +++ b/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m @@ -1,6 +1,6 @@ #import "ClosedGroupCiphertextMessage.h" #import "AxolotlExceptions.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m b/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m index 69b78a856..e011fc666 100644 --- a/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m +++ b/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m @@ -7,8 +7,8 @@ #import "Constants.h" #import "SerializationUtilities.h" #import -#import -#import +#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m b/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m index 1489ccecf..9c0526dc5 100644 --- a/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m +++ b/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m @@ -7,10 +7,11 @@ #import "Constants.h" #import "NSData+keyVersionByte.h" #import "SerializationUtilities.h" -#import +#import #import -#import -#import +#import +#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/Crypto/AES-CBC.m b/SessionProtocolKit/Signal/Crypto/AES-CBC.m index 84612ff47..720157b6e 100644 --- a/SessionProtocolKit/Signal/Crypto/AES-CBC.m +++ b/SessionProtocolKit/Signal/Crypto/AES-CBC.m @@ -8,7 +8,7 @@ #import #import #import -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/ECPrivateKey.swift b/SessionProtocolKit/Signal/ECPrivateKey.swift deleted file mode 100644 index 2af140eef..000000000 --- a/SessionProtocolKit/Signal/ECPrivateKey.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -// See: -// https://github.com/signalapp/libsignal-protocol-java/blob/87fae0f98332e98a32bbb82515428b4edeb4181f/java/src/main/java/org/whispersystems/libsignal/ecc/ECPrivateKey.java -@objc public class ECPrivateKey: NSObject { - - @objc - public let keyData: Data - - @objc - public init(keyData: Data) throws { - guard keyData.count == ECCKeyLength else { - throw SMKError.assertionError(description: "\(ECPrivateKey.logTag) key has invalid length") - } - - self.keyData = keyData - } - - open override func isEqual(_ object: Any?) -> Bool { - if let object = object as? ECPrivateKey { - return keyData == object.keyData - } else { - return false - } - } - - public override var hash: Int { - return keyData.hashValue - } -} diff --git a/SessionProtocolKit/Signal/ECPublicKey.swift b/SessionProtocolKit/Signal/ECPublicKey.swift deleted file mode 100644 index a27d985b2..000000000 --- a/SessionProtocolKit/Signal/ECPublicKey.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -// See: -// https://github.com/signalapp/libsignal-protocol-java/blob/87fae0f98332e98a32bbb82515428b4edeb4181f/java/src/main/java/org/whispersystems/libsignal/ecc/DjbECPublicKey.java -@objc public class ECPublicKey: NSObject { - - @objc - public static let keyTypeDJB: UInt8 = 0x05 - - @objc - public let keyData: Data - - @objc - public init(keyData: Data) throws { - guard keyData.count == ECCKeyLength else { - throw SMKError.assertionError(description: "\(ECPublicKey.logTag) key has invalid length") - } - - self.keyData = keyData - } - - // https://github.com/signalapp/libsignal-protocol-java/blob/master/java/src/main/java/org/whispersystems/libsignal/ecc/Curve.java#L30 - @objc - public init(serializedKeyData: Data) throws { - let parser = OWSDataParser(data: serializedKeyData) - - let typeByte = try parser.nextByte(name: "type byte") - guard typeByte == ECPublicKey.keyTypeDJB else { - throw SMKError.assertionError(description: "\(ECPublicKey.logTag) key data has invalid type byte") - } - - let keyData = try parser.remainder(name: "key data") - guard keyData.count == ECCKeyLength else { - throw SMKError.assertionError(description: "\(ECPublicKey.logTag) key has invalid length") - } - - self.keyData = keyData - } - - @objc public var serialized: Data { - let typeBytes = [ECPublicKey.keyTypeDJB] - let typeData = Data(bytes: typeBytes) - return NSData.join([typeData, keyData]) - } - - open override func isEqual(_ object: Any?) -> Bool { - if let object = object as? ECPublicKey { - return keyData == object.keyData - } else { - return false - } - } - - public override var hash: Int { - return keyData.hashValue - } -} diff --git a/SessionProtocolKit/Signal/FallbackSessionCipher.swift b/SessionProtocolKit/Signal/FallbackSessionCipher.swift index 8d3992744..897f44c60 100644 --- a/SessionProtocolKit/Signal/FallbackSessionCipher.swift +++ b/SessionProtocolKit/Signal/FallbackSessionCipher.swift @@ -20,8 +20,7 @@ import SessionUtilitiesKit private lazy var symmetricKey: Data? = { guard let privateKey = privateKey else { return nil } - let keyPair = ECKeyPair(publicKey: recipientPublicKeyAsData, privateKey: privateKey) - return Curve25519.generateSharedSecret(fromPublicKey: recipientPublicKeyAsData, andKeyPair: keyPair) + return try? Curve25519.generateSharedSecret(fromPublicKey: recipientPublicKeyAsData, privateKey: privateKey) }() @objc public init(recipientPublicKey: String, privateKey: Data?) { diff --git a/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m b/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m index d45cb2e8b..b420eb84f 100644 --- a/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m +++ b/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m @@ -7,7 +7,7 @@ // #import "PreKeyBundle.h" -#import +#import static NSString* const kCoderPKBIdentityKey = @"kCoderPKBIdentityKey"; diff --git a/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m b/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m index 7ee04c837..13c8e4c8b 100644 --- a/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m +++ b/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m @@ -7,7 +7,7 @@ // #import "PreKeyRecord.h" -#import +#import static NSString* const kCoderPreKeyId = @"kCoderPreKeyId"; static NSString* const kCoderPreKeyPair = @"kCoderPreKeyPair"; diff --git a/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m b/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m index 1fbed9994..46d3e25e6 100644 --- a/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m +++ b/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m @@ -3,7 +3,7 @@ // #import "SignedPrekeyRecord.h" -#import +#import static NSString* const kCoderPreKeyId = @"kCoderPreKeyId"; static NSString* const kCoderPreKeyPair = @"kCoderPreKeyPair"; diff --git a/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m b/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m index 979b0cc2d..10d3189a5 100644 --- a/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m +++ b/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m @@ -7,7 +7,7 @@ // #import "AliceAxolotlParameters.h" -#import +#import @implementation AliceAxolotlParameters diff --git a/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m b/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m index def81109f..1d1f83a5b 100644 --- a/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m +++ b/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m @@ -7,7 +7,7 @@ // #import "BobAxolotlParameters.h" -#import +#import @implementation BobAxolotlParameters diff --git a/SessionProtocolKit/Signal/Ratchet/ChainKey.m b/SessionProtocolKit/Signal/Ratchet/ChainKey.m index 1cafdec7d..5ac5d146e 100644 --- a/SessionProtocolKit/Signal/Ratchet/ChainKey.m +++ b/SessionProtocolKit/Signal/Ratchet/ChainKey.m @@ -6,7 +6,7 @@ #import "TSDerivedSecrets.h" #import #import -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/Ratchet/MessageKeys.m b/SessionProtocolKit/Signal/Ratchet/MessageKeys.m index cc14fff0b..7cb2af79f 100644 --- a/SessionProtocolKit/Signal/Ratchet/MessageKeys.m +++ b/SessionProtocolKit/Signal/Ratchet/MessageKeys.m @@ -7,7 +7,7 @@ // #import "MessageKeys.h" -#import +#import static NSString* const kCoderMessageKeysCipherKey = @"kCoderMessageKeysCipherKey"; static NSString* const kCoderMessageKeysMacKey = @"kCoderMessageKeysMacKey"; diff --git a/SessionProtocolKit/Signal/Ratchet/RKCK.m b/SessionProtocolKit/Signal/Ratchet/RKCK.m index e1c8c1506..7aade2d12 100644 --- a/SessionProtocolKit/Signal/Ratchet/RKCK.m +++ b/SessionProtocolKit/Signal/Ratchet/RKCK.m @@ -5,7 +5,7 @@ #import "RKCK.h" #import #import "TSDerivedSecrets.h" -#import +#import @implementation RKCK diff --git a/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m b/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m index 82d602f88..a7fc66ee3 100644 --- a/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m +++ b/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m @@ -10,8 +10,8 @@ #import "SessionState.h" #import #import -#import -#import +#import +#import @interface DHEResult : NSObject @@ -140,28 +140,28 @@ if ([parameters isKindOfClass:[AliceAxolotlParameters class]]) { AliceAxolotlParameters *params = (AliceAxolotlParameters*)parameters; - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirSignedPreKey - andKeyPair:params.ourIdentityKeyPair]]; - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirIdentityKey - andKeyPair:params.ourBaseKey]]; - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirSignedPreKey - andKeyPair:params.ourBaseKey]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirSignedPreKey + andKeyPair:params.ourIdentityKeyPair]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirIdentityKey + andKeyPair:params.ourBaseKey]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirSignedPreKey + andKeyPair:params.ourBaseKey]]; if (params.theirOneTimePrekey) { - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirOneTimePrekey - andKeyPair:params.ourBaseKey]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirOneTimePrekey + andKeyPair:params.ourBaseKey]]; } } else if ([parameters isKindOfClass:[BobAxolotlParameters class]]){ BobAxolotlParameters *params = (BobAxolotlParameters*)parameters; - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirIdentityKey - andKeyPair:params.ourSignedPrekey]]; - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirBaseKey - andKeyPair:params.ourIdentityKeyPair]]; - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirBaseKey - andKeyPair:params.ourSignedPrekey]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirIdentityKey + andKeyPair:params.ourSignedPrekey]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirBaseKey + andKeyPair:params.ourIdentityKeyPair]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirBaseKey + andKeyPair:params.ourSignedPrekey]]; if (params.ourOneTimePrekey) { - [masterKey appendData:[Curve25519 generateSharedSecretFromPublicKey:params.theirBaseKey - andKeyPair:params.ourOneTimePrekey]]; + [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirBaseKey + andKeyPair:params.ourOneTimePrekey]]; } } diff --git a/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m b/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m index 012113851..c489c67ab 100644 --- a/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m +++ b/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m @@ -7,7 +7,7 @@ // #import "ReceivingChain.h" -#import +#import @interface ReceivingChain () diff --git a/SessionProtocolKit/Signal/Ratchet/RootKey.m b/SessionProtocolKit/Signal/Ratchet/RootKey.m index 170794138..fd905642d 100644 --- a/SessionProtocolKit/Signal/Ratchet/RootKey.m +++ b/SessionProtocolKit/Signal/Ratchet/RootKey.m @@ -7,7 +7,7 @@ #import "RKCK.h" #import "TSDerivedSecrets.h" #import -#import +#import static NSString* const kCoderData = @"kCoderData"; @@ -48,7 +48,7 @@ static NSString* const kCoderData = @"kCoderData"; OWSAssert(theirEphemeral); OWSAssert(ourEphemeral); - NSData *sharedSecret = [Curve25519 generateSharedSecretFromPublicKey:theirEphemeral andKeyPair:ourEphemeral]; + NSData *sharedSecret = [Curve25519 throws_generateSharedSecretFromPublicKey:theirEphemeral andKeyPair:ourEphemeral]; OWSAssert(sharedSecret.length == 32); TSDerivedSecrets *secrets = diff --git a/SessionProtocolKit/Signal/Ratchet/SendingChain.m b/SessionProtocolKit/Signal/Ratchet/SendingChain.m index 768c634d0..10502f6d0 100644 --- a/SessionProtocolKit/Signal/Ratchet/SendingChain.m +++ b/SessionProtocolKit/Signal/Ratchet/SendingChain.m @@ -4,7 +4,7 @@ #import "SendingChain.h" #import "ChainKey.h" -#import +#import @interface SendingChain () diff --git a/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m b/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m index 0aa8eda75..931d13cf2 100644 --- a/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m +++ b/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m @@ -4,7 +4,7 @@ #import "TSDerivedSecrets.h" #import -#import +#import #import @implementation TSDerivedSecrets diff --git a/SessionProtocolKit/Signal/SMKCertificateValidator.swift b/SessionProtocolKit/Signal/SMKCertificateValidator.swift index 4f4a7b7d5..da8b7efbd 100644 --- a/SessionProtocolKit/Signal/SMKCertificateValidator.swift +++ b/SessionProtocolKit/Signal/SMKCertificateValidator.swift @@ -3,6 +3,7 @@ // import Foundation +import SignalCoreKit public enum SMKCertificateError: Error { case invalidCertificate(description: String) diff --git a/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift b/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift index 2289b8cf8..2d7e2813f 100644 --- a/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift +++ b/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift @@ -4,6 +4,7 @@ import Foundation import HKDFKit +import SignalCoreKit @objc public class SecretSessionKnownSenderError: NSObject, CustomNSError { @@ -38,32 +39,6 @@ public enum SMKSecretSessionCipherError: Int, Error { case selfSentMessage } -// See: -// https://github.com/signalapp/libsignal-metadata-java/blob/master/java/src/main/java/org/signal/libsignal/metadata/SecretSessionCipher.java - -public extension ECKeyPair { - - // TODO: Rename to publicKey(), rename existing publicKey() method to publicKeyData(). - func ecPublicKey() throws -> ECPublicKey { - guard publicKey().count == ECCKeyLength else { - throw SMKError.assertionError(description: "\(logTag) public key has invalid length") - } - - // NOTE: we don't use ECPublicKey(serializedKeyData:) since the - // key data should not have a type byte. - return try ECPublicKey(keyData: publicKey()) - } - - // TODO: Rename to privateKey(), rename existing privateKey() method to privateKeyData(). - func ecPrivateKey() throws -> ECPrivateKey { - guard privateKey().count == ECCKeyLength else { - throw SMKError.assertionError(description: "\(logTag) private key has invalid length") - } - - return try ECPrivateKey(keyData: privateKey()) - } -} - // MARK: - private class SMKSecretKeySpec: NSObject { @@ -182,7 +157,7 @@ public class SMKDecryptResult: NSObject { let encryptedMessage: CipherMessage if useFallbackSessionCipher { - let cipher = FallBackSessionCipher(recipientPublicKey: recipientPublicKey, privateKey: try ourIdentityKeyPair.privateKey()) + let cipher = FallBackSessionCipher(recipientPublicKey: recipientPublicKey, privateKey: try ourIdentityKeyPair.privateKey) let ivAndCiphertext = cipher.encrypt(paddedPlaintext)! encryptedMessage = FallbackMessage(_throws_with: ivAndCiphertext) } else { @@ -207,7 +182,7 @@ public class SMKDecryptResult: NSObject { // key data should not have a type byte. let theirIdentityKey = try ECPublicKey(keyData: theirIdentityKeyData) - let ephemeral = Curve25519.generateKeyPair()! + let ephemeral = Curve25519.generateKeyPair() guard let prefixData = kUDPrefixString.data(using: String.Encoding.utf8) else { throw SMKError.assertionError(description: "\(logTag) Could not encode prefix.") @@ -388,8 +363,7 @@ public class SMKDecryptResult: NSObject { // // See: // https://github.com/signalapp/libsignal-protocol-java/blob/master/java/src/main/java/org/whispersystems/libsignal/ecc/Curve.java#L30 - let keyPair = ECKeyPair(publicKey: ephemeralPublicKey.keyData, privateKey: ephemeralPrivateKey.keyData) - let ephemeralSecret = try Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey.keyData, andKeyPair: keyPair) + let ephemeralSecret = try Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey.keyData, privateKey: ephemeralPrivateKey.keyData) // byte[] ephemeralDerived = new HKDFv3().deriveSecrets(ephemeralSecret, salt, new byte[0], 96); let kEphemeralDerivedLength: UInt = 96 @@ -429,8 +403,7 @@ public class SMKDecryptResult: NSObject { // // See: // https://github.com/signalapp/libsignal-protocol-java/blob/master/java/src/main/java/org/whispersystems/libsignal/ecc/Curve.java#L30 - let keyPair = ECKeyPair(publicKey: staticPublicKey.keyData, privateKey: staticPrivateKey.keyData) - let staticSecret = Curve25519.generateSharedSecret(fromPublicKey: staticPublicKey.keyData, andKeyPair: keyPair) + let staticSecret = try Curve25519.generateSharedSecret(fromPublicKey: staticPublicKey.keyData, privateKey: staticPrivateKey.keyData) // byte[] staticDerived = new HKDFv3().deriveSecrets(staticSecret, salt, new byte[0], 96); let kStaticDerivedLength: UInt = 96 @@ -509,7 +482,7 @@ public class SMKDecryptResult: NSObject { case .prekey: cipherMessage = try PreKeyWhisperMessage(data: messageContent.contentData) case .fallback: - let privateKey = try? identityStore.identityKeyPair(protocolContext)?.privateKey() + let privateKey = try? identityStore.identityKeyPair(protocolContext)?.privateKey let cipher = FallBackSessionCipher(recipientPublicKey: senderRecipientId, privateKey: privateKey) let plaintext = cipher.decrypt(messageContent.contentData)! return plaintext diff --git a/SessionProtocolKit/Signal/SMKUDAccessKey.swift b/SessionProtocolKit/Signal/SMKUDAccessKey.swift index a0c312473..70ec3b9c3 100644 --- a/SessionProtocolKit/Signal/SMKUDAccessKey.swift +++ b/SessionProtocolKit/Signal/SMKUDAccessKey.swift @@ -3,6 +3,7 @@ // import Foundation +import SignalCoreKit @objc public class SMKUDAccessKey: NSObject { @@ -22,7 +23,7 @@ public class SMKUDAccessKey: NSObject { // We derive the "ud access key" from the private key by encrypting zeroes. let emptyPlaintextLength = 16 let emptyPlaintext = Data(count: Int(emptyPlaintextLength)) - let initializationVector = Data(count: Int(kAESGCM256_IVLength)) + let initializationVector = Data(count: Int(kAESGCM256_DefaultIVLength)) guard let keyData = Cryptography.encryptAESGCM(plainTextData: emptyPlaintext, initializationVector: initializationVector, additionalAuthenticatedData: nil, diff --git a/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift b/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift index 5592d2e05..d536d7d60 100644 --- a/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift +++ b/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift @@ -3,6 +3,7 @@ // import Foundation +import SignalCoreKit // https://github.com/signalapp/libsignal-metadata-java/blob/master/java/src/main/java/org/signal/libsignal/metadata/protocol/UnidentifiedSenderMessage.java @objc public class SMKUnidentifiedSenderMessage: NSObject { diff --git a/SessionProtocolKit/Signal/SessionCipher.m b/SessionProtocolKit/Signal/SessionCipher.m index 7b2cbeece..ed5adef81 100644 --- a/SessionProtocolKit/Signal/SessionCipher.m +++ b/SessionProtocolKit/Signal/SessionCipher.m @@ -19,8 +19,9 @@ #import #import #import -#import -#import +#import +#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/Sessions/SessionBuilder.m b/SessionProtocolKit/Signal/Sessions/SessionBuilder.m index f50bd1faf..2961c08c9 100644 --- a/SessionProtocolKit/Signal/Sessions/SessionBuilder.m +++ b/SessionProtocolKit/Signal/Sessions/SessionBuilder.m @@ -15,9 +15,9 @@ #import "SessionState.h" #import #import -#import -#import -#import +#import +#import +#import NS_ASSUME_NONNULL_BEGIN @@ -106,9 +106,9 @@ const int kPreKeyOfLastResortId = 0xFFFFFF; } // NOTE: we use preKeyBundle.signedPreKeyPublic which has the key type byte. - if (![Ed25519 verifySignature:preKeyBundle.signedPreKeySignature - publicKey:theirIdentityKey - data:preKeyBundle.signedPreKeyPublic]) { + if (![Ed25519 throws_verifySignature:preKeyBundle.signedPreKeySignature + publicKey:theirIdentityKey + data:preKeyBundle.signedPreKeyPublic]) { @throw [NSException exceptionWithName:InvalidKeyException reason:@"KeyIsNotValidlySigned" userInfo:nil]; } diff --git a/SessionProtocolKit/Signal/Sessions/SessionRecord.m b/SessionProtocolKit/Signal/Sessions/SessionRecord.m index 54d8267fb..32fc95da0 100644 --- a/SessionProtocolKit/Signal/Sessions/SessionRecord.m +++ b/SessionProtocolKit/Signal/Sessions/SessionRecord.m @@ -3,7 +3,7 @@ // #import "SessionRecord.h" -#import +#import #define ARCHIVED_STATES_MAX_LENGTH 40 diff --git a/SessionProtocolKit/Signal/Sessions/SessionState.m b/SessionProtocolKit/Signal/Sessions/SessionState.m index 5807d6c9f..f877c539e 100644 --- a/SessionProtocolKit/Signal/Sessions/SessionState.m +++ b/SessionProtocolKit/Signal/Sessions/SessionState.m @@ -7,7 +7,7 @@ #import "ReceivingChain.h" #import "SendingChain.h" #import "ChainAndIndex.h" -#import +#import @implementation PendingPreKey diff --git a/SessionProtocolKit/Signal/Utility/Cryptography.h b/SessionProtocolKit/Signal/Utility/Cryptography.h deleted file mode 100644 index f7ea09bfe..000000000 --- a/SessionProtocolKit/Signal/Utility/Cryptography.h +++ /dev/null @@ -1,161 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -extern const NSUInteger kAES256_KeyByteLength; -extern const NSUInteger kAESGCM256_IVLength; -extern const NSUInteger kAES256CTR_IVLength; - -extern const NSUInteger SCKErrorCodeFailedToDecryptMessage; - -/// Key appropriate for use in AES256-GCM -@interface OWSAES256Key : NSObject - -/// Generates new secure random key -- (instancetype)init; -+ (instancetype)generateRandomKey; - -/** - * @param data representing the raw key bytes - * - * @returns a new instance if key is of appropriate length for AES256-GCM - * else returns nil. - */ -+ (nullable instancetype)keyWithData:(NSData *)data; - -/// The raw key material -@property (nonatomic, readonly) NSData *keyData; - -@end - -#pragma mark - - -// TODO: This class should probably be renamed to: AES256GCMEncryptionResult -// (note the missing 6 in 256). -@interface AES25GCMEncryptionResult : NSObject - -@property (nonatomic, readonly) NSData *ciphertext; -@property (nonatomic, readonly) NSData *initializationVector; -@property (nonatomic, readonly) NSData *authTag; - -- (instancetype)init NS_UNAVAILABLE; -- (nullable instancetype)initWithCipherText:(NSData *)cipherText - initializationVector:(NSData *)initializationVector - authTag:(NSData *)authTag NS_DESIGNATED_INITIALIZER; - -@end - -#pragma mark - - -@interface AES256CTREncryptionResult : NSObject - -@property (nonatomic, readonly) NSData *ciphertext; -@property (nonatomic, readonly) NSData *initializationVector; - -- (instancetype)init NS_UNAVAILABLE; -- (nullable instancetype)initWithCiphertext:(NSData *)ciphertext - initializationVector:(NSData *)initializationVector NS_DESIGNATED_INITIALIZER; - -@end - -#pragma mark - - -@interface Cryptography : NSObject - -typedef NS_ENUM(NSInteger, TSMACType) { - TSHMACSHA256Truncated10Bytes = 2, - TSHMACSHA256AttachementType = 3 -}; - -+ (NSData *)generateRandomBytes:(NSUInteger)numberBytes; - -+ (uint32_t)randomUInt32; -+ (uint64_t)randomUInt64; -+ (unsigned)randomUnsigned; - -#pragma mark - SHA and HMAC methods - -// Full length SHA256 digest for `data` -+ (nullable NSData *)computeSHA256Digest:(NSData *)data; - -// Truncated SHA256 digest for `data` -+ (nullable NSData *)computeSHA256Digest:(NSData *)data truncatedToBytes:(NSUInteger)truncatedBytes; - -+ (nullable NSString *)truncatedSHA1Base64EncodedWithoutPadding:(NSString *)string; - -+ (nullable NSData *)decryptAppleMessagePayload:(NSData *)payload withSignalingKey:(NSString *)signalingKeyString; - -+ (nullable NSData *)computeSHA256HMAC:(NSData *)data withHMACKey:(NSData *)HMACKey; - -+ (nullable NSData *)truncatedSHA256HMAC:(NSData *)dataToHMAC - withHMACKey:(NSData *)HMACKey - truncation:(NSUInteger)truncation; - -#pragma mark - Attachments & Stickers - -// Though digest can and will be nil for legacy clients, we now reject attachments lacking a digest. -+ (nullable NSData *)decryptAttachment:(NSData *)dataToDecrypt - withKey:(NSData *)key - digest:(nullable NSData *)digest - unpaddedSize:(UInt32)unpaddedSize - error:(NSError **)error; - -+ (nullable NSData *)decryptStickerData:(NSData *)dataToDecrypt - withKey:(NSData *)key - error:(NSError **)error; - -+ (nullable NSData *)encryptAttachmentData:(NSData *)attachmentData - outKey:(NSData *_Nonnull *_Nullable)outKey - outDigest:(NSData *_Nonnull *_Nullable)outDigest; - -#pragma mark - AES-GCM - -+ (nullable AES25GCMEncryptionResult *)encryptAESGCMWithData:(NSData *)plaintext - additionalAuthenticatedData:(nullable NSData *)additionalAuthenticatedData - key:(OWSAES256Key *)key - NS_SWIFT_NAME(encryptAESGCM(plainTextData:additionalAuthenticatedData:key:)); - -+ (nullable AES25GCMEncryptionResult *)encryptAESGCMWithData:(NSData *)plaintext - initializationVector:(NSData *)initializationVector - additionalAuthenticatedData:(nullable NSData *)additionalAuthenticatedData - key:(OWSAES256Key *)key - NS_SWIFT_NAME(encryptAESGCM(plainTextData:initializationVector:additionalAuthenticatedData:key:)); - -+ (nullable NSData *)decryptAESGCMWithInitializationVector:(NSData *)initializationVector - ciphertext:(NSData *)ciphertext - additionalAuthenticatedData:(nullable NSData *)additionalAuthenticatedData - authTag:(NSData *)authTagFromEncrypt - key:(OWSAES256Key *)key - NS_SWIFT_NAME(decryptAESGCM(withInitializationVector:ciphertext:additionalAuthenticatedData:authTag:key:)); - -#pragma mark - Profiles - -+ (nullable NSData *)encryptAESGCMWithProfileData:(NSData *)plaintextData key:(OWSAES256Key *)key - NS_SWIFT_NAME(encryptAESGCMProfileData(plainTextData:key:)); - -+ (nullable NSData *)decryptAESGCMWithProfileData:(NSData *)encryptedData key:(OWSAES256Key *)key - NS_SWIFT_NAME(decryptAESGCMProfileData(encryptedData:key:)); - -#pragma mark - AES-CTR - -+ (nullable AES256CTREncryptionResult *)encryptAESCTRWithData:(NSData *)plaintext - initializationVector:(NSData *)initializationVector - key:(OWSAES256Key *)key - NS_SWIFT_NAME(encryptAESCTR(plaintextData:initializationVector:key:)); - -+ (nullable NSData *)decryptAESCTRWithCipherText:(NSData *)cipherText - initializationVector:(NSData *)initializationVector - key:(OWSAES256Key *)key - NS_SWIFT_NAME(decryptAESCTR(cipherText:initializationVector:key:)); - -#pragma mark - - -+ (void)seedRandom; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/Cryptography.m b/SessionProtocolKit/Signal/Utility/Cryptography.m deleted file mode 100644 index 5d9a5c402..000000000 --- a/SessionProtocolKit/Signal/Utility/Cryptography.m +++ /dev/null @@ -1,1074 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import -#import "Cryptography.h" -#import "NSData+OWS.h" -#import -#import -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -#define HMAC256_KEY_LENGTH 32 -#define HMAC256_OUTPUT_LENGTH 32 -#define AES_CBC_IV_LENGTH 16 -#define AES_KEY_SIZE 32 - -NSString *const SignalCoreKitErrorDomain = @"SignalCoreKitErrorDomain"; - -const NSUInteger SCKErrorCodeFailedToDecryptMessage = 100; - -NSError *SCKErrorWithCodeDescription(NSUInteger code, NSString *description) -{ - return [NSError errorWithDomain:SignalCoreKitErrorDomain - code:code - userInfo:@{ NSLocalizedDescriptionKey: description }]; -} - -// Returned by many OpenSSL functions - indicating success -const int kOpenSSLSuccess = 1; - -// length of initialization nonce for AES256-GCM -const NSUInteger kAESGCM256_IVLength = 12; - -const NSUInteger kAES256CTR_IVLength = 16; - -// length of authentication tag for AES256-GCM -static const NSUInteger kAESGCM256_TagLength = 16; - -// length of key used for websocket envelope authentication -static const NSUInteger kHMAC256_EnvelopeKeyLength = 20; - -const NSUInteger kAES256_KeyByteLength = 32; - -@implementation OWSAES256Key - -+ (nullable instancetype)keyWithData:(NSData *)data -{ - if (data.length != kAES256_KeyByteLength) { - OWSLogError(@"Invalid key length: %lu", (unsigned long)data.length); - return nil; - } - - return [[self alloc] initWithData:data]; -} - -+ (instancetype)generateRandomKey -{ - return [self new]; -} - -- (instancetype)init -{ - return [self initWithData:[Cryptography generateRandomBytes:kAES256_KeyByteLength]]; -} - -- (instancetype)initWithData:(NSData *)data -{ - self = [super init]; - if (!self) { - return self; - } - - _keyData = data; - - return self; -} - -#pragma mark - SecureCoding - -+ (BOOL)supportsSecureCoding -{ - return YES; -} - -- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder -{ - self = [super init]; - if (!self) { - return self; - } - - NSData *keyData = [aDecoder decodeObjectOfClass:[NSData class] forKey:@"keyData"]; - if (keyData.length != kAES256_KeyByteLength) { - OWSFailDebug(@"Invalid key length: %lu", (unsigned long)keyData.length); - return nil; - } - - _keyData = keyData; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder -{ - [aCoder encodeObject:_keyData forKey:@"keyData"]; -} - -@end - -#pragma mark - - -@implementation AES25GCMEncryptionResult - -- (nullable instancetype)initWithCipherText:(NSData *)cipherText - initializationVector:(NSData *)initializationVector - authTag:(NSData *)authTag -{ - self = [super init]; - if (!self) { - return self; - } - - _ciphertext = [cipherText copy]; - _initializationVector = [initializationVector copy]; - _authTag = [authTag copy]; - - if (_ciphertext == nil || _initializationVector.length != kAESGCM256_IVLength - || _authTag.length != kAESGCM256_TagLength) { - return nil; - } - - return self; -} - -@end - -#pragma mark - - -@implementation AES256CTREncryptionResult - -- (nullable instancetype)initWithCiphertext:(NSData *)ciphertext initializationVector:(NSData *)initializationVector -{ - self = [super init]; - if (!self) { - return self; - } - - _ciphertext = [ciphertext copy]; - _initializationVector = [initializationVector copy]; - - if (_ciphertext == nil) { - OWSFail(@"Missing cipher text."); - return nil; - } - if (_initializationVector.length != kAES256CTR_IVLength) { - OWSFail(@"Invalid initialization vector."); - return nil; - } - - return self; -} - -@end - -#pragma mark - - -@implementation Cryptography - -+ (NSString *)logTag -{ - return @"AES25GCMEncryptionResult"; -} - -#pragma mark - random bytes methods - -+ (NSData *)generateRandomBytes:(NSUInteger)numberBytes -{ - return [Randomness generateRandomBytes:(int)numberBytes]; -} - -+ (uint32_t)randomUInt32 -{ - size_t size = sizeof(uint32_t); - NSData *data = [self generateRandomBytes:size]; - uint32_t result = 0; - [data getBytes:&result range:NSMakeRange(0, size)]; - return result; -} - -+ (uint64_t)randomUInt64 -{ - size_t size = sizeof(uint64_t); - NSData *data = [self generateRandomBytes:size]; - uint64_t result = 0; - [data getBytes:&result range:NSMakeRange(0, size)]; - return result; -} - -+ (unsigned)randomUnsigned -{ - size_t size = sizeof(unsigned); - NSData *data = [self generateRandomBytes:size]; - unsigned result = 0; - [data getBytes:&result range:NSMakeRange(0, size)]; - return result; -} - -#pragma mark - SHA1 - -// Used by TSContactManager to send hashed/truncated contact list to server. -+ (nullable NSString *)truncatedSHA1Base64EncodedWithoutPadding:(NSString *)string -{ - NSData *_Nullable stringData = [string dataUsingEncoding:NSUTF8StringEncoding]; - if (!stringData) { - OWSFailDebug(@"could not convert string to utf-8."); - return nil; - } - if (stringData.length >= UINT32_MAX) { - OWSFailDebug(@"string data is too long."); - return nil; - } - uint32_t dataLength = (uint32_t)stringData.length; - - NSMutableData *_Nullable hashData = [NSMutableData dataWithLength:20]; - if (!hashData) { - OWSFail(@"Could not allocate buffer."); - } - CC_SHA1(stringData.bytes, dataLength, hashData.mutableBytes); - - NSData *truncatedData = [hashData subdataWithRange:NSMakeRange(0, 10)]; - return [[truncatedData base64EncodedString] stringByReplacingOccurrencesOfString:@"=" withString:@""]; -} - -#pragma mark - SHA256 Digest - -+ (nullable NSData *)computeSHA256Digest:(NSData *)data -{ - return [self computeSHA256Digest:data truncatedToBytes:CC_SHA256_DIGEST_LENGTH]; -} - -+ (nullable NSData *)computeSHA256Digest:(NSData *)data truncatedToBytes:(NSUInteger)truncatedBytes -{ - if (data.length >= UINT32_MAX) { - OWSFailDebug(@"data is too long."); - return nil; - } - uint32_t dataLength = (uint32_t)data.length; - - NSMutableData *_Nullable digestData = [[NSMutableData alloc] initWithLength:CC_SHA256_DIGEST_LENGTH]; - if (!digestData) { - OWSFailDebug(@"could not allocate buffer."); - return nil; - } - CC_SHA256(data.bytes, dataLength, digestData.mutableBytes); - return [digestData subdataWithRange:NSMakeRange(0, truncatedBytes)]; -} - -#pragma mark - HMAC/SHA256 - -+ (nullable NSData *)computeSHA256HMAC:(NSData *)data withHMACKey:(NSData *)HMACKey -{ - if (data.length >= SIZE_MAX) { - OWSFailDebug(@"data is too long."); - return nil; - } - size_t dataLength = (size_t)data.length; - if (HMACKey.length >= SIZE_MAX) { - OWSFailDebug(@"HMAC key is too long."); - return nil; - } - size_t hmacKeyLength = (size_t)HMACKey.length; - - NSMutableData *_Nullable ourHmacData = [[NSMutableData alloc] initWithLength:CC_SHA256_DIGEST_LENGTH]; - if (!ourHmacData) { - OWSFailDebug(@"could not allocate buffer."); - return nil; - } - CCHmac(kCCHmacAlgSHA256, [HMACKey bytes], hmacKeyLength, [data bytes], dataLength, ourHmacData.mutableBytes); - return [ourHmacData copy]; -} - -+ (nullable NSData *)truncatedSHA256HMAC:(NSData *)dataToHMAC - withHMACKey:(NSData *)HMACKey - truncation:(NSUInteger)truncation -{ - OWSAssert(truncation <= CC_SHA256_DIGEST_LENGTH); - OWSAssert(dataToHMAC); - OWSAssert(HMACKey); - - return - [[Cryptography computeSHA256HMAC:dataToHMAC withHMACKey:HMACKey] subdataWithRange:NSMakeRange(0, truncation)]; -} - -#pragma mark - AES CBC Mode - -/** - * AES256 CBC encrypt then mac. Used to decrypt both signal messages and attachment blobs - * - * @return decrypted data or nil if hmac invalid/decryption fails - */ -+ (nullable NSData *)decryptCBCMode:(NSData *)dataToDecrypt - key:(NSData *)key - IV:(NSData *)iv - version:(nullable NSData *)version - HMACKey:(NSData *)hmacKey - HMACType:(TSMACType)hmacType - matchingHMAC:(NSData *)hmac - digest:(nullable NSData *)digest -{ - OWSAssert(dataToDecrypt); - OWSAssert(key); - if (key.length != kCCKeySizeAES256) { - OWSFailDebug(@"key had wrong size."); - return nil; - } - OWSAssert(iv); - if (iv.length != kCCBlockSizeAES128) { - OWSFailDebug(@"iv had wrong size."); - return nil; - } - OWSAssert(hmacKey); - OWSAssert(hmac); - - size_t bufferSize; - BOOL didOverflow = __builtin_add_overflow(dataToDecrypt.length, kCCBlockSizeAES128, &bufferSize); - if (didOverflow) { - OWSFailDebug(@"bufferSize was too large."); - return nil; - } - - // Verify hmac of: version? || iv || encrypted data - - NSUInteger dataToAuthLength = 0; - if (__builtin_add_overflow(dataToDecrypt.length, iv.length, &dataToAuthLength)) { - OWSFailDebug(@"dataToAuth was too large."); - return nil; - } - if (version != nil && __builtin_add_overflow(dataToAuthLength, version.length, &dataToAuthLength)) { - OWSFailDebug(@"dataToAuth was too large."); - return nil; - } - - NSMutableData *dataToAuth = [NSMutableData data]; - if (version != nil) { - [dataToAuth appendData:version]; - } - [dataToAuth appendData:iv]; - [dataToAuth appendData:dataToDecrypt]; - - NSData *_Nullable ourHmacData; - - if (hmacType == TSHMACSHA256Truncated10Bytes) { - // used to authenticate envelope from websocket - OWSAssert(hmacKey.length == kHMAC256_EnvelopeKeyLength); - ourHmacData = [Cryptography truncatedSHA256HMAC:dataToAuth withHMACKey:hmacKey truncation:10]; - OWSAssert(ourHmacData.length == 10); - } else if (hmacType == TSHMACSHA256AttachementType) { - OWSAssert(hmacKey.length == HMAC256_KEY_LENGTH); - ourHmacData = - [Cryptography truncatedSHA256HMAC:dataToAuth withHMACKey:hmacKey truncation:HMAC256_OUTPUT_LENGTH]; - OWSAssert(ourHmacData.length == HMAC256_OUTPUT_LENGTH); - } else { - OWSFail(@"unknown HMAC scheme: %ld", (long)hmacType); - } - - if (hmac == nil || ![ourHmacData ows_constantTimeIsEqualToData:hmac]) { - OWSLogError(@"Bad HMAC on decrypting payload."); - // Don't log HMAC in prod - OWSLogDebug(@"Bad HMAC on decrypting payload. Their MAC: %@, our MAC: %@", hmac, ourHmacData); - return nil; - } - - // Optionally verify digest of: version? || iv || encrypted data || hmac - if (digest) { - OWSLogDebug(@"verifying their digest"); - [dataToAuth appendData:ourHmacData]; - NSData *_Nullable ourDigest = [Cryptography computeSHA256Digest:dataToAuth]; - if (!ourDigest || ![ourDigest ows_constantTimeIsEqualToData:digest]) { - OWSLogWarn(@"Bad digest on decrypting payload"); - // Don't log digest in prod - DDLogDebug(@"Bad digest on decrypting payload. Their digest: %@, our digest: %@, data: %@", - digest.hexadecimalString, - ourDigest.hexadecimalString, - dataToAuth.hexadecimalString); - return nil; - } - } - - // decrypt - NSMutableData *_Nullable bufferData = [NSMutableData dataWithLength:bufferSize]; - if (!bufferData) { - OWSLogError(@"Failed to allocate buffer."); - return nil; - } - - size_t bytesDecrypted = 0; - CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, - kCCAlgorithmAES128, - kCCOptionPKCS7Padding, - [key bytes], - [key length], - [iv bytes], - [dataToDecrypt bytes], - [dataToDecrypt length], - bufferData.mutableBytes, - bufferSize, - &bytesDecrypted); - if (cryptStatus == kCCSuccess) { - return [bufferData subdataWithRange:NSMakeRange(0, bytesDecrypted)]; - } else { - OWSLogError(@"Failed CBC decryption"); - } - - return nil; -} - -#pragma mark - methods which use AES CBC - -+ (nullable NSData *)decryptAppleMessagePayload:(NSData *)payload withSignalingKey:(NSString *)signalingKeyString -{ - OWSAssertDebug(payload); - OWSAssertDebug(signalingKeyString); - - size_t versionLength = 1; - size_t ivLength = 16; - size_t macLength = 10; - size_t nonCiphertextLength = versionLength + ivLength + macLength; - - size_t ciphertextLength; - ows_sub_overflow(payload.length, nonCiphertextLength, &ciphertextLength); - - if (payload.length < nonCiphertextLength) { - OWSFailDebug(@"Invalid payload"); - return nil; - } - if (payload.length >= MIN(SIZE_MAX, NSUIntegerMax) - nonCiphertextLength) { - OWSFailDebug(@"Invalid payload"); - return nil; - } - - NSUInteger cursor = 0; - NSData *versionData = [payload subdataWithRange:NSMakeRange(cursor, versionLength)]; - cursor += versionLength; - NSData *ivData = [payload subdataWithRange:NSMakeRange(cursor, ivLength)]; - cursor += ivLength; - NSData *ciphertextData = [payload subdataWithRange:NSMakeRange(cursor, ciphertextLength)]; - ows_add_overflow(cursor, ciphertextLength, &cursor); - NSData *macData = [payload subdataWithRange:NSMakeRange(cursor, macLength)]; - - NSData *signalingKey = [NSData dataFromBase64String:signalingKeyString]; - NSData *signalingKeyAESKeyMaterial = [signalingKey subdataWithRange:NSMakeRange(0, 32)]; - NSData *signalingKeyHMACKeyMaterial = [signalingKey subdataWithRange:NSMakeRange(32, kHMAC256_EnvelopeKeyLength)]; - return [Cryptography decryptCBCMode:ciphertextData - key:signalingKeyAESKeyMaterial - IV:ivData - version:versionData - HMACKey:signalingKeyHMACKeyMaterial - HMACType:TSHMACSHA256Truncated10Bytes - matchingHMAC:macData - digest:nil]; -} - -#pragma mark - Attachments & Stickers - -+ (nullable NSData *)decryptAttachment:(NSData *)dataToDecrypt - withKey:(NSData *)key - digest:(nullable NSData *)digest - unpaddedSize:(UInt32)unpaddedSize - error:(NSError **)error -{ - if (digest.length <= 0) { - // This *could* happen with sufficiently outdated clients. - OWSLogError(@"Refusing to decrypt attachment without a digest."); - *error = SCKErrorWithCodeDescription(SCKErrorCodeFailedToDecryptMessage, - NSLocalizedString(@"ERROR_MESSAGE_ATTACHMENT_FROM_OLD_CLIENT", - @"Error message when unable to receive an attachment because the sending client is too old.")); - return nil; - } - - return [self decryptData:dataToDecrypt - withKey:key - digest:digest - unpaddedSize:unpaddedSize - error:error]; -} - -+ (nullable NSData *)decryptStickerData:(NSData *)dataToDecrypt - withKey:(NSData *)key - error:(NSError **)error -{ - return [self decryptData:dataToDecrypt - withKey:key - digest:nil - unpaddedSize:0 - error:error]; -} - -+ (nullable NSData *)decryptData:(NSData *)dataToDecrypt - withKey:(NSData *)key - digest:(nullable NSData *)digest - unpaddedSize:(UInt32)unpaddedSize - error:(NSError **)error -{ - if (([dataToDecrypt length] < AES_CBC_IV_LENGTH + HMAC256_OUTPUT_LENGTH) || - ([key length] < AES_KEY_SIZE + HMAC256_KEY_LENGTH)) { - OWSLogError(@"Message shorter than crypto overhead!"); - *error = SCKErrorWithCodeDescription(SCKErrorCodeFailedToDecryptMessage, NSLocalizedString(@"ERROR_MESSAGE_INVALID_MESSAGE", @"")); - return nil; - } - - // key: 32 byte AES key || 32 byte Hmac-SHA256 key. - NSData *encryptionKey = [key subdataWithRange:NSMakeRange(0, AES_KEY_SIZE)]; - NSData *hmacKey = [key subdataWithRange:NSMakeRange(AES_KEY_SIZE, HMAC256_KEY_LENGTH)]; - - // dataToDecrypt: IV || Ciphertext || truncated MAC(IV||Ciphertext) - NSData *iv = [dataToDecrypt subdataWithRange:NSMakeRange(0, AES_CBC_IV_LENGTH)]; - - NSUInteger cipherTextLength; - ows_sub_overflow(dataToDecrypt.length, (AES_CBC_IV_LENGTH + HMAC256_OUTPUT_LENGTH), &cipherTextLength); - NSData *encryptedAttachment = [dataToDecrypt subdataWithRange:NSMakeRange(AES_CBC_IV_LENGTH, cipherTextLength)]; - - NSUInteger hmacOffset; - ows_sub_overflow(dataToDecrypt.length, HMAC256_OUTPUT_LENGTH, &hmacOffset); - NSData *hmac = [dataToDecrypt subdataWithRange:NSMakeRange(hmacOffset, HMAC256_OUTPUT_LENGTH)]; - - NSData *_Nullable paddedPlainText = [Cryptography decryptCBCMode:encryptedAttachment - key:encryptionKey - IV:iv - version:nil - HMACKey:hmacKey - HMACType:TSHMACSHA256AttachementType - matchingHMAC:hmac - digest:digest]; - if (!paddedPlainText) { - OWSFailDebug(@"couldn't decrypt attachment."); - *error = SCKErrorWithCodeDescription(SCKErrorCodeFailedToDecryptMessage, NSLocalizedString(@"ERROR_MESSAGE_INVALID_MESSAGE", @"")); - return nil; - } else if (unpaddedSize == 0) { - // Work around for legacy iOS client's which weren't setting padding size. - // Since we know those clients pre-date attachment padding we return the entire data. - OWSLogWarn(@"Decrypted attachment with unspecified size."); - return paddedPlainText; - } else { - if (unpaddedSize > paddedPlainText.length) { - *error = SCKErrorWithCodeDescription(SCKErrorCodeFailedToDecryptMessage, NSLocalizedString(@"ERROR_MESSAGE_INVALID_MESSAGE", @"")); - return nil; - } - - if (unpaddedSize == paddedPlainText.length) { - OWSLogInfo(@"decrypted unpadded attachment."); - return [paddedPlainText copy]; - } else { - unsigned long paddingSize; - ows_sub_overflow(paddedPlainText.length, unpaddedSize, &paddingSize); - - OWSLogInfo(@"decrypted padded attachment with unpaddedSize: %lu, paddingSize: %lu", - (unsigned long)unpaddedSize, - paddingSize); - return [paddedPlainText subdataWithRange:NSMakeRange(0, unpaddedSize)]; - } - } -} - -+ (unsigned long)paddedSize:(unsigned long)unpaddedSize -{ - // Don't enable this until clients are sufficiently rolled out. - BOOL shouldPad = NO; - if (shouldPad) { - // Note: This just rounds up to the nearsest power of two, - // but the actual padding scheme is TBD - return pow(2, ceil( log2( unpaddedSize ))); - } else { - return unpaddedSize; - } -} - -+ (nullable NSData *)encryptAttachmentData:(NSData *)attachmentData - outKey:(NSData *_Nonnull *_Nullable)outKey - outDigest:(NSData *_Nonnull *_Nullable)outDigest -{ - // Due to paddedSize, we need to divide by two. - if (attachmentData.length >= SIZE_MAX / 2) { - OWSLogError(@"data is too long."); - return nil; - } - - NSData *iv = [Cryptography generateRandomBytes:AES_CBC_IV_LENGTH]; - NSData *encryptionKey = [Cryptography generateRandomBytes:AES_KEY_SIZE]; - NSData *hmacKey = [Cryptography generateRandomBytes:HMAC256_KEY_LENGTH]; - - // The concatenated key for storage - NSMutableData *attachmentKey = [NSMutableData data]; - [attachmentKey appendData:encryptionKey]; - [attachmentKey appendData:hmacKey]; - *outKey = [attachmentKey copy]; - - // Apply any padding - unsigned long desiredSize = [self paddedSize:attachmentData.length]; - NSMutableData *paddedAttachmentData = [attachmentData mutableCopy]; - paddedAttachmentData.length = desiredSize; - - // Encrypt - size_t bufferSize; - ows_add_overflow(paddedAttachmentData.length, kCCBlockSizeAES128, &bufferSize); - NSMutableData *_Nullable bufferData = [NSMutableData dataWithLength:bufferSize]; - if (!bufferData) { - OWSFail(@"Failed to allocate buffer."); - } - - size_t bytesEncrypted = 0; - CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, - kCCAlgorithmAES128, - kCCOptionPKCS7Padding, - [encryptionKey bytes], - [encryptionKey length], - [iv bytes], - [paddedAttachmentData bytes], - [paddedAttachmentData length], - bufferData.mutableBytes, - bufferSize, - &bytesEncrypted); - - if (cryptStatus != kCCSuccess) { - OWSLogError(@"CCCrypt failed with status: %d", (int32_t)cryptStatus); - return nil; - } - - NSData *cipherText = [bufferData subdataWithRange:NSMakeRange(0, bytesEncrypted)]; - - NSMutableData *encryptedPaddedData = [NSMutableData data]; - [encryptedPaddedData appendData:iv]; - [encryptedPaddedData appendData:cipherText]; - - // compute hmac of: iv || encrypted data - NSData *_Nullable hmac = - [Cryptography truncatedSHA256HMAC:encryptedPaddedData withHMACKey:hmacKey truncation:HMAC256_OUTPUT_LENGTH]; - if (!hmac) { - OWSFailDebug(@"could not compute SHA 256 HMAC."); - return nil; - } - - [encryptedPaddedData appendData:hmac]; - - // compute digest of: iv || encrypted data || hmac - NSData *_Nullable digest = [self computeSHA256Digest:encryptedPaddedData]; - if (!digest) { - OWSFailDebug(@"data is too long."); - return nil; - } - *outDigest = digest; - - return [encryptedPaddedData copy]; -} - -#pragma mark - AES-GCM - -+ (nullable AES25GCMEncryptionResult *)encryptAESGCMWithData:(NSData *)plaintext - additionalAuthenticatedData:(nullable NSData *)additionalAuthenticatedData - key:(OWSAES256Key *)key -{ - NSData *initializationVector = [Cryptography generateRandomBytes:kAESGCM256_IVLength]; - - return [self encryptAESGCMWithData:plaintext - initializationVector:initializationVector - additionalAuthenticatedData:additionalAuthenticatedData - key:key]; -} - -+ (nullable AES25GCMEncryptionResult *)encryptAESGCMWithData:(NSData *)plaintext - initializationVector:(NSData *)initializationVector - additionalAuthenticatedData:(nullable NSData *)additionalAuthenticatedData - key:(OWSAES256Key *)key -{ - OWSAssert(initializationVector.length == kAESGCM256_IVLength); - - NSMutableData *ciphertext = [NSMutableData dataWithLength:plaintext.length]; - NSMutableData *authTag = [NSMutableData dataWithLength:kAESGCM256_TagLength]; - - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - if (!ctx) { - OWSFailDebug(@"failed to build context while encrypting"); - return nil; - } - - // Initialise the encryption operation. - if (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to init encryption"); - return nil; - } - - // Set IV length if default 12 bytes (96 bits) is not appropriate - if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)initializationVector.length, NULL) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to set IV length"); - return nil; - } - - // Initialise key and IV - if (EVP_EncryptInit_ex(ctx, NULL, NULL, key.keyData.bytes, initializationVector.bytes) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to set key and iv while encrypting"); - return nil; - } - - int bytesEncrypted = 0; - - // Provide any AAD data. This can be called zero or more times as - // required - if (additionalAuthenticatedData != nil) { - if (additionalAuthenticatedData.length >= INT_MAX) { - OWSFailDebug(@"additionalAuthenticatedData too large"); - return nil; - } - if (EVP_EncryptUpdate( - ctx, NULL, &bytesEncrypted, additionalAuthenticatedData.bytes, (int)additionalAuthenticatedData.length) - != kOpenSSLSuccess) { - OWSFailDebug(@"encryptUpdate failed"); - return nil; - } - } - - if (plaintext.length >= INT_MAX) { - OWSFailDebug(@"plaintext too large"); - return nil; - } - - // Provide the message to be encrypted, and obtain the encrypted output. - // - // If we wanted to save memory, we could encrypt piece-wise from a plaintext iostream - - // feeding each chunk to EVP_EncryptUpdate, which can be called multiple times. - // For simplicity, we currently encrypt the entire plaintext in one shot. - if (EVP_EncryptUpdate(ctx, ciphertext.mutableBytes, &bytesEncrypted, plaintext.bytes, (int)plaintext.length) - != kOpenSSLSuccess) { - OWSFailDebug(@"encryptUpdate failed"); - return nil; - } - if (bytesEncrypted != plaintext.length) { - OWSFailDebug(@"bytesEncrypted != plainTextData.length"); - return nil; - } - - int finalizedBytes = 0; - // Finalize the encryption. Normally ciphertext bytes may be written at - // this stage, but this does not occur in GCM mode - if (EVP_EncryptFinal_ex(ctx, ciphertext.mutableBytes + bytesEncrypted, &finalizedBytes) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to finalize encryption"); - return nil; - } - if (finalizedBytes != 0) { - OWSFailDebug(@"Unexpected finalized bytes written"); - return nil; - } - - // Get the tag - if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, kAESGCM256_TagLength, authTag.mutableBytes) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to write tag"); - return nil; - } - - // Clean up - EVP_CIPHER_CTX_free(ctx); - - AES25GCMEncryptionResult *_Nullable result = - [[AES25GCMEncryptionResult alloc] initWithCipherText:ciphertext - initializationVector:initializationVector - authTag:authTag]; - - return result; -} - -+ (nullable NSData *)decryptAESGCMWithInitializationVector:(NSData *)initializationVector - ciphertext:(NSData *)ciphertext - additionalAuthenticatedData:(nullable NSData *)additionalAuthenticatedData - authTag:(NSData *)authTagFromEncrypt - key:(OWSAES256Key *)key -{ - OWSAssertDebug(initializationVector.length == kAESGCM256_IVLength); - OWSAssertDebug(ciphertext.length > 0); - OWSAssertDebug(authTagFromEncrypt.length == kAESGCM256_TagLength); - OWSAssertDebug(key); - - NSMutableData *plaintext = [NSMutableData dataWithLength:ciphertext.length]; - - // Create and initialise the context - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - - if (!ctx) { - OWSFailDebug(@"failed to build context while decrypting"); - return nil; - } - - // Initialise the decryption operation. - if (EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to init decryption"); - return nil; - } - - // Set IV length. Not necessary if this is 12 bytes (96 bits) - if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, kAESGCM256_IVLength, NULL) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to set key and iv while decrypting"); - return nil; - } - - // Initialise key and IV - if (EVP_DecryptInit_ex(ctx, NULL, NULL, key.keyData.bytes, initializationVector.bytes) != kOpenSSLSuccess) { - OWSFailDebug(@"failed to init decryption"); - return nil; - } - - int decryptedBytes = 0; - - // Provide any AAD data. This can be called zero or more times as - // required - if (additionalAuthenticatedData) { - if (additionalAuthenticatedData.length >= INT_MAX) { - OWSFailDebug(@"additionalAuthenticatedData too large"); - return nil; - } - if (!EVP_DecryptUpdate(ctx, - NULL, - &decryptedBytes, - additionalAuthenticatedData.bytes, - (int)additionalAuthenticatedData.length)) { - OWSFailDebug(@"failed during additionalAuthenticatedData"); - return nil; - } - } - - // Provide the message to be decrypted, and obtain the plaintext output. - // - // If we wanted to save memory, we could decrypt piece-wise from an iostream - - // feeding each chunk to EVP_DecryptUpdate, which can be called multiple times. - // For simplicity, we currently decrypt the entire ciphertext in one shot. - if (ciphertext.length >= INT_MAX) { - OWSFailDebug(@"ciphertext too large"); - return nil; - } - if (EVP_DecryptUpdate(ctx, plaintext.mutableBytes, &decryptedBytes, ciphertext.bytes, (int)ciphertext.length) - != kOpenSSLSuccess) { - OWSFailDebug(@"decryptUpdate failed"); - return nil; - } - - if (decryptedBytes != ciphertext.length) { - OWSFailDebug(@"Failed to decrypt entire ciphertext"); - return nil; - } - - // Set expected tag value. Works in OpenSSL 1.0.1d and later - if (authTagFromEncrypt.length >= INT_MAX) { - OWSFailDebug(@"authTagFromEncrypt too large"); - return nil; - } - if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)authTagFromEncrypt.length, (void *)authTagFromEncrypt.bytes) - != kOpenSSLSuccess) { - OWSFailDebug(@"Failed to set auth tag in decrypt."); - return nil; - } - - // Finalise the decryption. A positive return value indicates success, - // anything else is a failure - the plaintext is not trustworthy. - int finalBytes = 0; - int decryptStatus = EVP_DecryptFinal_ex(ctx, (unsigned char *)(plaintext.bytes + decryptedBytes), &finalBytes); - - // AESGCM doesn't write any final bytes - OWSAssertDebug(finalBytes == 0); - - // Clean up - EVP_CIPHER_CTX_free(ctx); - - if (decryptStatus > 0) { - return [plaintext copy]; - } else { - // This should only happen if the user has changed their profile key, which should only - // happen currently if they re-register. - OWSLogError(@"Decrypt verification failed"); - return nil; - } -} - -#pragma mark - Profiles - -+ (nullable NSData *)encryptAESGCMWithProfileData:(NSData *)plaintext key:(OWSAES256Key *)key -{ - AES25GCMEncryptionResult *result = [self encryptAESGCMWithData:plaintext additionalAuthenticatedData:nil key:key]; - return [NSData join:@[ - result.initializationVector, - result.ciphertext, - result.authTag, - ]]; -} - -+ (nullable NSData *)decryptAESGCMWithProfileData:(NSData *)encryptedData key:(OWSAES256Key *)key -{ - NSUInteger cipherTextLength; - BOOL didOverflow - = __builtin_sub_overflow(encryptedData.length, (kAESGCM256_IVLength + kAESGCM256_TagLength), &cipherTextLength); - if (didOverflow) { - OWSFailDebug(@"unexpectedly short encryptedData.length: %lu", (unsigned long)encryptedData.length); - return nil; - } - - // encryptedData layout: initializationVector || ciphertext || authTag - NSData *initializationVector = [encryptedData subdataWithRange:NSMakeRange(0, kAESGCM256_IVLength)]; - NSData *ciphertext = [encryptedData subdataWithRange:NSMakeRange(kAESGCM256_IVLength, cipherTextLength)]; - - NSUInteger tagOffset; - ows_add_overflow(kAESGCM256_IVLength, cipherTextLength, &tagOffset); - - NSData *authTag = [encryptedData subdataWithRange:NSMakeRange(tagOffset, kAESGCM256_TagLength)]; - - return [self decryptAESGCMWithInitializationVector:initializationVector - ciphertext:ciphertext - additionalAuthenticatedData:nil - authTag:authTag - key:key]; -} - -#pragma mark - AES-CTR - -+ (nullable AES256CTREncryptionResult *)encryptAESCTRWithData:(NSData *)plaintext - initializationVector:(NSData *)initializationVector - key:(OWSAES256Key *)key -{ - OWSAssertDebug(plaintext); - OWSAssertDebug(initializationVector.length == kAES256CTR_IVLength); - OWSAssertDebug(key); - - NSMutableData *cipherText = [NSMutableData dataWithLength:plaintext.length]; - - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - if (!ctx) { - OWSFailDebug(@"%@ failed to build context while encrypting", self.logTag); - return nil; - } - - // Initialise the encryption operation. - if (EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, NULL, NULL) != kOpenSSLSuccess) { - OWSFailDebug(@"%@ failed to init encryption", self.logTag); - return nil; - } - - // Initialise key and IV - if (EVP_EncryptInit_ex(ctx, NULL, NULL, key.keyData.bytes, initializationVector.bytes) != kOpenSSLSuccess) { - OWSFailDebug(@"%@ failed to set key and iv while encrypting", self.logTag); - return nil; - } - - if (plaintext.length >= INT_MAX) { - OWSFailDebug(@"%@ plaintext too large", self.logTag); - return nil; - } - - // Provide the message to be encrypted, and obtain the encrypted output. - // - // If we wanted to save memory, we could encrypt piece-wise from a plaintext iostream - - // feeding each chunk to EVP_EncryptUpdate, which can be called multiple times. - // For simplicity, we currently encrypt the entire plaintext in one shot. - int bytesEncrypted = 0; - if (EVP_EncryptUpdate(ctx, cipherText.mutableBytes, &bytesEncrypted, plaintext.bytes, (int)plaintext.length) - != kOpenSSLSuccess) { - OWSFailDebug(@"%@ encryptUpdate failed", self.logTag); - return nil; - } - if (bytesEncrypted != plaintext.length) { - OWSFailDebug(@"%@ bytesEncrypted != plaintextData.length", self.logTag); - return nil; - } - - int finalizedBytes = 0; - // Finalize the encryption. Normally cipherText bytes may be written at - // this stage, but this does not occur in CTR mode - if (EVP_EncryptFinal_ex(ctx, cipherText.mutableBytes + bytesEncrypted, &finalizedBytes) != kOpenSSLSuccess) { - OWSFailDebug(@"%@ failed to finalize encryption", self.logTag); - return nil; - } - if (finalizedBytes != 0) { - OWSFailDebug(@"%@ Unexpected finalized bytes written", self.logTag); - return nil; - } - - // Clean up - EVP_CIPHER_CTX_free(ctx); - - AES256CTREncryptionResult *_Nullable result = - [[AES256CTREncryptionResult alloc] initWithCiphertext:cipherText initializationVector:initializationVector]; - - return result; -} - -+ (nullable NSData *)decryptAESCTRWithCipherText:(NSData *)cipherText - initializationVector:(NSData *)initializationVector - key:(OWSAES256Key *)key -{ - OWSAssertDebug(initializationVector.length == kAES256CTR_IVLength); - OWSAssertDebug(cipherText.length > 0); - OWSAssertDebug(key); - - NSMutableData *plaintext = [NSMutableData dataWithLength:cipherText.length]; - - // Create and initialise the context - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - - if (!ctx) { - OWSFailDebug(@"%@ failed to build context while decrypting", self.logTag); - return nil; - } - - // Initialise the decryption operation. - if (EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, NULL, NULL) != kOpenSSLSuccess) { - OWSFailDebug(@"%@ failed to init decryption", self.logTag); - return nil; - } - - // Initialise key and IV - if (EVP_DecryptInit_ex(ctx, NULL, NULL, key.keyData.bytes, initializationVector.bytes) != kOpenSSLSuccess) { - OWSFailDebug(@"%@ failed to init decryption", self.logTag); - return nil; - } - - // Provide the message to be decrypted, and obtain the plaintext output. - // - // If we wanted to save memory, we could decrypt piece-wise from an iostream - - // feeding each chunk to EVP_DecryptUpdate, which can be called multiple times. - // For simplicity, we currently decrypt the entire cipherText in one shot. - if (cipherText.length >= INT_MAX) { - OWSFailDebug(@"%@ cipherText too large", self.logTag); - return nil; - } - int decryptedBytes = 0; - if (EVP_DecryptUpdate(ctx, plaintext.mutableBytes, &decryptedBytes, cipherText.bytes, (int)cipherText.length) - != kOpenSSLSuccess) { - OWSFailDebug(@"%@ decryptUpdate failed", self.logTag); - return nil; - } - - if (decryptedBytes != cipherText.length) { - OWSFailDebug(@"%@ Failed to decrypt entire cipherText", self.logTag); - return nil; - } - - // Finalise the decryption. A positive return value indicates success, - // anything else is a failure - the plaintext is not trustworthy. - int finalBytes = 0; - int decryptStatus = EVP_DecryptFinal_ex(ctx, (unsigned char *)(plaintext.bytes + decryptedBytes), &finalBytes); - - // AES CTR doesn't write any final bytes - OWSAssertDebug(finalBytes == 0); - - // Clean up - EVP_CIPHER_CTX_free(ctx); - - if (decryptStatus > 0) { - return [plaintext copy]; - } else { - DDLogError(@"%@ Decrypt verification failed", self.logTag); - return nil; - } -} - -#pragma mark - - -+ (void)seedRandom -{ - // We should never use rand(), but seed it just in case it's used by 3rd-party code - unsigned seed = [Cryptography randomUnsigned]; - srand(seed); -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/Data+OWS.swift b/SessionProtocolKit/Signal/Utility/Data+OWS.swift deleted file mode 100644 index 0468f3d54..000000000 --- a/SessionProtocolKit/Signal/Utility/Data+OWS.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -extension Data { - public var hexadecimalString: String { - return (self as NSData).hexadecimalString() - } - - public static func data(fromHex hexString: String) -> Data? { - guard let data = NSData(fromHexString : hexString) else { - return nil - } - return data as Data - } - - public func ows_constantTimeIsEqual(to other: Data) -> Bool { - return (self as NSData).ows_constantTimeIsEqual(to: other) - } -} diff --git a/SessionProtocolKit/Signal/Utility/Logger.swift b/SessionProtocolKit/Signal/Utility/Logger.swift deleted file mode 100644 index be05f3e1c..000000000 --- a/SessionProtocolKit/Signal/Utility/Logger.swift +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -// Once we're on Swift4.2 we can mark this as inlineable -// @inlinable -public func owsFormatLogMessage(_ logString: String, - file: String = #file, - function: String = #function, - line: Int = #line) -> String { - let filename = (file as NSString).lastPathComponent - // We format the filename & line number in a format compatible - // with XCode's "Open Quickly..." feature. - return "[\(filename):\(line) \(function)]: \(logString)" -} - -/** - * A minimal DDLog wrapper for swift. - */ -open class Logger: NSObject { - - open class func verbose(_ logString: @autoclosure () -> String, - file: String = #file, - function: String = #function, - line: Int = #line) { - guard ShouldLogVerbose() else { - return - } - OWSLogger.verbose(owsFormatLogMessage(logString(), file: file, function: function, line: line)) - } - - open class func debug(_ logString: @autoclosure () -> String, - file: String = #file, - function: String = #function, - line: Int = #line) { - guard ShouldLogDebug() else { - return - } - OWSLogger.debug(owsFormatLogMessage(logString(), file: file, function: function, line: line)) - } - - open class func info(_ logString: @autoclosure () -> String, - file: String = #file, - function: String = #function, - line: Int = #line) { - guard ShouldLogInfo() else { - return - } - OWSLogger.info(owsFormatLogMessage(logString(), file: file, function: function, line: line)) - } - - open class func warn(_ logString: @autoclosure () -> String, - file: String = #file, - function: String = #function, - line: Int = #line) { - guard ShouldLogWarning() else { - return - } - OWSLogger.warn(owsFormatLogMessage(logString(), file: file, function: function, line: line)) - } - - open class func error(_ logString: @autoclosure () -> String, - file: String = #file, - function: String = #function, - line: Int = #line) { - guard ShouldLogError() else { - return - } - OWSLogger.error(owsFormatLogMessage(logString(), file: file, function: function, line: line)) - } - - open class func flush() { - OWSLogger.flush() - } -} diff --git a/SessionProtocolKit/Signal/Utility/NSData+OWS.h b/SessionProtocolKit/Signal/Utility/NSData+OWS.h deleted file mode 100644 index 80324051d..000000000 --- a/SessionProtocolKit/Signal/Utility/NSData+OWS.h +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface NSData (OWS) - -+ (NSData *)join:(NSArray *)datas; - -- (NSData *)dataByAppendingData:(NSData *)data; - -#pragma mark - Hex - -- (NSString *)hexadecimalString; - -+ (nullable NSData *)dataFromHexString:(NSString *)hexString; - -#pragma mark - Base64 - -+ (nullable NSData *)dataFromBase64StringNoPadding:(NSString *)aString; -+ (nullable NSData *)dataFromBase64String:(NSString *)aString; - -- (NSString *)base64EncodedString; - -#pragma mark - - -/** - * Compares data in constant time so as to help avoid potential timing attacks. - */ -- (BOOL)ows_constantTimeIsEqualToData:(NSData *)other; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSData+OWS.m b/SessionProtocolKit/Signal/Utility/NSData+OWS.m deleted file mode 100644 index c33c8b782..000000000 --- a/SessionProtocolKit/Signal/Utility/NSData+OWS.m +++ /dev/null @@ -1,147 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "NSData+OWS.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation NSData (OWS) - -+ (NSData *)join:(NSArray *)datas -{ - OWSAssert(datas); - - NSMutableData *result = [NSMutableData new]; - for (NSData *data in datas) { - [result appendData:data]; - } - return [result copy]; -} - -- (NSData *)dataByAppendingData:(NSData *)data -{ - NSMutableData *result = [self mutableCopy]; - [result appendData:data]; - return [result copy]; -} - -#pragma mark - Hex - -- (NSString *)hexadecimalString -{ - /* Returns hexadecimal string of NSData. Empty string if data is empty. */ - const unsigned char *dataBuffer = (const unsigned char *)[self bytes]; - if (!dataBuffer) { - return @""; - } - - NSUInteger dataLength = [self length]; - NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)]; - - for (NSUInteger i = 0; i < dataLength; ++i) { - [hexString appendFormat:@"%02x", dataBuffer[i]]; - } - return [hexString copy]; -} - -+ (nullable NSData *)dataFromHexString:(NSString *)hexString { - NSMutableData *data = [NSMutableData new]; - - if (hexString.length % 2 != 0) { - OWSFailDebug(@"Hexadecimal string has unexpected length: %@ (%lu)", hexString, (unsigned long)hexString.length); - return nil; - } - for (NSUInteger i = 0; i + 2 <= hexString.length; i += 2) { - NSString *_Nullable byteString = [hexString substringWithRange:NSMakeRange(i, 2)]; - if (!byteString) { - OWSFailDebug(@"Couldn't slice hexadecimal string."); - return nil; - } - unsigned byteValue; - if (![[NSScanner scannerWithString:byteString] scanHexInt:&byteValue]) { - OWSFailDebug(@"Couldn't parse hex byte: %@.", byteString); - return nil; - } - if (byteValue > 0xff) { - OWSFailDebug(@"Invalid hex byte: %@ (%d).", byteString, byteValue); - return nil; - } - uint8_t byte = (uint8_t)(0xff & byteValue); - [data appendBytes:&byte length:1]; - } - return [data copy]; -} - -#pragma mark - Base64 - -+ (nullable NSData *)dataFromBase64StringNoPadding:(NSString *)aString -{ - int padding = aString.length % 4; - - NSMutableString *strResult = [aString mutableCopy]; - if (padding != 0) { - int charsToAdd = 4 - padding; - for (int i = 0; i < charsToAdd; i++) { - [strResult appendString:@"="]; - } - } - return [self dataFromBase64String:strResult]; -} - -// -// dataFromBase64String: -// -// Creates an NSData object containing the base64 decoded representation of -// the base64 string 'aString' -// -// Parameters: -// aString - the base64 string to decode -// -// returns the NSData representation of the base64 string -// - -+ (nullable NSData *)dataFromBase64String:(NSString *)aString -{ - return [[NSData alloc] initWithBase64EncodedString:aString options:NSDataBase64DecodingIgnoreUnknownCharacters]; -} - -// -// base64EncodedString -// -// Creates an NSString object that contains the base 64 encoding of the -// receiver's data. Lines are broken at 64 characters long. -// -// returns an NSString being the base 64 representation of the -// receiver. -// -- (NSString *)base64EncodedString -{ - return [self base64EncodedStringWithOptions:0]; -} - -#pragma mark - - -- (BOOL)ows_constantTimeIsEqualToData:(NSData *)other -{ - volatile UInt8 isEqual = 0; - - if (self.length != other.length) { - return NO; - } - - UInt8 *leftBytes = (UInt8 *)self.bytes; - UInt8 *rightBytes = (UInt8 *)other.bytes; - for (int i = 0; i < self.length; i++) { - // rather than returning as soon as we find a discrepency, we compare the rest of - // the byte stream to maintain a constant time comparison - isEqual |= leftBytes[i] ^ rightBytes[i]; - } - - return isEqual == 0; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m b/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m index 04a3a2554..24c0f8648 100644 --- a/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m +++ b/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m @@ -4,8 +4,8 @@ #import "NSData+keyVersionByte.h" #import "AxolotlExceptions.h" -#import -#import +#import +#import @implementation NSData (keyVersionByte) diff --git a/SessionProtocolKit/Signal/Utility/NSDate+OWS.h b/SessionProtocolKit/Signal/Utility/NSDate+OWS.h deleted file mode 100644 index e246493a3..000000000 --- a/SessionProtocolKit/Signal/Utility/NSDate+OWS.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -// These NSTimeInterval constants provide simplified durations for readability. -// -// These approximations should never be used for strict date/time calcuations. -extern const NSTimeInterval kSecondInterval; -extern const NSTimeInterval kMinuteInterval; -extern const NSTimeInterval kHourInterval; -extern const NSTimeInterval kDayInterval; -extern const NSTimeInterval kWeekInterval; -extern const NSTimeInterval kMonthInterval; -extern const NSTimeInterval kYearInterval; - -#define kSecondInMs ((uint64_t)1000) -#define kMinuteInMs (kSecondInMs * 60) -#define kHourInMs (kMinuteInMs * 60) -#define kDayInMs (kHourInMs * 24) -#define kWeekInMs (kDayInMs * 7) -#define kMonthInMs (kDayInMs * 30) - -// kYearsInMs is a double to avoid overflow -#define kYearsInMs (kDayInMs * 365.0) - -@interface NSDate (OWS) - -+ (uint64_t)ows_millisecondTimeStamp; -+ (NSDate *)ows_dateWithMillisecondsSince1970:(uint64_t)milliseconds; -+ (uint64_t)ows_millisecondsSince1970ForDate:(NSDate *)date; - -- (BOOL)isAfterDate:(NSDate *)otherDate; -- (BOOL)isBeforeDate:(NSDate *)otherDate; - -- (BOOL)isAfterNow; -- (BOOL)isBeforeNow; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSDate+OWS.mm b/SessionProtocolKit/Signal/Utility/NSDate+OWS.mm deleted file mode 100644 index 4680bfdfc..000000000 --- a/SessionProtocolKit/Signal/Utility/NSDate+OWS.mm +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "NSDate+OWS.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -const NSTimeInterval kSecondInterval = 1; -const NSTimeInterval kMinuteInterval = 60; -const NSTimeInterval kHourInterval = 60 * kMinuteInterval; -const NSTimeInterval kDayInterval = 24 * kHourInterval; -const NSTimeInterval kWeekInterval = 7 * kDayInterval; -const NSTimeInterval kMonthInterval = 30 * kDayInterval; -const NSTimeInterval kYearInterval = 365 * kDayInterval; - -@implementation NSDate (OWS) - -+ (uint64_t)ows_millisecondTimeStamp -{ - uint64_t milliseconds - = (uint64_t)(std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1)); - return milliseconds; -} - -+ (NSDate *)ows_dateWithMillisecondsSince1970:(uint64_t)milliseconds -{ - return [NSDate dateWithTimeIntervalSince1970:(milliseconds / 1000.0)]; -} - -+ (uint64_t)ows_millisecondsSince1970ForDate:(NSDate *)date -{ - return (uint64_t)(date.timeIntervalSince1970 * 1000); -} - -- (BOOL)isAfterDate:(NSDate *)otherDate -{ - return [self compare:otherDate] == NSOrderedDescending; -} - -- (BOOL)isBeforeDate:(NSDate *)otherDate -{ - return [self compare:otherDate] == NSOrderedAscending; -} - -- (BOOL)isAfterNow -{ - return [self isAfterDate:[NSDate new]]; -} - -- (BOOL)isBeforeNow -{ - return [self isBeforeDate:[NSDate new]]; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSObject+OWS.h b/SessionProtocolKit/Signal/Utility/NSObject+OWS.h deleted file mode 100644 index 5799ba8d1..000000000 --- a/SessionProtocolKit/Signal/Utility/NSObject+OWS.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface NSObject (OWS) - -#pragma mark - Logging - -@property (nonatomic, readonly) NSString *logTag; - -@property (class, nonatomic, readonly) NSString *logTag; - -+ (BOOL)isNullableObject:(nullable NSObject *)left equalTo:(nullable NSObject *)right; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSObject+OWS.m b/SessionProtocolKit/Signal/Utility/NSObject+OWS.m deleted file mode 100644 index 2368ef19a..000000000 --- a/SessionProtocolKit/Signal/Utility/NSObject+OWS.m +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "NSObject+OWS.h" - -NS_ASSUME_NONNULL_BEGIN - -@implementation NSObject (OWS) - -#pragma mark - Logging - -+ (NSString *)logTag -{ - return [NSString stringWithFormat:@"[%@]", self.class]; -} - -- (NSString *)logTag -{ - return self.class.logTag; -} - -+ (BOOL)isNullableObject:(nullable NSObject *)left equalTo:(nullable NSObject *)right -{ - if (!left && !right) { - return YES; - } else if (!left || !right) { - return NO; - } else { - return [left isEqual:right]; - } -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSString+OWS.h b/SessionProtocolKit/Signal/Utility/NSString+OWS.h deleted file mode 100644 index f76b1b096..000000000 --- a/SessionProtocolKit/Signal/Utility/NSString+OWS.h +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface NSString (OWS) - -- (NSString *)ows_stripped; - -- (NSString *)digitsOnly; - -@property (nonatomic, readonly) BOOL hasAnyASCII; -@property (nonatomic, readonly) BOOL isOnlyASCII; - -- (NSString *)filterStringForDisplay; - -- (NSString *)filterFilename; - -- (BOOL)isValidE164; - -+ (NSString *)formatDurationSeconds:(uint32_t)durationSeconds useShortFormat:(BOOL)useShortFormat; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSString+OWS.m b/SessionProtocolKit/Signal/Utility/NSString+OWS.m deleted file mode 100644 index 5414f46f0..000000000 --- a/SessionProtocolKit/Signal/Utility/NSString+OWS.m +++ /dev/null @@ -1,453 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "NSString+OWS.h" -#import "iOSVersions.h" -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface UnicodeCodeRange : NSObject - -@property (nonatomic) unichar first; -@property (nonatomic) unichar last; - -@end - -#pragma mark - - -@implementation UnicodeCodeRange - -+ (UnicodeCodeRange *)rangeWithStart:(unichar)first last:(unichar)last -{ - OWSAssertDebug(first <= last); - - UnicodeCodeRange *range = [UnicodeCodeRange new]; - range.first = first; - range.last = last; - return range; -} - -- (NSComparisonResult)compare:(UnicodeCodeRange *)other -{ - - return self.first > other.first; -} - -@end - -#pragma mark - - -static void *kNSString_SSK_hasExcessiveDiacriticals = &kNSString_SSK_hasExcessiveDiacriticals; - -@implementation NSString (OWS) - -- (NSString *)ows_stripped -{ - return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; -} - -+ (BOOL)shouldFilterIndic -{ - static BOOL result = NO; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - result = (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(11, 0) && !SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(11, 3)); - }); - return result; -} - -+ (BOOL)isIndicVowel:(unichar)c -{ - static NSArray *ranges; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - // From: - // https://unicode.org/charts/PDF/U0C00.pdf - // https://unicode.org/charts/PDF/U0980.pdf - // https://unicode.org/charts/PDF/U0900.pdf - ranges = [@[ - // Telugu: - [UnicodeCodeRange rangeWithStart:0xC05 last:0xC14], - [UnicodeCodeRange rangeWithStart:0xC3E last:0xC4C], - [UnicodeCodeRange rangeWithStart:0xC60 last:0xC63], - // Bengali - [UnicodeCodeRange rangeWithStart:0x985 last:0x994], - [UnicodeCodeRange rangeWithStart:0x9BE last:0x9C8], - [UnicodeCodeRange rangeWithStart:0x9CB last:0x9CC], - [UnicodeCodeRange rangeWithStart:0x9E0 last:0x9E3], - // Devanagari - [UnicodeCodeRange rangeWithStart:0x904 last:0x914], - [UnicodeCodeRange rangeWithStart:0x93A last:0x93B], - [UnicodeCodeRange rangeWithStart:0x93E last:0x94C], - [UnicodeCodeRange rangeWithStart:0x94E last:0x94F], - [UnicodeCodeRange rangeWithStart:0x955 last:0x957], - [UnicodeCodeRange rangeWithStart:0x960 last:0x963], - [UnicodeCodeRange rangeWithStart:0x972 last:0x977], - ] sortedArrayUsingSelector:@selector(compare:)]; - }); - - for (UnicodeCodeRange *range in ranges) { - if (c < range.first) { - // For perf, we can take advantage of the fact that the - // ranges are sorted to exit early if the character lies - // before the current range. - return NO; - } - if (range.first <= c && c <= range.last) { - return YES; - } - } - return NO; -} - -+ (NSCharacterSet *)problematicCharacterSetForIndicScript -{ - static NSCharacterSet *characterSet; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - characterSet = [NSCharacterSet characterSetWithCharactersInString:@"\u200C"]; - }); - - return characterSet; -} - -// See: https://manishearth.github.io/blog/2018/02/15/picking-apart-the-crashing-ios-string/ -- (NSString *)filterForIndicScripts -{ - if (!NSString.shouldFilterIndic) { - return self; - } - - if ([self rangeOfCharacterFromSet:[[self class] problematicCharacterSetForIndicScript]].location == NSNotFound) { - return self; - } - - NSMutableString *filteredForIndic = [NSMutableString new]; - for (NSUInteger index = 0; index < self.length; index++) { - unichar c = [self characterAtIndex:index]; - if (c == 0x200C) { - NSUInteger nextIndex = index + 1; - if (nextIndex < self.length) { - unichar next = [self characterAtIndex:nextIndex]; - if ([NSString isIndicVowel:next]) { - // Discard ZWNJ (zero-width non-joiner) whenever we find a ZWNJ - // followed by an Indic (Telugu, Bengali, Devanagari) vowel - // and replace it with 0xFFFD, the Unicode "replacement character." - [filteredForIndic appendFormat:@"\uFFFD"]; - OWSLogError(@"Filtered unsafe Indic script."); - // Then discard the vowel too. - index++; - continue; - } - } - } - [filteredForIndic appendFormat:@"%C", c]; - } - return [filteredForIndic copy]; -} - -+ (NSCharacterSet *)unsafeFilenameCharacterSet -{ - static NSCharacterSet *characterSet; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - // 0x202D and 0x202E are the unicode ordering letters - // and can be used to control the rendering of text. - // They could be used to construct misleading attachment - // filenames that appear to have a different file extension, - // for example. - characterSet = [NSCharacterSet characterSetWithCharactersInString:@"\u202D\u202E"]; - }); - - return characterSet; -} - -- (NSString *)filterUnsafeFilenameCharacters -{ - NSCharacterSet *unsafeCharacterSet = [[self class] unsafeFilenameCharacterSet]; - NSRange range = [self rangeOfCharacterFromSet:unsafeCharacterSet]; - if (range.location == NSNotFound) { - return self; - } - NSMutableString *filtered = [NSMutableString new]; - NSString *remainder = [self copy]; - while (range.location != NSNotFound) { - if (range.location > 0) { - [filtered appendString:[remainder substringToIndex:range.location]]; - } - // The "replacement" code point. - [filtered appendString:@"\uFFFD"]; - remainder = [remainder substringFromIndex:range.location + range.length]; - range = [remainder rangeOfCharacterFromSet:unsafeCharacterSet]; - } - [filtered appendString:remainder]; - return filtered; -} - -- (NSString *)filterStringForDisplay -{ - return self.ows_stripped.filterForIndicScripts.filterForExcessiveDiacriticals; -} - -- (NSString *)filterFilename -{ - return self.ows_stripped.filterForIndicScripts.filterForExcessiveDiacriticals.filterUnsafeFilenameCharacters; -} - -- (NSString *)filterForExcessiveDiacriticals -{ - if (!self.hasExcessiveDiacriticals) { - return self; - } - return [self stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]]; -} - -- (BOOL)hasExcessiveDiacriticals -{ - NSNumber *cachedValue = objc_getAssociatedObject(self, kNSString_SSK_hasExcessiveDiacriticals); - if (!cachedValue) { - cachedValue = @([self computeHasExcessiveDiacriticals]); - objc_setAssociatedObject(self, kNSString_SSK_hasExcessiveDiacriticals, cachedValue, OBJC_ASSOCIATION_COPY); - } - - return cachedValue.boolValue; -} - -- (BOOL)computeHasExcessiveDiacriticals -{ - // discard any zalgo style text, by detecting maximum number of glyphs per character - NSUInteger index = 0; - - // store in local var, it's a hot code path. - NSUInteger length = self.length; - while (index < length) { - // Walk the grapheme clusters in the string. - NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index]; - if (range.length > 8) { - // There are too many characters in this grapheme cluster. - return YES; - } else if (range.location != index || range.length < 1) { - // This should never happen. - OWSFailDebug( - @"unexpected composed character sequence: %lu, %@", (unsigned long)index, NSStringFromRange(range)); - return YES; - } - index = range.location + range.length; - } - return NO; -} - -+ (NSRegularExpression *)anyASCIIRegex -{ - static dispatch_once_t onceToken; - static NSRegularExpression *regex; - dispatch_once(&onceToken, ^{ - NSError *error; - regex = [NSRegularExpression regularExpressionWithPattern:@"[\x00-\x7F]+" - options:0 - error:&error]; - if (error || !regex) { - // crash! it's not clear how to proceed safely, and this regex should never fail. - OWSFail(@"could not compile regex: %@", error); - } - }); - - return regex; -} - -+ (NSRegularExpression *)onlyASCIIRegex -{ - static dispatch_once_t onceToken; - static NSRegularExpression *regex; - dispatch_once(&onceToken, ^{ - NSError *error; - regex = [NSRegularExpression regularExpressionWithPattern:@"^[\x00-\x7F]*$" - options:0 - error:&error]; - if (error || !regex) { - // crash! it's not clear how to proceed safely, and this regex should never fail. - OWSFail(@"could not compile regex: %@", error); - } - }); - - return regex; -} - - -- (BOOL)isOnlyASCII; -{ - return [self.class.onlyASCIIRegex rangeOfFirstMatchInString:self - options:0 - range:NSMakeRange(0, self.length)].location != NSNotFound; -} - -- (BOOL)hasAnyASCII -{ - return [self.class.anyASCIIRegex rangeOfFirstMatchInString:self - options:0 - range:NSMakeRange(0, self.length)].location != NSNotFound; -} - -- (BOOL)isValidE164 -{ - NSError *error = nil; - NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\+\\d+$" - options:NSRegularExpressionCaseInsensitive - error:&error]; - if (error || !regex) { - OWSFailDebug(@"could not compile regex: %@", error); - return NO; - } - return [regex rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, self.length)].location != NSNotFound; -} - -+ (NSString *)formatDurationSeconds:(uint32_t)durationSeconds useShortFormat:(BOOL)useShortFormat -{ - NSString *amountFormat; - uint32_t duration; - - uint32_t secondsPerMinute = 60; - uint32_t secondsPerHour = secondsPerMinute * 60; - uint32_t secondsPerDay = secondsPerHour * 24; - uint32_t secondsPerWeek = secondsPerDay * 7; - - if (durationSeconds < secondsPerMinute) { // XX Seconds - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_SECONDS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of seconds}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5s' not '5 s'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_SECONDS", - @"{{number of seconds}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{5 seconds}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds; - } else if (durationSeconds < secondsPerMinute * 1.5) { // 1 Minute - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_MINUTES_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of minutes}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5m' not '5 m'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_SINGLE_MINUTE", - @"{{1 minute}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{1 minute}}'. See other *_TIME_AMOUNT strings"); - } - duration = durationSeconds / secondsPerMinute; - } else if (durationSeconds < secondsPerHour) { // Multiple Minutes - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_MINUTES_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of minutes}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5m' not '5 m'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_MINUTES", - @"{{number of minutes}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{5 minutes}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerMinute; - } else if (durationSeconds < secondsPerHour * 1.5) { // 1 Hour - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_HOURS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of hours}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5h' not '5 h'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_SINGLE_HOUR", - @"{{1 hour}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{1 hour}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerHour; - } else if (durationSeconds < secondsPerDay) { // Multiple Hours - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_HOURS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of hours}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5h' not '5 h'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_HOURS", - @"{{number of hours}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{5 hours}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerHour; - } else if (durationSeconds < secondsPerDay * 1.5) { // 1 Day - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_DAYS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of days}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5d' not '5 d'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_SINGLE_DAY", - @"{{1 day}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{1 day}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerDay; - } else if (durationSeconds < secondsPerWeek) { // Multiple Days - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_DAYS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of days}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5d' not '5 d'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_DAYS", - @"{{number of days}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{5 days}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerDay; - } else if (durationSeconds < secondsPerWeek * 1.5) { // 1 Week - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_WEEKS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of weeks}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5w' not '5 w'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_SINGLE_WEEK", - @"{{1 week}} embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{1 week}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerWeek; - } else { // Multiple weeks - if (useShortFormat) { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_WEEKS_SHORT_FORMAT", - @"Label text below navbar button, embeds {{number of weeks}}. Must be very short, like 1 or 2 " - @"characters, The space is intentionally omitted between the text and the embedded duration so that " - @"we get, e.g. '5w' not '5 w'. See other *_TIME_AMOUNT strings"); - } else { - amountFormat = NSLocalizedString(@"TIME_AMOUNT_WEEKS", - @"{{number of weeks}}, embedded in strings, e.g. 'Alice updated disappearing messages " - @"expiration to {{5 weeks}}'. See other *_TIME_AMOUNT strings"); - } - - duration = durationSeconds / secondsPerWeek; - } - - return [NSString stringWithFormat:amountFormat, - [NSNumberFormatter localizedStringFromNumber:@(duration) numberStyle:NSNumberFormatterNoStyle]]; -} - -- (NSString *)removeAllCharactersIn:(NSCharacterSet *)characterSet -{ - OWSAssertDebug(characterSet); - - return [[self componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""]; -} - -- (NSString *)digitsOnly -{ - return [self removeAllCharactersIn:[NSCharacterSet.decimalDigitCharacterSet invertedSet]]; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/OWSAsserts.h b/SessionProtocolKit/Signal/Utility/OWSAsserts.h deleted file mode 100644 index 5049740e0..000000000 --- a/SessionProtocolKit/Signal/Utility/OWSAsserts.h +++ /dev/null @@ -1,210 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "OWSLogs.h" - -NS_ASSUME_NONNULL_BEGIN - -#ifndef OWSAssert - -#define CONVERT_TO_STRING(X) #X -#define CONVERT_EXPR_TO_STRING(X) CONVERT_TO_STRING(X) - -#ifdef DEBUG - -#define USE_ASSERTS - -// OWSAssertDebug() and OWSFailDebug() should be used in Obj-C methods. -// OWSCAssertDebug() and OWSCFailDebug() should be used in free functions. - -#define OWSAssertDebug(X) \ - do { \ - if (!(X)) { \ - OWSLogError(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - OWSLogFlush(); \ - NSAssert(0, @"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - } \ - } while (NO) - -#define OWSCAssertDebug(X) \ - do { \ - if (!(X)) { \ - OWSLogError(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - OWSLogFlush(); \ - NSCAssert(0, @"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - } \ - } while (NO) - -#define OWSFailWithoutLogging(message, ...) \ - do { \ - NSString *formattedMessage = [NSString stringWithFormat:message, ##__VA_ARGS__]; \ - NSAssert(0, formattedMessage); \ - } while (NO) - -#define OWSCFailWithoutLogging(message, ...) \ - do { \ - NSString *formattedMessage = [NSString stringWithFormat:message, ##__VA_ARGS__]; \ - NSCAssert(0, formattedMessage); \ - } while (NO) - -#define OWSFailNoFormat(message) \ - do { \ - OWSLogError(@"%@", message); \ - OWSLogFlush(); \ - NSAssert(0, message); \ - } while (NO) - -#define OWSCFailNoFormat(message) \ - do { \ - OWSLogError(@"%@", message); \ - OWSLogFlush(); \ - NSCAssert(0, message); \ - } while (NO) - -#else - -#define OWSAssertDebug(X) -#define OWSCAssertDebug(X) -#define OWSFailWithoutLogging(message, ...) -#define OWSCFailWithoutLogging(message, ...) -#define OWSFailNoFormat(X) -#define OWSCFailNoFormat(X) - -#endif - -#endif - -// Like OWSAssertDebug, but will fail in production, terminating the app -#define OWSAssert(X) \ - do { \ - if (!(X)) { \ - OWSFail(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - } \ - } while (NO) - -#define OWSCAssert(X) \ - do { \ - if (!(X)) { \ - OWSCFail(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - } \ - } while (NO) - -#define OWSAbstractMethod() OWSFail(@"Method needs to be implemented by subclasses.") - -// This macro is intended for use in Objective-C. -#define OWSAssertIsOnMainThread() OWSCAssertDebug([NSThread isMainThread]) - -#define OWSFailDebug(_messageFormat, ...) \ - do { \ - OWSLogError(_messageFormat, ##__VA_ARGS__); \ - OWSLogFlush(); \ - OWSFailWithoutLogging(_messageFormat, ##__VA_ARGS__); \ - } while (0) - -#define OWSCFailDebug(_messageFormat, ...) \ - do { \ - OWSLogError(_messageFormat, ##__VA_ARGS__); \ - OWSLogFlush(); \ - OWSCFailWithoutLogging(_messageFormat, ##__VA_ARGS__); \ - } while (NO) - -void SwiftExit(NSString *message, const char *file, const char *function, int line); - -#define OWSFail(_messageFormat, ...) \ - do { \ - OWSFailDebug(_messageFormat, ##__VA_ARGS__); \ - \ - NSString *_message = [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]; \ - SwiftExit(_message, __FILE__, __PRETTY_FUNCTION__, __LINE__); \ - } while (0) - -#define OWSCFail(_messageFormat, ...) \ - do { \ - OWSCFailDebug(_messageFormat, ##__VA_ARGS__); \ - \ - NSString *_message = [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]; \ - SwiftExit(_message, __FILE__, __PRETTY_FUNCTION__, __LINE__); \ - } while (NO) - -// Avoids Clang analyzer warning: -// Value stored to 'x' during it's initialization is never read -#define SUPPRESS_DEADSTORE_WARNING(x) \ - do { \ - (void)x; \ - } while (0) - -__attribute__((annotate("returns_localized_nsstring"))) static inline NSString *LocalizationNotNeeded(NSString *s) -{ - return s; -} - -#define OWSGuardWithException(X, ExceptionName) \ - do { \ - if (!(X)) { \ - OWSRaiseException(ExceptionName, @"Guard failed: %s", CONVERT_EXPR_TO_STRING(X)); \ - } \ - } while (NO) - -#define OWSRaiseException(name, formatParam, ...) \ - do { \ - OWSLogError(@"Exception: %@ %@", name, [NSString stringWithFormat:formatParam, ##__VA_ARGS__]); \ - OWSLogFlush(); \ - @throw [NSException exceptionWithName:name \ - reason:[NSString stringWithFormat:formatParam, ##__VA_ARGS__] \ - userInfo:nil]; \ - } while (NO) - -#define OWSRaiseExceptionWithUserInfo(name, userInfoParam, formatParam, ...) \ - do { \ - OWSLogError( \ - @"Exception: %@ %@ %@", name, userInfoParam, [NSString stringWithFormat:formatParam, ##__VA_ARGS__]); \ - OWSLogFlush(); \ - @throw [NSException exceptionWithName:name \ - reason:[NSString stringWithFormat:formatParam, ##__VA_ARGS__] \ - userInfo:userInfoParam]; \ - } while (NO) - - -// UI JANK -// -// In pursuit of smooth UI, we want to continue moving blocking operations off the main thread. -// Add `OWSJanksUI` in code paths that shouldn't be called on the main thread. -// Because we have pervasively broken this tenant, enabling it by default would be too disruptive -// but it's helpful while unjanking and maybe someday we can have it enabled by default. -//#define DEBUG_UI_JANK 1 - -#ifdef DEBUG -#ifdef DEBUG_UI_JANK -#define OWSJanksUI() \ - do { \ - OWSAssertDebug(![NSThread isMainThread]) \ - } while (NO) -#endif -#endif - -#ifndef OWSJanksUI -#define OWSJanksUI() -#endif - -#pragma mark - Overflow Math - -#define ows_add_overflow(a, b, resultRef) \ - do { \ - BOOL _didOverflow = __builtin_add_overflow(a, b, resultRef); \ - OWSAssert(!_didOverflow); \ - } while (NO) - -#define ows_sub_overflow(a, b, resultRef) \ - do { \ - BOOL _didOverflow = __builtin_sub_overflow(a, b, resultRef); \ - OWSAssert(!_didOverflow); \ - } while (NO) - -#define ows_mul_overflow(a, b, resultRef) \ - do { \ - BOOL _didOverflow = __builtin_mul_overflow(a, b, resultRef); \ - OWSAssert(!_didOverflow); \ - } while (NO) - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/OWSAsserts.m b/SessionProtocolKit/Signal/Utility/OWSAsserts.m deleted file mode 100644 index cafc3aa3d..000000000 --- a/SessionProtocolKit/Signal/Utility/OWSAsserts.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "OWSAsserts.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -void SwiftExit(NSString *message, const char *file, const char *function, int line) -{ - NSString *_file = [NSString stringWithFormat:@"%s", file]; - NSString *_function = [NSString stringWithFormat:@"%s", function]; - [OWSSwiftUtils owsFail:message file:_file function:_function line:line]; -} - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/OWSDataParser.swift b/SessionProtocolKit/Signal/Utility/OWSDataParser.swift deleted file mode 100644 index 3fc472d68..000000000 --- a/SessionProtocolKit/Signal/Utility/OWSDataParser.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -public enum OWSDataParserError: Error { - case overflow(description : String) -} - -// MARK: - OWSDataParser - -@objc public class OWSDataParser: NSObject { - - private let data: Data - private var cursor: UInt = 0 - - @objc public init(data: Data) { - self.data = data - } - - @objc public func nextData(length: UInt, name: String?=nil) throws -> Data { - guard cursor + length <= data.count else { - guard let name = name else { - throw OWSDataParserError.overflow(description: "\(logTag) invalid data read") - } - throw OWSDataParserError.overflow(description: "\(logTag) invalid data read: \(name)") - } - - let endIndex = cursor + length - let result = data.subdata(in: Int(cursor).. UInt8 { - let subdata = try nextData(length: 1, name: name) - return subdata[0] - } - - @objc public func remainder(name: String?=nil) throws -> Data { - return try nextData(length: UInt(data.count) - cursor, name: name) - } - - @objc public var isEmpty: Bool { - return data.count == cursor - } -} diff --git a/SessionProtocolKit/Signal/Utility/OWSLogs.h b/SessionProtocolKit/Signal/Utility/OWSLogs.h deleted file mode 100644 index cdf8b8fe3..000000000 --- a/SessionProtocolKit/Signal/Utility/OWSLogs.h +++ /dev/null @@ -1,91 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -#ifdef DEBUG -static const NSUInteger ddLogLevel = DDLogLevelAll; -#else -static const NSUInteger ddLogLevel = DDLogLevelInfo; -#endif - -static inline BOOL ShouldLogVerbose() -{ - return ddLogLevel >= DDLogLevelVerbose; -} - -static inline BOOL ShouldLogDebug() -{ - return ddLogLevel >= DDLogLevelDebug; -} - -static inline BOOL ShouldLogInfo() -{ - return ddLogLevel >= DDLogLevelInfo; -} - -static inline BOOL ShouldLogWarning() -{ - return ddLogLevel >= DDLogLevelWarning; -} - -static inline BOOL ShouldLogError() -{ - return ddLogLevel >= DDLogLevelError; -} - -/** - * A minimal DDLog wrapper for swift. - */ -@interface OWSLogger : NSObject - -+ (void)verbose:(NSString *)logString; -+ (void)debug:(NSString *)logString; -+ (void)info:(NSString *)logString; -+ (void)warn:(NSString *)logString; -+ (void)error:(NSString *)logString; - -+ (void)flush; - -@end - -#define OWSLogPrefix() \ - ([NSString stringWithFormat:@"[%@:%d %s]: ", \ - [[NSString stringWithUTF8String:__FILE__] lastPathComponent], \ - __LINE__, \ - __PRETTY_FUNCTION__]) - -#define OWSLogVerbose(_messageFormat, ...) \ - do { \ - DDLogVerbose(@"%@%@", OWSLogPrefix(), [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]); \ - } while (0) - -#define OWSLogDebug(_messageFormat, ...) \ - do { \ - DDLogDebug(@"%@%@", OWSLogPrefix(), [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]); \ - } while (0) - -#define OWSLogInfo(_messageFormat, ...) \ - do { \ - DDLogInfo(@"%@%@", OWSLogPrefix(), [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]); \ - } while (0) - -#define OWSLogWarn(_messageFormat, ...) \ - do { \ - DDLogWarn(@"%@%@", OWSLogPrefix(), [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]); \ - } while (0) - -#define OWSLogError(_messageFormat, ...) \ - do { \ - DDLogError(@"%@%@", OWSLogPrefix(), [NSString stringWithFormat:_messageFormat, ##__VA_ARGS__]); \ - } while (0) - -#define OWSLogFlush() \ - do { \ - [DDLog flushLog]; \ - } while (0) - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/OWSLogs.m b/SessionProtocolKit/Signal/Utility/OWSLogs.m deleted file mode 100644 index 4d38312e7..000000000 --- a/SessionProtocolKit/Signal/Utility/OWSLogs.m +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "OWSLogs.h" - -NS_ASSUME_NONNULL_BEGIN - -@implementation OWSLogger - -+ (void)verbose:(NSString *)logString -{ - DDLogVerbose(@"%@", logString); -} - -+ (void)debug:(NSString *)logString -{ - DDLogDebug(@"%@", logString); -} - -+ (void)info:(NSString *)logString -{ - DDLogInfo(@"%@", logString); -} - -+ (void)warn:(NSString *)logString -{ - DDLogWarn(@"%@", logString); -} - -+ (void)error:(NSString *)logString -{ - DDLogError(@"%@", logString); -} - -+ (void)flush -{ - OWSLogFlush(); -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/OWSSwiftUtils.swift b/SessionProtocolKit/Signal/Utility/OWSSwiftUtils.swift deleted file mode 100644 index c5e08bfb3..000000000 --- a/SessionProtocolKit/Signal/Utility/OWSSwiftUtils.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -/** - * We synchronize access to state in this class using this queue. - */ -public func assertOnQueue(_ queue: DispatchQueue) { - if #available(iOS 10.0, *) { - dispatchPrecondition(condition: .onQueue(queue)) - } else { - // Skipping check on Never { - owsFailDebug(logMessage, file: file, function: function, line: line) - let formattedMessage = owsFormatLogMessage(logMessage, file: file, function: function, line: line) - fatalError(formattedMessage) -} - -// Once we're on Swift4.2 we can mark this as inlineable -// @inlinable -public func notImplemented(file: String = #file, - function: String = #function, - line: Int = #line) -> Never { - owsFail("Method not implemented.", file: file, function: function, line: line) -} - -@objc public class OWSSwiftUtils: NSObject { - // This method can be invoked from Obj-C to exit the app. - @objc public class func owsFail(_ logMessage: String, - file: String = #file, - function: String = #function, - line: Int = #line) -> Never { - - owsFailDebug(logMessage, file: file, function: function, line: line) - let formattedMessage = owsFormatLogMessage(logMessage, file: file, function: function, line: line) - fatalError(formattedMessage) - } -} diff --git a/SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.h b/SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.h deleted file mode 100644 index b2eab60bb..000000000 --- a/SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.h +++ /dev/null @@ -1,95 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -extern NSErrorDomain const SCKExceptionWrapperErrorDomain; -typedef NS_ERROR_ENUM(SCKExceptionWrapperErrorDomain, SCKExceptionWrapperError) { - SCKExceptionWrapperErrorThrown = 900 -}; - -extern NSErrorUserInfoKey const SCKExceptionWrapperUnderlyingExceptionKey; - -NSError *SCKExceptionWrapperErrorMake(NSException *exception); - -/// Naming conventions: -/// -/// Every objc method that can throw an exception should be prefixed with `throws_`. -/// e.g. `throws_foo` and `throws_fooWithBar:bar` -/// -/// Every objc method that *calls* an uncaught `throws_` method can throw an exception, -/// so transitively, it should be a `throws_method` -/// -/// WRONG!: -/// -/// -(void)bar -/// { -/// [foo throws_foo]; -/// } -/// -/// RIGHT!: -/// -/// -(void)throws_bar -/// { -/// [foo throws_foo]; -/// } -/// -/// WRONG!: -/// -/// -(void)throws_bar -/// { -/// @try { -/// [foo throws_foo]; -/// } @catch(NSException *exception) { -/// // all exceptions are caught, -/// // so bar doesn't throw. -/// [self doSomethingElse]; -/// } -/// } -/// -/// RIGHT!: -/// -/// -(void)bar -/// { -/// @try { -/// [foo throws_foo]; -/// } @catch(NSException *exception) { -/// // all exceptions are caught, -/// // so bar doesn't throw. -/// [self doSomethingElse]; -/// } -/// } -/// -/// Since initializers must start with the word `init`, an initializer which throws is labeled -/// somewhat awkwardly as: `init_throws_foo` or `init_throws_withFoo:` -/// -/// -/// Any method that can throw an objc exception must not be called from swift, so must be marked -/// as NS_SWIFT_UNAVAILABLE("some helpful comment or alternative"). When appropriate, provide a -/// Swift safe wrapper using SCKExceptionWrapper. -/// -/// -/// -(BOOL)barAndReturnError:(NSError **)outError -/// { -/// return [SCKExceptionWrapper tryBlock:^{ [self throws_bar]; } -/// error:outError]; -/// } -/// -/// -(void)throws_bar -/// { -/// [foo throws_foo]; -/// } - -NS_SWIFT_UNAVAILABLE("throws objc exceptions") -@interface SCKExceptionWrapper: NSObject - -+ (BOOL)tryBlock:(void (^)(void))block error:(NSError **)outError; - -@end - -void SCKRaiseIfExceptionWrapperError(NSError *_Nullable error) NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.m b/SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.m deleted file mode 100644 index fcea30a7f..000000000 --- a/SessionProtocolKit/Signal/Utility/SCKExceptionWrapper.m +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "SCKExceptionWrapper.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -NSErrorDomain const SCKExceptionWrapperErrorDomain = @"SignalCoreKit.SCKExceptionWrapper"; -NSErrorUserInfoKey const SCKExceptionWrapperUnderlyingExceptionKey = @"SCKExceptionWrapperUnderlyingException"; - -NSError *SCKExceptionWrapperErrorMake(NSException *exception) -{ - return [NSError errorWithDomain:SCKExceptionWrapperErrorDomain - code:SCKExceptionWrapperErrorThrown - userInfo:@{ SCKExceptionWrapperUnderlyingExceptionKey : exception }]; -} - -@implementation SCKExceptionWrapper - -+ (BOOL)tryBlock:(void (^)(void))block error:(NSError **)outError -{ - OWSAssertDebug(outError); - @try { - block(); - return YES; - } @catch (NSException *exception) { - *outError = SCKExceptionWrapperErrorMake(exception); - return NO; - } -} - -@end - -void SCKRaiseIfExceptionWrapperError(NSError *_Nullable error) -{ - if (error && [error.domain isEqualToString:SCKExceptionWrapperErrorDomain] - && error.code == SCKExceptionWrapperErrorThrown) { - NSException *_Nullable exception = error.userInfo[SCKExceptionWrapperUnderlyingExceptionKey]; - OWSCAssert(exception); - @throw exception; - } -} - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/SerializationUtilities.m b/SessionProtocolKit/Signal/Utility/SerializationUtilities.m index a06c1f659..c8dd2729f 100644 --- a/SessionProtocolKit/Signal/Utility/SerializationUtilities.m +++ b/SessionProtocolKit/Signal/Utility/SerializationUtilities.m @@ -4,7 +4,7 @@ #import "SerializationUtilities.h" #import -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SessionProtocolKit/Signal/Utility/String+OWS.swift b/SessionProtocolKit/Signal/Utility/String+OWS.swift deleted file mode 100644 index 518ccebb1..000000000 --- a/SessionProtocolKit/Signal/Utility/String+OWS.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -@objc -public extension NSString { - func ows_truncated(toByteCount byteCount: UInt) -> NSString? { - return (self as String).truncated(toByteCount: byteCount) as NSString? - } -} - -public extension String { - var stripped: String { - return (self as NSString).ows_stripped() - } - - var filterForDisplay: String? { - return (self as NSString).filterStringForDisplay() - } - - // Truncates string to be less than or equal to byteCount, while ensuring we never truncate partial characters for multibyte characters. - func truncated(toByteCount byteCount: UInt) -> String? { - var lowerBoundCharCount = 0 - var upperBoundCharCount = self.count - - while (lowerBoundCharCount < upperBoundCharCount) { - guard let upperBoundData = self.prefix(upperBoundCharCount).data(using: .utf8) else { - owsFailDebug("upperBoundData was unexpectedly nil") - return nil - } - - if upperBoundData.count <= byteCount { - break - } - - // converge - if upperBoundCharCount - lowerBoundCharCount == 1 { - upperBoundCharCount = lowerBoundCharCount - break - } - - let midpointCharCount = (lowerBoundCharCount + upperBoundCharCount) / 2 - let midpointString = self.prefix(midpointCharCount) - - guard let midpointData = midpointString.data(using: .utf8) else { - owsFailDebug("midpointData was unexpectedly nil") - return nil - } - let midpointByteCount = midpointData.count - - if midpointByteCount < byteCount { - lowerBoundCharCount = midpointCharCount - } else { - upperBoundCharCount = midpointCharCount - } - } - - return String(self.prefix(upperBoundCharCount)) - } - - func replaceCharacters(characterSet: CharacterSet, replacement: String) -> String { - let components = self.components(separatedBy: characterSet) - return components.joined(separator: replacement) - } - - func removeCharacters(characterSet: CharacterSet) -> String { - let components = self.components(separatedBy: characterSet) - return components.joined() - } -} diff --git a/SessionProtocolKit/Signal/Utility/Threading.h b/SessionProtocolKit/Signal/Utility/Threading.h deleted file mode 100644 index 98c4d724c..000000000 --- a/SessionProtocolKit/Signal/Utility/Threading.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -// The block is executed immediately if called from the -// main thread; otherwise it is dispatched async to the -// main thread. -void DispatchMainThreadSafe(dispatch_block_t block); - -// The block is executed immediately if called from the -// main thread; otherwise it is dispatched sync to the -// main thread. -void DispatchSyncMainThreadSafe(dispatch_block_t block); - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/Threading.m b/SessionProtocolKit/Signal/Utility/Threading.m deleted file mode 100644 index 10504a585..000000000 --- a/SessionProtocolKit/Signal/Utility/Threading.m +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "Threading.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -void DispatchMainThreadSafe(dispatch_block_t block) -{ - OWSCAssertDebug(block); - - if ([NSThread isMainThread]) { - block(); - } else { - dispatch_async(dispatch_get_main_queue(), ^{ - block(); - }); - } -} - -void DispatchSyncMainThreadSafe(dispatch_block_t block) -{ - OWSCAssertDebug(block); - - if ([NSThread isMainThread]) { - block(); - } else { - dispatch_sync(dispatch_get_main_queue(), ^{ - block(); - }); - } -} - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/iOSVersions.h b/SessionProtocolKit/Signal/Utility/iOSVersions.h deleted file mode 100644 index 581401847..000000000 --- a/SessionProtocolKit/Signal/Utility/iOSVersions.h +++ /dev/null @@ -1,8 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(major, minor) \ - ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = major, .minorVersion = minor, .patchVersion = 0}]) diff --git a/SessionShareExtension/Meta/SignalShareExtension-Bridging-Header.h b/SessionShareExtension/Meta/SignalShareExtension-Bridging-Header.h index de6e1ce0d..75494b4e4 100644 --- a/SessionShareExtension/Meta/SignalShareExtension-Bridging-Header.h +++ b/SessionShareExtension/Meta/SignalShareExtension-Bridging-Header.h @@ -8,9 +8,9 @@ // Separate iOS Frameworks from other imports. #import "SAEScreenLockViewController.h" #import "ShareAppExtensionContext.h" -#import -#import -#import +#import +#import +#import #import #import #import diff --git a/SessionShareExtension/Meta/SignalShareExtension-Prefix.pch b/SessionShareExtension/Meta/SignalShareExtension-Prefix.pch index fbeac4a83..228f1b0d4 100644 --- a/SessionShareExtension/Meta/SignalShareExtension-Prefix.pch +++ b/SessionShareExtension/Meta/SignalShareExtension-Prefix.pch @@ -15,7 +15,7 @@ static const NSUInteger ddLogLevel = DDLogLevelInfo; #endif - #import - #import + #import + #import #import #endif diff --git a/SessionUtilitiesKit/AESGCM.swift b/SessionUtilitiesKit/AESGCM.swift index 11fa584dc..8cb40809f 100644 --- a/SessionUtilitiesKit/AESGCM.swift +++ b/SessionUtilitiesKit/AESGCM.swift @@ -55,15 +55,13 @@ public enum AESGCM { #endif } let x25519PublicKey = Data(hex: hexEncodedX25519PublicKey) - guard let ephemeralKeyPair = Curve25519.generateKeyPair() else { - throw Error.keyPairGenerationFailed - } - guard let ephemeralSharedSecret = Curve25519.generateSharedSecret(fromPublicKey: x25519PublicKey, andKeyPair: ephemeralKeyPair) else { + let ephemeralKeyPair = Curve25519.generateKeyPair() + guard let ephemeralSharedSecret = try? Curve25519.generateSharedSecret(fromPublicKey: x25519PublicKey, privateKey: ephemeralKeyPair.privateKey) else { throw Error.sharedSecretGenerationFailed } let salt = "LOKI" let symmetricKey = try HMAC(key: salt.bytes, variant: .sha256).authenticate(ephemeralSharedSecret.bytes) let ciphertext = try encrypt(plaintext, with: Data(symmetricKey)) - return EncryptionResult(ciphertext: ciphertext, symmetricKey: Data(symmetricKey), ephemeralPublicKey: ephemeralKeyPair.publicKey()) + return EncryptionResult(ciphertext: ciphertext, symmetricKey: Data(symmetricKey), ephemeralPublicKey: ephemeralKeyPair.publicKey) } } diff --git a/SessionUtilitiesKit/DiffieHellman.swift b/SessionUtilitiesKit/DiffieHellman.swift index 3858d1094..cbc7b9950 100644 --- a/SessionUtilitiesKit/DiffieHellman.swift +++ b/SessionUtilitiesKit/DiffieHellman.swift @@ -28,8 +28,7 @@ public final class DiffieHellman : NSObject { } public static func encrypt(_ plaintext: Data, publicKey: Data, privateKey: Data) throws -> Data { - let keyPair = ECKeyPair(publicKey: publicKey, privateKey: privateKey) - guard let symmetricKey = Curve25519.generateSharedSecret(fromPublicKey: publicKey, andKeyPair: keyPair) else { throw Error.sharedSecretGenerationFailed } + guard let symmetricKey = try? Curve25519.generateSharedSecret(fromPublicKey: publicKey, privateKey: privateKey) else { throw Error.sharedSecretGenerationFailed } return try encrypt(plaintext, using: symmetricKey) } @@ -44,8 +43,7 @@ public final class DiffieHellman : NSObject { } public static func decrypt(_ ivAndCiphertext: Data, publicKey: Data, privateKey: Data) throws -> Data { - let keyPair = ECKeyPair(publicKey: publicKey, privateKey: privateKey) - guard let symmetricKey = Curve25519.generateSharedSecret(fromPublicKey: publicKey, andKeyPair: keyPair) else { throw Error.sharedSecretGenerationFailed } + guard let symmetricKey = try? Curve25519.generateSharedSecret(fromPublicKey: publicKey, privateKey: privateKey) else { throw Error.sharedSecretGenerationFailed } return try decrypt(ivAndCiphertext, using: symmetricKey) } } diff --git a/SessionUtilitiesKit/ECKeyPair+Utilities.h b/SessionUtilitiesKit/ECKeyPair+Utilities.h deleted file mode 100644 index 6435f2e64..000000000 --- a/SessionUtilitiesKit/ECKeyPair+Utilities.h +++ /dev/null @@ -1,13 +0,0 @@ -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface ECKeyPair (Utilities) - -- (ECKeyPair *)initWithPublicKey:(NSData *)publicKey privateKey:(NSData *)privateKey; -- (NSData *)privateKey; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionUtilitiesKit/ECKeyPair+Utilities.m b/SessionUtilitiesKit/ECKeyPair+Utilities.m deleted file mode 100644 index aaf731bef..000000000 --- a/SessionUtilitiesKit/ECKeyPair+Utilities.m +++ /dev/null @@ -1,22 +0,0 @@ -#import "ECKeyPair+Utilities.h" - -NS_ASSUME_NONNULL_BEGIN - -@implementation ECKeyPair (Utilities) - -- (ECKeyPair *)initWithPublicKey:(NSData *)snPublicKey privateKey:(NSData *)snPrivateKey -{ - ECKeyPair *keyPair = [[ECKeyPair alloc] init]; - [keyPair setValue:snPublicKey forKey:@"publicKey"]; - [keyPair setValue:snPrivateKey forKey:@"privateKey"]; - return keyPair; -} - -- (NSData *)privateKey -{ - return [NSData dataWithBytes:self->privateKey length:32]; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionUtilitiesKit/Meta/SessionUtilitiesKit.h b/SessionUtilitiesKit/Meta/SessionUtilitiesKit.h index f2aec9c6d..8ecbab311 100644 --- a/SessionUtilitiesKit/Meta/SessionUtilitiesKit.h +++ b/SessionUtilitiesKit/Meta/SessionUtilitiesKit.h @@ -3,7 +3,6 @@ FOUNDATION_EXPORT double SessionUtilitiesKitVersionNumber; FOUNDATION_EXPORT const unsigned char SessionUtilitiesKitVersionString[]; -#import #import #import #import diff --git a/Signal.xcodeproj/project.pbxproj b/Signal.xcodeproj/project.pbxproj index 51a7bc5e5..6223796f4 100644 --- a/Signal.xcodeproj/project.pbxproj +++ b/Signal.xcodeproj/project.pbxproj @@ -783,8 +783,6 @@ C3471ED42555386B00297E91 /* AESGCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A5D72553860B00C340D1 /* AESGCM.swift */; }; C3471F4225553A4D00297E91 /* Threading.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3471F4125553A4D00297E91 /* Threading.swift */; }; C3471F4C25553AB000297E91 /* MessageReceiver+Decryption.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3471F4B25553AB000297E91 /* MessageReceiver+Decryption.swift */; }; - C3471F5625553E1100297E91 /* ECKeyPair+Utilities.h in Headers */ = {isa = PBXBuildFile; fileRef = C3471F5525553DA000297E91 /* ECKeyPair+Utilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3471F6825553E7600297E91 /* ECKeyPair+Utilities.m in Sources */ = {isa = PBXBuildFile; fileRef = C3471F6725553E7600297E91 /* ECKeyPair+Utilities.m */; }; C3471FA42555439E00297E91 /* Notification+MessageSender.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3471FA32555439E00297E91 /* Notification+MessageSender.swift */; }; C34C8F7423A7830B00D82669 /* SpaceMono-Bold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = C34C8F7323A7830A00D82669 /* SpaceMono-Bold.ttf */; }; C352A2F525574B4700338F3E /* Job.swift in Sources */ = {isa = PBXBuildFile; fileRef = C352A2F425574B4700338F3E /* Job.swift */; }; @@ -1018,9 +1016,7 @@ C3A71D2925589EBF0043A11F /* SessionRestorationProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D2825589EBF0043A11F /* SessionRestorationProtocol.swift */; }; C3A71D3B25589F2B0043A11F /* SessionRestorationStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D3A25589F2B0043A11F /* SessionRestorationStatus.swift */; }; C3A71D5025589FF30043A11F /* SMKUDAccessKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4425589FF10043A11F /* SMKUDAccessKey.swift */; }; - C3A71D5125589FF30043A11F /* ECPublicKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4525589FF10043A11F /* ECPublicKey.swift */; }; C3A71D5225589FF30043A11F /* SMKError.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4625589FF10043A11F /* SMKError.swift */; }; - C3A71D5325589FF30043A11F /* ECPrivateKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4725589FF10043A11F /* ECPrivateKey.swift */; }; C3A71D5425589FF30043A11F /* NSData+messagePadding.m in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4825589FF20043A11F /* NSData+messagePadding.m */; }; C3A71D5525589FF30043A11F /* SMKSenderCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4925589FF20043A11F /* SMKSenderCertificate.swift */; }; C3A71D5625589FF30043A11F /* SMKServerCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4A25589FF20043A11F /* SMKServerCertificate.swift */; }; @@ -1148,30 +1144,6 @@ C3C2A96F2553B63C00C340D1 /* NSData+keyVersionByte.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A96B2553B63C00C340D1 /* NSData+keyVersionByte.h */; settings = {ATTRIBUTES = (Public, ); }; }; C3C2A9702553B63C00C340D1 /* SerializationUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A96C2553B63C00C340D1 /* SerializationUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; C3C2A9712553B63C00C340D1 /* SerializationUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A96D2553B63C00C340D1 /* SerializationUtilities.m */; }; - C3C2A9EF2553B9C400C340D1 /* OWSDataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9D42553B9C100C340D1 /* OWSDataParser.swift */; }; - C3C2A9F02553B9C400C340D1 /* OWSAsserts.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9D52553B9C200C340D1 /* OWSAsserts.m */; }; - C3C2A9F12553B9C400C340D1 /* OWSLogs.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9D62553B9C200C340D1 /* OWSLogs.m */; }; - C3C2A9F22553B9C400C340D1 /* NSObject+OWS.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9D72553B9C200C340D1 /* NSObject+OWS.m */; }; - C3C2A9F32553B9C400C340D1 /* String+OWS.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9D82553B9C200C340D1 /* String+OWS.swift */; }; - C3C2A9F42553B9C400C340D1 /* Threading.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9D92553B9C200C340D1 /* Threading.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9F52553B9C400C340D1 /* NSDate+OWS.mm in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9DA2553B9C200C340D1 /* NSDate+OWS.mm */; }; - C3C2A9F62553B9C400C340D1 /* Data+OWS.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9DB2553B9C200C340D1 /* Data+OWS.swift */; }; - C3C2A9F72553B9C400C340D1 /* NSData+OWS.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9DC2553B9C200C340D1 /* NSData+OWS.m */; }; - C3C2A9F82553B9C400C340D1 /* NSString+OWS.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9DD2553B9C200C340D1 /* NSString+OWS.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9F92553B9C400C340D1 /* NSData+OWS.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9DE2553B9C200C340D1 /* NSData+OWS.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9FA2553B9C400C340D1 /* OWSSwiftUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9DF2553B9C200C340D1 /* OWSSwiftUtils.swift */; }; - C3C2A9FB2553B9C400C340D1 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9E02553B9C300C340D1 /* Logger.swift */; }; - C3C2A9FC2553B9C400C340D1 /* iOSVersions.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9E12553B9C300C340D1 /* iOSVersions.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9FD2553B9C400C340D1 /* SCKExceptionWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9E22553B9C300C340D1 /* SCKExceptionWrapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9FE2553B9C400C340D1 /* OWSLogs.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9E32553B9C300C340D1 /* OWSLogs.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2AA002553B9C400C340D1 /* NSDate+OWS.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9E52553B9C300C340D1 /* NSDate+OWS.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2AA012553B9C400C340D1 /* Threading.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9E62553B9C300C340D1 /* Threading.m */; }; - C3C2AA022553B9C400C340D1 /* Cryptography.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9E72553B9C300C340D1 /* Cryptography.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2AA042553B9C400C340D1 /* OWSAsserts.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9E92553B9C300C340D1 /* OWSAsserts.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2AA052553B9C400C340D1 /* SCKExceptionWrapper.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9EA2553B9C300C340D1 /* SCKExceptionWrapper.m */; }; - C3C2AA072553B9C400C340D1 /* Cryptography.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9EC2553B9C400C340D1 /* Cryptography.m */; }; - C3C2AA082553B9C400C340D1 /* NSString+OWS.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9ED2553B9C400C340D1 /* NSString+OWS.m */; }; - C3C2AA092553B9C400C340D1 /* NSObject+OWS.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9EE2553B9C400C340D1 /* NSObject+OWS.h */; settings = {ATTRIBUTES = (Public, ); }; }; C3C2AAC82553C25300C340D1 /* SessionProtocolKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C3C2A8622553B41A00C340D1 /* SessionProtocolKit.framework */; }; C3C2AB642553C5FF00C340D1 /* SharedSenderKeys.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2AB632553C5FF00C340D1 /* SharedSenderKeys.swift */; }; C3C2ABD22553C6C900C340D1 /* Data+SecureRandom.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2ABD12553C6C900C340D1 /* Data+SecureRandom.swift */; }; @@ -2172,8 +2144,6 @@ C3471ECA2555356A00297E91 /* MessageSender+Encryption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MessageSender+Encryption.swift"; sourceTree = ""; }; C3471F4125553A4D00297E91 /* Threading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Threading.swift; sourceTree = ""; }; C3471F4B25553AB000297E91 /* MessageReceiver+Decryption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MessageReceiver+Decryption.swift"; sourceTree = ""; }; - C3471F5525553DA000297E91 /* ECKeyPair+Utilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ECKeyPair+Utilities.h"; sourceTree = ""; }; - C3471F6725553E7600297E91 /* ECKeyPair+Utilities.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "ECKeyPair+Utilities.m"; sourceTree = ""; }; C3471FA32555439E00297E91 /* Notification+MessageSender.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Notification+MessageSender.swift"; sourceTree = ""; }; C34C8F7323A7830A00D82669 /* SpaceMono-Bold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "SpaceMono-Bold.ttf"; sourceTree = ""; }; C352A2F425574B4700338F3E /* Job.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Job.swift; sourceTree = ""; }; @@ -2407,9 +2377,7 @@ C3A71D2825589EBF0043A11F /* SessionRestorationProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRestorationProtocol.swift; sourceTree = ""; }; C3A71D3A25589F2B0043A11F /* SessionRestorationStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRestorationStatus.swift; sourceTree = ""; }; C3A71D4425589FF10043A11F /* SMKUDAccessKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKUDAccessKey.swift; sourceTree = ""; }; - C3A71D4525589FF10043A11F /* ECPublicKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ECPublicKey.swift; sourceTree = ""; }; C3A71D4625589FF10043A11F /* SMKError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKError.swift; sourceTree = ""; }; - C3A71D4725589FF10043A11F /* ECPrivateKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ECPrivateKey.swift; sourceTree = ""; }; C3A71D4825589FF20043A11F /* NSData+messagePadding.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+messagePadding.m"; sourceTree = ""; }; C3A71D4925589FF20043A11F /* SMKSenderCertificate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKSenderCertificate.swift; sourceTree = ""; }; C3A71D4A25589FF20043A11F /* SMKServerCertificate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKServerCertificate.swift; sourceTree = ""; }; @@ -2544,30 +2512,6 @@ C3C2A96B2553B63C00C340D1 /* NSData+keyVersionByte.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSData+keyVersionByte.h"; path = "Utility/NSData+keyVersionByte.h"; sourceTree = ""; }; C3C2A96C2553B63C00C340D1 /* SerializationUtilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SerializationUtilities.h; path = Utility/SerializationUtilities.h; sourceTree = ""; }; C3C2A96D2553B63C00C340D1 /* SerializationUtilities.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SerializationUtilities.m; path = Utility/SerializationUtilities.m; sourceTree = ""; }; - C3C2A9D42553B9C100C340D1 /* OWSDataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OWSDataParser.swift; path = Utility/OWSDataParser.swift; sourceTree = ""; }; - C3C2A9D52553B9C200C340D1 /* OWSAsserts.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = OWSAsserts.m; path = Utility/OWSAsserts.m; sourceTree = ""; }; - C3C2A9D62553B9C200C340D1 /* OWSLogs.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = OWSLogs.m; path = Utility/OWSLogs.m; sourceTree = ""; }; - C3C2A9D72553B9C200C340D1 /* NSObject+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSObject+OWS.m"; path = "Utility/NSObject+OWS.m"; sourceTree = ""; }; - C3C2A9D82553B9C200C340D1 /* String+OWS.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "String+OWS.swift"; path = "Utility/String+OWS.swift"; sourceTree = ""; }; - C3C2A9D92553B9C200C340D1 /* Threading.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Threading.h; path = Utility/Threading.h; sourceTree = ""; }; - C3C2A9DA2553B9C200C340D1 /* NSDate+OWS.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "NSDate+OWS.mm"; path = "Utility/NSDate+OWS.mm"; sourceTree = ""; }; - C3C2A9DB2553B9C200C340D1 /* Data+OWS.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "Data+OWS.swift"; path = "Utility/Data+OWS.swift"; sourceTree = ""; }; - C3C2A9DC2553B9C200C340D1 /* NSData+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSData+OWS.m"; path = "Utility/NSData+OWS.m"; sourceTree = ""; }; - C3C2A9DD2553B9C200C340D1 /* NSString+OWS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+OWS.h"; path = "Utility/NSString+OWS.h"; sourceTree = ""; }; - C3C2A9DE2553B9C200C340D1 /* NSData+OWS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSData+OWS.h"; path = "Utility/NSData+OWS.h"; sourceTree = ""; }; - C3C2A9DF2553B9C200C340D1 /* OWSSwiftUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OWSSwiftUtils.swift; path = Utility/OWSSwiftUtils.swift; sourceTree = ""; }; - C3C2A9E02553B9C300C340D1 /* Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Logger.swift; path = Utility/Logger.swift; sourceTree = ""; }; - C3C2A9E12553B9C300C340D1 /* iOSVersions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = iOSVersions.h; path = Utility/iOSVersions.h; sourceTree = ""; }; - C3C2A9E22553B9C300C340D1 /* SCKExceptionWrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SCKExceptionWrapper.h; path = Utility/SCKExceptionWrapper.h; sourceTree = ""; }; - C3C2A9E32553B9C300C340D1 /* OWSLogs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OWSLogs.h; path = Utility/OWSLogs.h; sourceTree = ""; }; - C3C2A9E52553B9C300C340D1 /* NSDate+OWS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSDate+OWS.h"; path = "Utility/NSDate+OWS.h"; sourceTree = ""; }; - C3C2A9E62553B9C300C340D1 /* Threading.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Threading.m; path = Utility/Threading.m; sourceTree = ""; }; - C3C2A9E72553B9C300C340D1 /* Cryptography.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Cryptography.h; path = Utility/Cryptography.h; sourceTree = ""; }; - C3C2A9E92553B9C300C340D1 /* OWSAsserts.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OWSAsserts.h; path = Utility/OWSAsserts.h; sourceTree = ""; }; - C3C2A9EA2553B9C300C340D1 /* SCKExceptionWrapper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SCKExceptionWrapper.m; path = Utility/SCKExceptionWrapper.m; sourceTree = ""; }; - C3C2A9EC2553B9C400C340D1 /* Cryptography.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Cryptography.m; path = Utility/Cryptography.m; sourceTree = ""; }; - C3C2A9ED2553B9C400C340D1 /* NSString+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSString+OWS.m"; path = "Utility/NSString+OWS.m"; sourceTree = ""; }; - C3C2A9EE2553B9C400C340D1 /* NSObject+OWS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSObject+OWS.h"; path = "Utility/NSObject+OWS.h"; sourceTree = ""; }; C3C2AB632553C5FF00C340D1 /* SharedSenderKeys.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedSenderKeys.swift; sourceTree = ""; }; C3C2ABD12553C6C900C340D1 /* Data+SecureRandom.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Data+SecureRandom.swift"; sourceTree = ""; }; C3C2ABE32553C74400C340D1 /* ClosedGroupRatchet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClosedGroupRatchet.swift; sourceTree = ""; }; @@ -4065,8 +4009,6 @@ C3A71DB12558B25F0043A11F /* Metadata */ = { isa = PBXGroup; children = ( - C3A71D4725589FF10043A11F /* ECPrivateKey.swift */, - C3A71D4525589FF10043A11F /* ECPublicKey.swift */, C3A71D4E25589FF30043A11F /* NSData+messagePadding.h */, C3A71D4825589FF20043A11F /* NSData+messagePadding.m */, C3A71D4B25589FF20043A11F /* SMKCertificateValidator.swift */, @@ -4168,8 +4110,6 @@ C3C2ABD12553C6C900C340D1 /* Data+SecureRandom.swift */, C3C2A5D52553860A00C340D1 /* Dictionary+Description.swift */, C3A71D662558A0170043A11F /* DiffieHellman.swift */, - C3471F5525553DA000297E91 /* ECKeyPair+Utilities.h */, - C3471F6725553E7600297E91 /* ECKeyPair+Utilities.m */, C3C2A5BC255385EE00C340D1 /* HTTP.swift */, C3C2A5D92553860B00C340D1 /* JSON.swift */, C3C2A5CE2553860700C340D1 /* Logging.swift */, @@ -4370,34 +4310,10 @@ C3C2A9692553B62B00C340D1 /* Utility */ = { isa = PBXGroup; children = ( - C3C2A9E72553B9C300C340D1 /* Cryptography.h */, - C3C2A9EC2553B9C400C340D1 /* Cryptography.m */, - C3C2A9DB2553B9C200C340D1 /* Data+OWS.swift */, - C3C2A9E12553B9C300C340D1 /* iOSVersions.h */, - C3C2A9E02553B9C300C340D1 /* Logger.swift */, C3C2A96B2553B63C00C340D1 /* NSData+keyVersionByte.h */, C3C2A96A2553B63B00C340D1 /* NSData+keyVersionByte.m */, - C3C2A9DE2553B9C200C340D1 /* NSData+OWS.h */, - C3C2A9DC2553B9C200C340D1 /* NSData+OWS.m */, - C3C2A9E52553B9C300C340D1 /* NSDate+OWS.h */, - C3C2A9DA2553B9C200C340D1 /* NSDate+OWS.mm */, - C3C2A9EE2553B9C400C340D1 /* NSObject+OWS.h */, - C3C2A9D72553B9C200C340D1 /* NSObject+OWS.m */, - C3C2A9DD2553B9C200C340D1 /* NSString+OWS.h */, - C3C2A9ED2553B9C400C340D1 /* NSString+OWS.m */, - C3C2A9E92553B9C300C340D1 /* OWSAsserts.h */, - C3C2A9D52553B9C200C340D1 /* OWSAsserts.m */, - C3C2A9D42553B9C100C340D1 /* OWSDataParser.swift */, - C3C2A9E32553B9C300C340D1 /* OWSLogs.h */, - C3C2A9D62553B9C200C340D1 /* OWSLogs.m */, - C3C2A9DF2553B9C200C340D1 /* OWSSwiftUtils.swift */, - C3C2A9E22553B9C300C340D1 /* SCKExceptionWrapper.h */, - C3C2A9EA2553B9C300C340D1 /* SCKExceptionWrapper.m */, C3C2A96C2553B63C00C340D1 /* SerializationUtilities.h */, C3C2A96D2553B63C00C340D1 /* SerializationUtilities.m */, - C3C2A9D82553B9C200C340D1 /* String+OWS.swift */, - C3C2A9D92553B9C200C340D1 /* Threading.h */, - C3C2A9E62553B9C300C340D1 /* Threading.m */, ); name = Utility; sourceTree = ""; @@ -4809,7 +4725,6 @@ C352A3B72557B6ED00338F3E /* TSRequest.h in Headers */, C300A63B2554B72200555489 /* NSDate+Timestamp.h in Headers */, C352A3772557864000338F3E /* NSTimer+Proxying.h in Headers */, - C3471F5625553E1100297E91 /* ECKeyPair+Utilities.h in Headers */, C3C2A67D255388CC00C340D1 /* SessionUtilitiesKit.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -4826,7 +4741,6 @@ isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - C3C2AA092553B9C400C340D1 /* NSObject+OWS.h in Headers */, C3C2A95E2553B62400C340D1 /* IdentityKeyStore.h in Headers */, C3C2A95D2553B62400C340D1 /* PreKeyStore.h in Headers */, C3C2A91F2553B5B200C340D1 /* AxolotlParameters.h in Headers */, @@ -4834,19 +4748,15 @@ C3C2A8D52553B57C00C340D1 /* PreKeyBundle.h in Headers */, C3C2A9092553B5B200C340D1 /* RatchetingSession.h in Headers */, C3C2A96F2553B63C00C340D1 /* NSData+keyVersionByte.h in Headers */, - C3C2A9FC2553B9C400C340D1 /* iOSVersions.h in Headers */, C3C2A91D2553B5B200C340D1 /* AliceAxolotlParameters.h in Headers */, C3C2A9402553B5D700C340D1 /* SessionRecord.h in Headers */, - C3C2A9F42553B9C400C340D1 /* Threading.h in Headers */, C3C2A90A2553B5B200C340D1 /* Chain.h in Headers */, C3C2A8882553B4CC00C340D1 /* AxolotlExceptions.h in Headers */, C3A71D5A25589FF30043A11F /* NSData+messagePadding.h in Headers */, C3C2A89E2553B4F600C340D1 /* WhisperMessage.h in Headers */, C3C2A8D92553B57C00C340D1 /* PreKeyRecord.h in Headers */, C3C2A90B2553B5B200C340D1 /* MessageKeys.h in Headers */, - C3C2AA022553B9C400C340D1 /* Cryptography.h in Headers */, C3C2A90C2553B5B200C340D1 /* RKCK.h in Headers */, - C3C2AA042553B9C400C340D1 /* OWSAsserts.h in Headers */, C3C2A92B2553B5BE00C340D1 /* SessionCipher.h in Headers */, C3C2A9152553B5B200C340D1 /* BobAxolotlParameters.h in Headers */, C3C2A9412553B5D700C340D1 /* SessionState.h in Headers */, @@ -4855,17 +4765,12 @@ C3C2A89F2553B4F600C340D1 /* ClosedGroupCiphertextMessage.h in Headers */, C3C2A95C2553B62400C340D1 /* AxolotlStore.h in Headers */, C3C2A9602553B62400C340D1 /* SignedPreKeyStore.h in Headers */, - C3C2A9F82553B9C400C340D1 /* NSString+OWS.h in Headers */, C3C2A9702553B63C00C340D1 /* SerializationUtilities.h in Headers */, C3C2A8A42553B4F600C340D1 /* FallbackMessage.h in Headers */, C3C2A9122553B5B200C340D1 /* ReceivingChain.h in Headers */, - C3C2AA002553B9C400C340D1 /* NSDate+OWS.h in Headers */, C3C2A9202553B5B200C340D1 /* SendingChain.h in Headers */, C3C2A89C2553B4F600C340D1 /* PreKeyWhisperMessage.h in Headers */, - C3C2A9FD2553B9C400C340D1 /* SCKExceptionWrapper.h in Headers */, C3C2A8B62553B53800C340D1 /* Constants.h in Headers */, - C3C2A9FE2553B9C400C340D1 /* OWSLogs.h in Headers */, - C3C2A9F92553B9C400C340D1 /* NSData+OWS.h in Headers */, C3C2A8C22553B55600C340D1 /* AES-CBC.h in Headers */, C3C2A93C2553B5D700C340D1 /* SessionBuilder.h in Headers */, C3C2A9162553B5B200C340D1 /* ChainAndIndex.h in Headers */, @@ -5469,6 +5374,7 @@ "${BUILT_PRODUCTS_DIR}/ZXingObjC/ZXingObjC.framework", "${BUILT_PRODUCTS_DIR}/Curve25519Kit/Curve25519Kit.framework", "${PODS_ROOT}/GRKOpenSSLFramework/OpenSSL-iOS/bin/openssl.framework", + "${BUILT_PRODUCTS_DIR}/SignalCoreKit/SignalCoreKit.framework", "${BUILT_PRODUCTS_DIR}/HKDFKit/HKDFKit.framework", "${BUILT_PRODUCTS_DIR}/SAMKeychain/SAMKeychain.framework", "${BUILT_PRODUCTS_DIR}/SwiftProtobuf/SwiftProtobuf.framework", @@ -5494,6 +5400,7 @@ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ZXingObjC.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Curve25519Kit.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/openssl.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SignalCoreKit.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/HKDFKit.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SAMKeychain.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftProtobuf.framework", @@ -6090,7 +5997,6 @@ C3C2ABD22553C6C900C340D1 /* Data+SecureRandom.swift in Sources */, C3A7211A2558BCA10043A11F /* DiffieHellman.swift in Sources */, C3A7225E2558C38D0043A11F /* AnyPromise+Retaining.swift in Sources */, - C3471F6825553E7600297E91 /* ECKeyPair+Utilities.m in Sources */, C3BBE0AA2554D4DE0050F1E3 /* Dictionary+Description.swift in Sources */, C3C2AC2E2553CBEB00C340D1 /* String+Trimming.swift in Sources */, C352A3A62557B60D00338F3E /* TSRequest.m in Sources */, @@ -6171,49 +6077,34 @@ C3C2A9172553B5B200C340D1 /* RootKey.m in Sources */, C3C2A9112553B5B200C340D1 /* ChainKey.m in Sources */, C3C2A8C32553B55600C340D1 /* AES-CBC.m in Sources */, - C3C2AA012553B9C400C340D1 /* Threading.m in Sources */, - C3C2A9F32553B9C400C340D1 /* String+OWS.swift in Sources */, C3A71D682558A0170043A11F /* LokiSessionCipher.swift in Sources */, - C3C2A9F12553B9C400C340D1 /* OWSLogs.m in Sources */, - C3C2A9F22553B9C400C340D1 /* NSObject+OWS.m in Sources */, C3A71D5B25589FF30043A11F /* SMKUnidentifiedSenderMessage.swift in Sources */, C3C2A9182553B5B200C340D1 /* SendingChain.m in Sources */, C3C2A8A02553B4F600C340D1 /* PreKeyWhisperMessage.m in Sources */, C3A71D5225589FF30043A11F /* SMKError.swift in Sources */, C3C2A93F2553B5D700C340D1 /* SessionState.m in Sources */, - C3C2A9F02553B9C400C340D1 /* OWSAsserts.m in Sources */, - C3A71D5125589FF30043A11F /* ECPublicKey.swift in Sources */, C3C2ABF82553C8A300C340D1 /* Storage.swift in Sources */, - C3C2A9F72553B9C400C340D1 /* NSData+OWS.m in Sources */, C3C2A90D2553B5B200C340D1 /* RKCK.m in Sources */, C3C2A8E72553B59B00C340D1 /* SPKProto.swift in Sources */, - C3A71D5325589FF30043A11F /* ECPrivateKey.swift in Sources */, C3A71D5525589FF30043A11F /* SMKSenderCertificate.swift in Sources */, C3C2A91E2553B5B200C340D1 /* ChainAndIndex.m in Sources */, C3C2A91A2553B5B200C340D1 /* TSDerivedSecrets.m in Sources */, C3A71D5025589FF30043A11F /* SMKUDAccessKey.swift in Sources */, C3C2A91C2553B5B200C340D1 /* ReceivingChain.m in Sources */, - C3C2A9EF2553B9C400C340D1 /* OWSDataParser.swift in Sources */, C3C2A8A32553B4F600C340D1 /* FallbackMessage.m in Sources */, C3A71D5425589FF30043A11F /* NSData+messagePadding.m in Sources */, - C3C2AA072553B9C400C340D1 /* Cryptography.m in Sources */, - C3C2A9F52553B9C400C340D1 /* NSDate+OWS.mm in Sources */, C3C2ABE42553C74400C340D1 /* ClosedGroupRatchet.swift in Sources */, C3C2A93E2553B5D700C340D1 /* SessionRecord.m in Sources */, C3A71D742558A0F60043A11F /* SMKProto.swift in Sources */, - C3C2AA052553B9C400C340D1 /* SCKExceptionWrapper.m in Sources */, C3A71D2925589EBF0043A11F /* SessionRestorationProtocol.swift in Sources */, C3C2A8D62553B57C00C340D1 /* PreKeyBundle.m in Sources */, - C3C2A9F62553B9C400C340D1 /* Data+OWS.swift in Sources */, C3C2A89D2553B4F600C340D1 /* ClosedGroupCiphertextMessage.m in Sources */, - C3C2A9FB2553B9C400C340D1 /* Logger.swift in Sources */, C3A71D672558A0170043A11F /* FallbackSessionCipher.swift in Sources */, C3C2AC0A2553C9A100C340D1 /* Configuration.swift in Sources */, C3C2A96E2553B63C00C340D1 /* NSData+keyVersionByte.m in Sources */, C3C2A8E62553B59B00C340D1 /* WhisperTextProtocol.pb.swift in Sources */, C3C2AB642553C5FF00C340D1 /* SharedSenderKeys.swift in Sources */, C3C2A9102553B5B200C340D1 /* AliceAxolotlParameters.m in Sources */, - C3C2A9FA2553B9C400C340D1 /* OWSSwiftUtils.swift in Sources */, C3C2A92C2553B5BE00C340D1 /* SessionCipher.m in Sources */, C3C2A8D42553B57C00C340D1 /* SignedPrekeyRecord.m in Sources */, C3A71D752558A0F60043A11F /* OWSUnidentifiedDelivery.pb.swift in Sources */, @@ -6223,7 +6114,6 @@ C3C2A90F2553B5B200C340D1 /* RatchetingSession.m in Sources */, C3A71D5725589FF30043A11F /* SMKCertificateValidator.swift in Sources */, C3C2A93D2553B5D700C340D1 /* SessionBuilder.m in Sources */, - C3C2AA082553B9C400C340D1 /* NSString+OWS.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/SignalUtilitiesKit/ClosedGroupUtilities.swift b/SignalUtilitiesKit/ClosedGroupUtilities.swift index c80383cf3..4521eb444 100644 --- a/SignalUtilitiesKit/ClosedGroupUtilities.swift +++ b/SignalUtilitiesKit/ClosedGroupUtilities.swift @@ -53,8 +53,7 @@ public final class ClosedGroupUtilities : NSObject { let ivAndCiphertext = wrapper.ciphertext let ephemeralPublicKey = wrapper.ephemeralPublicKey // 3. ) Decrypt the data inside - let groupKeyPair = ECKeyPair(publicKey: Data(hex: groupPublicKey), privateKey: groupPrivateKey) - let ephemeralSharedSecret = Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey, andKeyPair: groupKeyPair)! + let ephemeralSharedSecret = try Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey, privateKey: groupPrivateKey) let salt = "LOKI" let symmetricKey = try HMAC(key: salt.bytes, variant: .sha256).authenticate(ephemeralSharedSecret.bytes) let closedGroupCiphertextMessageAsData = try DecryptionUtilities.decrypt(ivAndCiphertext, usingAESGCMWithSymmetricKey: Data(symmetricKey)) diff --git a/SignalUtilitiesKit/ClosedGroupsProtocol.swift b/SignalUtilitiesKit/ClosedGroupsProtocol.swift index f1fb0f478..0d62b1750 100644 --- a/SignalUtilitiesKit/ClosedGroupsProtocol.swift +++ b/SignalUtilitiesKit/ClosedGroupsProtocol.swift @@ -40,7 +40,7 @@ public final class ClosedGroupsProtocol : NSObject { let messageSenderJobQueue = SSKEnvironment.shared.messageSenderJobQueue let userPublicKey = getUserHexEncodedPublicKey() // Generate a key pair for the group - let groupKeyPair = Curve25519.generateKeyPair()! + let groupKeyPair = Curve25519.generateKeyPair() let groupPublicKey = groupKeyPair.hexEncodedPublicKey // Includes the "05" prefix // Ensure the current user's master device is the one that's included in the member list members.remove(userPublicKey) @@ -74,12 +74,12 @@ public final class ClosedGroupsProtocol : NSObject { let thread = TSContactThread.getOrCreateThread(withContactId: member, transaction: transaction) thread.save(with: transaction) let closedGroupUpdateMessageKind = ClosedGroupUpdateMessage.Kind.new(groupPublicKey: Data(hex: groupPublicKey), name: name, - groupPrivateKey: groupKeyPair.privateKey(), senderKeys: senderKeys, members: membersAsData, admins: adminsAsData) + groupPrivateKey: groupKeyPair.privateKey, senderKeys: senderKeys, members: membersAsData, admins: adminsAsData) let closedGroupUpdateMessage = ClosedGroupUpdateMessage(thread: thread, kind: closedGroupUpdateMessageKind) promises.append(SSKEnvironment.shared.messageSender.sendPromise(message: closedGroupUpdateMessage)) } // Add the group to the user's set of public keys to poll for - Storage.setClosedGroupPrivateKey(groupKeyPair.privateKey().toHexString(), for: groupPublicKey, using: transaction) + Storage.setClosedGroupPrivateKey(groupKeyPair.privateKey.toHexString(), for: groupPublicKey, using: transaction) // Notify the PN server promises.append(LokiPushNotificationManager.performOperation(.subscribe, for: groupPublicKey, publicKey: userPublicKey)) // Notify the user diff --git a/SignalUtilitiesKit/Contact.m b/SignalUtilitiesKit/Contact.m index f679758d8..c16a43c85 100644 --- a/SignalUtilitiesKit/Contact.m +++ b/SignalUtilitiesKit/Contact.m @@ -8,8 +8,8 @@ #import "SSKEnvironment.h" #import "SignalRecipient.h" #import "TSAccountManager.h" -#import -#import +#import +#import #import @import Contacts; diff --git a/SignalUtilitiesKit/ContactDiscoveryService.m b/SignalUtilitiesKit/ContactDiscoveryService.m index 17c609298..4b51a5980 100644 --- a/SignalUtilitiesKit/ContactDiscoveryService.m +++ b/SignalUtilitiesKit/ContactDiscoveryService.m @@ -98,9 +98,9 @@ NSError *ContactDiscoveryServiceErrorMakeWithReason(NSInteger code, NSString *re NSData *ephemeralToStatic; @try { ephemeralToEphemeral = - [Curve25519 generateSharedSecretFromPublicKey:self.serverEphemeralPublic andKeyPair:self.keyPair]; + [Curve25519 throws_generateSharedSecretFromPublicKey:self.serverEphemeralPublic privateKey:self.keyPair.privateKey]; ephemeralToStatic = - [Curve25519 generateSharedSecretFromPublicKey:self.serverStaticPublic andKeyPair:self.keyPair]; + [Curve25519 throws_generateSharedSecretFromPublicKey:self.serverStaticPublic privateKey:self.keyPair.privateKey]; } @catch (NSException *exception) { OWSFailDebug(@"could not generate shared secrets: %@", exception); return NO; diff --git a/SignalUtilitiesKit/ContactsUpdater.m b/SignalUtilitiesKit/ContactsUpdater.m index 1fa10886a..c033d07a1 100644 --- a/SignalUtilitiesKit/ContactsUpdater.m +++ b/SignalUtilitiesKit/ContactsUpdater.m @@ -9,8 +9,8 @@ #import "PhoneNumber.h" #import "SSKEnvironment.h" #import "TSNetworkManager.h" -#import -#import +#import +#import #import #import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/DataSource.m b/SignalUtilitiesKit/DataSource.m index 369fe71f1..723983b55 100755 --- a/SignalUtilitiesKit/DataSource.m +++ b/SignalUtilitiesKit/DataSource.m @@ -6,7 +6,7 @@ #import "MIMETypeUtil.h" #import "NSData+Image.h" #import "OWSFileSystem.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/DeviceNames.swift b/SignalUtilitiesKit/DeviceNames.swift index 00505ea14..e349a56f4 100644 --- a/SignalUtilitiesKit/DeviceNames.swift +++ b/SignalUtilitiesKit/DeviceNames.swift @@ -4,6 +4,7 @@ import Foundation import Curve25519Kit +import SignalCoreKit @objc public enum DeviceNameError: Int, Error { @@ -27,12 +28,12 @@ public class DeviceNames: NSObject { throw DeviceNameError.invalidInput } - let ephemeralKeyPair = Curve25519.generateKeyPair()! + let ephemeralKeyPair = Curve25519.generateKeyPair() // master_secret = ECDH(ephemeral_private, identity_public). let masterSecret: Data do { - masterSecret = try Curve25519.generateSharedSecret(fromPublicKey: identityKeyPair.publicKey(), andKeyPair: ephemeralKeyPair) + masterSecret = try Curve25519.generateSharedSecret(fromPublicKey: identityKeyPair.publicKey, privateKey: ephemeralKeyPair.privateKey) } catch { Logger.error("Could not generate shared secret: \(error)") throw error @@ -58,7 +59,7 @@ public class DeviceNames: NSObject { throw DeviceNameError.assertionFailure } - guard let keyData = (ephemeralKeyPair.publicKey() as NSData).prependKeyType() else { + guard let keyData = (ephemeralKeyPair.publicKey as NSData).prependKeyType() else { owsFailDebug("Could not prepend key type.") throw DeviceNameError.assertionFailure } @@ -176,7 +177,7 @@ public class DeviceNames: NSObject { // master_secret = ECDH(identity_private, ephemeral_public) let masterSecret: Data do { - masterSecret = try Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublic, andKeyPair: identityKeyPair) + masterSecret = try Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublic, privateKey: identityKeyPair.privateKey) } catch { Logger.error("Could not generate shared secret: \(error)") throw error diff --git a/SignalUtilitiesKit/ECKeyPair+Hexadecimal.swift b/SignalUtilitiesKit/ECKeyPair+Hexadecimal.swift index ae9c07b85..894fd19ca 100644 --- a/SignalUtilitiesKit/ECKeyPair+Hexadecimal.swift +++ b/SignalUtilitiesKit/ECKeyPair+Hexadecimal.swift @@ -2,12 +2,12 @@ public extension ECKeyPair { @objc public var hexEncodedPrivateKey: String { - return privateKey().map { String(format: "%02hhx", $0) }.joined() + return privateKey.map { String(format: "%02hhx", $0) }.joined() } @objc public var hexEncodedPublicKey: String { // Prefixing with "05" is necessary for what seems to be a sort of Signal public key versioning system - return "05" + publicKey().map { String(format: "%02hhx", $0) }.joined() + return "05" + publicKey.map { String(format: "%02hhx", $0) }.joined() } @objc public static func isValidHexEncodedPublicKey(candidate: String) -> Bool { diff --git a/SignalUtilitiesKit/EncryptionUtilities.swift b/SignalUtilitiesKit/EncryptionUtilities.swift index 3820c8d55..cdb4db90f 100644 --- a/SignalUtilitiesKit/EncryptionUtilities.swift +++ b/SignalUtilitiesKit/EncryptionUtilities.swift @@ -17,7 +17,7 @@ enum EncryptionUtilities { let gcm = GCM(iv: iv.bytes, tagLength: Int(gcmTagSize), mode: .combined) let aes = try AES(key: symmetricKey.bytes, blockMode: gcm, padding: .noPadding) let ciphertext = try aes.encrypt(plaintext.bytes) - return iv + Data(bytes: ciphertext) + return iv + Data(ciphertext) } /// - Note: Sync. Don't call from the main thread. @@ -28,11 +28,11 @@ enum EncryptionUtilities { #endif } let x25519PublicKey = Data(hex: hexEncodedX25519PublicKey) - let ephemeralKeyPair = Curve25519.generateKeyPair()! - let ephemeralSharedSecret = Curve25519.generateSharedSecret(fromPublicKey: x25519PublicKey, andKeyPair: ephemeralKeyPair)! + let ephemeralKeyPair = Curve25519.generateKeyPair() + let ephemeralSharedSecret = try! Curve25519.generateSharedSecret(fromPublicKey: x25519PublicKey, privateKey: ephemeralKeyPair.privateKey) let salt = "LOKI" let symmetricKey = try HMAC(key: salt.bytes, variant: .sha256).authenticate(ephemeralSharedSecret.bytes) let ciphertext = try encrypt(plaintext, usingAESGCMWithSymmetricKey: Data(bytes: symmetricKey)) - return (ciphertext, Data(bytes: symmetricKey), ephemeralKeyPair.publicKey()) + return (ciphertext, Data(bytes: symmetricKey), ephemeralKeyPair.publicKey) } } diff --git a/SignalUtilitiesKit/LKDeviceLinkMessage.m b/SignalUtilitiesKit/LKDeviceLinkMessage.m index 1b1cc7219..e1836a1fd 100644 --- a/SignalUtilitiesKit/LKDeviceLinkMessage.m +++ b/SignalUtilitiesKit/LKDeviceLinkMessage.m @@ -5,8 +5,8 @@ #import "ProtoUtils.h" #import "SSKEnvironment.h" #import "SignalRecipient.h" -#import -#import +#import +#import #import @implementation LKDeviceLinkMessage diff --git a/SignalUtilitiesKit/LKUnlinkDeviceMessage.m b/SignalUtilitiesKit/LKUnlinkDeviceMessage.m index ed941cf07..d1a7594e6 100644 --- a/SignalUtilitiesKit/LKUnlinkDeviceMessage.m +++ b/SignalUtilitiesKit/LKUnlinkDeviceMessage.m @@ -1,5 +1,5 @@ #import "LKUnlinkDeviceMessage.h" -#import +#import #import @implementation LKUnlinkDeviceMessage diff --git a/SignalUtilitiesKit/Meta/SignalUtilitiesKit-Prefix.pch b/SignalUtilitiesKit/Meta/SignalUtilitiesKit-Prefix.pch index 7e8e09ea6..13ba93736 100644 --- a/SignalUtilitiesKit/Meta/SignalUtilitiesKit-Prefix.pch +++ b/SignalUtilitiesKit/Meta/SignalUtilitiesKit-Prefix.pch @@ -9,6 +9,7 @@ #import @import PureLayout; + @import SignalCoreKit; @import SessionMessagingKit; @import SessionProtocolKit; diff --git a/SignalUtilitiesKit/NSString+SSK.h b/SignalUtilitiesKit/NSString+SSK.h index f1669bf85..5f105ba13 100644 --- a/SignalUtilitiesKit/NSString+SSK.h +++ b/SignalUtilitiesKit/NSString+SSK.h @@ -2,8 +2,6 @@ // Copyright (c) 2018 Open Whisper Systems. All rights reserved. // -#import - NS_ASSUME_NONNULL_BEGIN @interface NSString (SSK) diff --git a/SignalUtilitiesKit/OWSAnalytics.m b/SignalUtilitiesKit/OWSAnalytics.m index f1edcc830..c5d896915 100755 --- a/SignalUtilitiesKit/OWSAnalytics.m +++ b/SignalUtilitiesKit/OWSAnalytics.m @@ -11,7 +11,7 @@ #import "YapDatabaseConnection+OWS.h" #import #import -#import +#import #import #import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/OWSAttachmentDownloads.m b/SignalUtilitiesKit/OWSAttachmentDownloads.m index c3b5454c1..c93b7ad25 100644 --- a/SignalUtilitiesKit/OWSAttachmentDownloads.m +++ b/SignalUtilitiesKit/OWSAttachmentDownloads.m @@ -22,7 +22,7 @@ #import "TSNetworkManager.h" #import "TSThread.h" #import -#import +#import #import #import diff --git a/SignalUtilitiesKit/OWSBatchMessageProcessor.m b/SignalUtilitiesKit/OWSBatchMessageProcessor.m index 19ecd4c2b..7b26795eb 100644 --- a/SignalUtilitiesKit/OWSBatchMessageProcessor.m +++ b/SignalUtilitiesKit/OWSBatchMessageProcessor.m @@ -18,7 +18,7 @@ #import "TSDatabaseView.h" #import "TSErrorMessage.h" #import "TSYapDatabaseObject.h" -#import +#import #import #import #import diff --git a/SignalUtilitiesKit/OWSChunkedOutputStream.m b/SignalUtilitiesKit/OWSChunkedOutputStream.m index 5c4f92ddc..10baabf8a 100644 --- a/SignalUtilitiesKit/OWSChunkedOutputStream.m +++ b/SignalUtilitiesKit/OWSChunkedOutputStream.m @@ -3,7 +3,7 @@ // #import "OWSChunkedOutputStream.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSContactDiscoveryOperation.swift b/SignalUtilitiesKit/OWSContactDiscoveryOperation.swift index 5b8cdef54..8a71e43a7 100644 --- a/SignalUtilitiesKit/OWSContactDiscoveryOperation.swift +++ b/SignalUtilitiesKit/OWSContactDiscoveryOperation.swift @@ -3,6 +3,7 @@ // import Foundation +import SignalCoreKit @objc(OWSLegacyContactDiscoveryOperation) public class LegacyContactDiscoveryBatchOperation: OWSOperation { @@ -314,6 +315,7 @@ class CDSBatchOperation: OWSOperation { let addressPlainTextData = try type(of: self).encodePhoneNumbers(recipientIds: recipientIds) guard let encryptionResult = Cryptography.encryptAESGCM(plainTextData: addressPlainTextData, + initializationVector: Cryptography.generateRandomBytes(kAESGCM256_DefaultIVLength), additionalAuthenticatedData: remoteAttestation.requestId, key: remoteAttestation.keys.clientKey) else { diff --git a/SignalUtilitiesKit/OWSContactsOutputStream.m b/SignalUtilitiesKit/OWSContactsOutputStream.m index 9515a0b29..722641472 100644 --- a/SignalUtilitiesKit/OWSContactsOutputStream.m +++ b/SignalUtilitiesKit/OWSContactsOutputStream.m @@ -12,8 +12,8 @@ #import "OWSRecipientIdentity.h" #import "SignalAccount.h" #import "TSContactThread.h" -#import -#import +#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSDevice.m b/SignalUtilitiesKit/OWSDevice.m index 7de3032ab..869b2bf9c 100644 --- a/SignalUtilitiesKit/OWSDevice.m +++ b/SignalUtilitiesKit/OWSDevice.m @@ -12,7 +12,7 @@ #import "YapDatabaseConnection.h" #import "YapDatabaseTransaction.h" #import -#import +#import #import #import diff --git a/SignalUtilitiesKit/OWSDisappearingMessagesConfigurationMessage.m b/SignalUtilitiesKit/OWSDisappearingMessagesConfigurationMessage.m index e6d539971..e787fc317 100644 --- a/SignalUtilitiesKit/OWSDisappearingMessagesConfigurationMessage.m +++ b/SignalUtilitiesKit/OWSDisappearingMessagesConfigurationMessage.m @@ -4,7 +4,7 @@ #import "OWSDisappearingMessagesConfigurationMessage.h" #import "OWSDisappearingMessagesConfiguration.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSDisappearingMessagesFinder.m b/SignalUtilitiesKit/OWSDisappearingMessagesFinder.m index a319141e7..7cb3b7d47 100644 --- a/SignalUtilitiesKit/OWSDisappearingMessagesFinder.m +++ b/SignalUtilitiesKit/OWSDisappearingMessagesFinder.m @@ -8,7 +8,7 @@ #import "TSMessage.h" #import "TSOutgoingMessage.h" #import "TSThread.h" -#import +#import #import #import #import diff --git a/SignalUtilitiesKit/OWSDisappearingMessagesJob.m b/SignalUtilitiesKit/OWSDisappearingMessagesJob.m index ef29f762e..0a3dec690 100644 --- a/SignalUtilitiesKit/OWSDisappearingMessagesJob.m +++ b/SignalUtilitiesKit/OWSDisappearingMessagesJob.m @@ -16,7 +16,7 @@ #import "TSIncomingMessage.h" #import "TSMessage.h" #import "TSThread.h" -#import +#import #import #import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/OWSDynamicOutgoingMessage.m b/SignalUtilitiesKit/OWSDynamicOutgoingMessage.m index f869b8830..00d212809 100644 --- a/SignalUtilitiesKit/OWSDynamicOutgoingMessage.m +++ b/SignalUtilitiesKit/OWSDynamicOutgoingMessage.m @@ -3,7 +3,7 @@ // #import "OWSDynamicOutgoingMessage.h" -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSEndSessionMessage.m b/SignalUtilitiesKit/OWSEndSessionMessage.m index c0bd12c5d..287bda45d 100644 --- a/SignalUtilitiesKit/OWSEndSessionMessage.m +++ b/SignalUtilitiesKit/OWSEndSessionMessage.m @@ -5,7 +5,7 @@ #import "OWSEndSessionMessage.h" #import "OWSPrimaryStorage+Loki.h" #import "SignalRecipient.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSFingerprint.m b/SignalUtilitiesKit/OWSFingerprint.m index b7ea82fff..20c777d31 100644 --- a/SignalUtilitiesKit/OWSFingerprint.m +++ b/SignalUtilitiesKit/OWSFingerprint.m @@ -6,7 +6,7 @@ #import "OWSError.h" #import #import -#import +#import #import #import diff --git a/SignalUtilitiesKit/OWSIdentityManager.m b/SignalUtilitiesKit/OWSIdentityManager.m index 6838f90b1..c8cff86fb 100644 --- a/SignalUtilitiesKit/OWSIdentityManager.m +++ b/SignalUtilitiesKit/OWSIdentityManager.m @@ -25,7 +25,7 @@ #import "YapDatabaseTransaction+OWS.h" #import #import -#import +#import #import #import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/OWSIncompleteCallsJob.m b/SignalUtilitiesKit/OWSIncompleteCallsJob.m index 3d09fa723..9a4e1755d 100644 --- a/SignalUtilitiesKit/OWSIncompleteCallsJob.m +++ b/SignalUtilitiesKit/OWSIncompleteCallsJob.m @@ -6,7 +6,7 @@ #import "AppContext.h" #import "OWSPrimaryStorage.h" #import "TSCall.h" -#import +#import #import #import #import diff --git a/SignalUtilitiesKit/OWSMessageDecrypter.m b/SignalUtilitiesKit/OWSMessageDecrypter.m index c2a7910ac..968fadf57 100644 --- a/SignalUtilitiesKit/OWSMessageDecrypter.m +++ b/SignalUtilitiesKit/OWSMessageDecrypter.m @@ -24,9 +24,9 @@ #import #import #import -#import -#import -#import +#import +#import +#import #import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/OWSMessageManager.m b/SignalUtilitiesKit/OWSMessageManager.m index 17bf623ef..d839a282e 100644 --- a/SignalUtilitiesKit/OWSMessageManager.m +++ b/SignalUtilitiesKit/OWSMessageManager.m @@ -50,8 +50,8 @@ #import "TSNetworkManager.h" #import "TSOutgoingMessage.h" #import "TSQuotedMessage.h" -#import -#import +#import +#import #import #import #import diff --git a/SignalUtilitiesKit/OWSMessageReceiver.m b/SignalUtilitiesKit/OWSMessageReceiver.m index 4d9b9a208..ecf4abba6 100644 --- a/SignalUtilitiesKit/OWSMessageReceiver.m +++ b/SignalUtilitiesKit/OWSMessageReceiver.m @@ -19,13 +19,13 @@ #import "TSDatabaseView.h" #import "TSErrorMessage.h" #import "TSYapDatabaseObject.h" -#import +#import #import #import #import #import #import -#import +#import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/OWSMessageSender.m b/SignalUtilitiesKit/OWSMessageSender.m index 3d6f990c3..a0f889952 100644 --- a/SignalUtilitiesKit/OWSMessageSender.m +++ b/SignalUtilitiesKit/OWSMessageSender.m @@ -53,10 +53,10 @@ #import #import #import -#import -#import -#import -#import +#import +#import +#import +#import #import #import #import diff --git a/SignalUtilitiesKit/OWSMessageServiceParams.m b/SignalUtilitiesKit/OWSMessageServiceParams.m index 6719a6551..d7a0cbf12 100644 --- a/SignalUtilitiesKit/OWSMessageServiceParams.m +++ b/SignalUtilitiesKit/OWSMessageServiceParams.m @@ -4,7 +4,7 @@ #import "OWSMessageServiceParams.h" #import "TSConstants.h" -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSOutgoingCallMessage.m b/SignalUtilitiesKit/OWSOutgoingCallMessage.m index a7a2f6478..7a59d300f 100644 --- a/SignalUtilitiesKit/OWSOutgoingCallMessage.m +++ b/SignalUtilitiesKit/OWSOutgoingCallMessage.m @@ -6,7 +6,7 @@ #import "ProtoUtils.h" #import "SignalRecipient.h" #import "TSContactThread.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSOutgoingNullMessage.m b/SignalUtilitiesKit/OWSOutgoingNullMessage.m index 876757b17..9e27356fc 100644 --- a/SignalUtilitiesKit/OWSOutgoingNullMessage.m +++ b/SignalUtilitiesKit/OWSOutgoingNullMessage.m @@ -5,8 +5,8 @@ #import "OWSOutgoingNullMessage.h" #import "OWSVerificationStateSyncMessage.h" #import "TSContactThread.h" -#import -#import +#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSOutgoingSyncMessage.m b/SignalUtilitiesKit/OWSOutgoingSyncMessage.m index 38a643e96..a45c7b457 100644 --- a/SignalUtilitiesKit/OWSOutgoingSyncMessage.m +++ b/SignalUtilitiesKit/OWSOutgoingSyncMessage.m @@ -4,8 +4,8 @@ #import "OWSOutgoingSyncMessage.h" #import "ProtoUtils.h" -#import -#import +#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSPrimaryStorage+Loki.m b/SignalUtilitiesKit/OWSPrimaryStorage+Loki.m index 0f2d09569..68f65931f 100644 --- a/SignalUtilitiesKit/OWSPrimaryStorage+Loki.m +++ b/SignalUtilitiesKit/OWSPrimaryStorage+Loki.m @@ -122,7 +122,7 @@ while (failureCount < 3) { @try { PreKeyBundle *preKeyBundle = [self generatePreKeyBundleForContact:hexEncodedPublicKey forceClean:forceClean]; - if (![Ed25519 verifySignature:preKeyBundle.signedPreKeySignature + if (![Ed25519 throws_verifySignature:preKeyBundle.signedPreKeySignature publicKey:preKeyBundle.identityKey.throws_removeKeyType data:preKeyBundle.signedPreKeyPublic]) { @throw [NSException exceptionWithName:InvalidKeyException reason:@"KeyIsNotValidlySigned" userInfo:nil]; diff --git a/SignalUtilitiesKit/OWSPrimaryStorage+SignedPreKeyStore.m b/SignalUtilitiesKit/OWSPrimaryStorage+SignedPreKeyStore.m index 541257db3..468a05f50 100644 --- a/SignalUtilitiesKit/OWSPrimaryStorage+SignedPreKeyStore.m +++ b/SignalUtilitiesKit/OWSPrimaryStorage+SignedPreKeyStore.m @@ -31,7 +31,7 @@ NSString *const OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId = @"currentSigne OWSAssert(identityKeyPair); @try { - NSData *signature = [Ed25519 sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair]; + NSData *signature = [Ed25519 throws_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair]; return [[SignedPreKeyRecord alloc] initWithId:preKeyId keyPair:keyPair signature:signature diff --git a/SignalUtilitiesKit/OWSProvisioningCipher.m b/SignalUtilitiesKit/OWSProvisioningCipher.m index b63074b85..e5d85bfcb 100644 --- a/SignalUtilitiesKit/OWSProvisioningCipher.m +++ b/SignalUtilitiesKit/OWSProvisioningCipher.m @@ -68,7 +68,7 @@ NS_ASSUME_NONNULL_BEGIN - (nullable NSData *)throws_encryptWithData:(NSData *)dataToEncrypt { NSData *sharedSecret = - [Curve25519 generateSharedSecretFromPublicKey:self.theirPublicKey andKeyPair:self.ourKeyPair]; + [Curve25519 throws_generateSharedSecretFromPublicKey:self.theirPublicKey privateKey:self.ourKeyPair.privateKey]; NSData *infoData = [@"TextSecure Provisioning Message" dataUsingEncoding:NSASCIIStringEncoding]; NSData *nullSalt = [[NSMutableData dataWithLength:32] copy]; diff --git a/SignalUtilitiesKit/OWSReceiptsForSenderMessage.m b/SignalUtilitiesKit/OWSReceiptsForSenderMessage.m index 1466e8ee6..0aca5877a 100644 --- a/SignalUtilitiesKit/OWSReceiptsForSenderMessage.m +++ b/SignalUtilitiesKit/OWSReceiptsForSenderMessage.m @@ -4,7 +4,7 @@ #import "OWSReceiptsForSenderMessage.h" #import "SignalRecipient.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSRecipientIdentity.m b/SignalUtilitiesKit/OWSRecipientIdentity.m index d37b99527..eaabf61b6 100644 --- a/SignalUtilitiesKit/OWSRecipientIdentity.m +++ b/SignalUtilitiesKit/OWSRecipientIdentity.m @@ -6,7 +6,7 @@ #import "OWSIdentityManager.h" #import "OWSPrimaryStorage+SessionStore.h" #import "OWSPrimaryStorage.h" -#import +#import #import #import diff --git a/SignalUtilitiesKit/OWSRequestFactory.m b/SignalUtilitiesKit/OWSRequestFactory.m index 3fbdd6fe8..182fd35b8 100644 --- a/SignalUtilitiesKit/OWSRequestFactory.m +++ b/SignalUtilitiesKit/OWSRequestFactory.m @@ -13,8 +13,8 @@ #import #import #import -#import -#import +#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSStorage.m b/SignalUtilitiesKit/OWSStorage.m index 8cb00e925..f1df7a394 100644 --- a/SignalUtilitiesKit/OWSStorage.m +++ b/SignalUtilitiesKit/OWSStorage.m @@ -11,8 +11,8 @@ #import "OWSPrimaryStorage.h" #import "OWSStorage+Subclass.h" #import "TSAttachmentStream.h" -#import -#import +#import +#import #import #import #import diff --git a/SignalUtilitiesKit/OWSSyncContactsMessage.m b/SignalUtilitiesKit/OWSSyncContactsMessage.m index 58e979984..8747fd31e 100644 --- a/SignalUtilitiesKit/OWSSyncContactsMessage.m +++ b/SignalUtilitiesKit/OWSSyncContactsMessage.m @@ -15,7 +15,7 @@ #import "TSAttachment.h" #import "TSAttachmentStream.h" #import "TSContactThread.h" -#import +#import #import #import "OWSPrimaryStorage.h" diff --git a/SignalUtilitiesKit/OWSSyncGroupsMessage.m b/SignalUtilitiesKit/OWSSyncGroupsMessage.m index c3def4420..f4440de44 100644 --- a/SignalUtilitiesKit/OWSSyncGroupsMessage.m +++ b/SignalUtilitiesKit/OWSSyncGroupsMessage.m @@ -9,7 +9,7 @@ #import "TSContactThread.h" #import "TSGroupModel.h" #import "TSGroupThread.h" -#import +#import #import #import "OWSPrimaryStorage.h" diff --git a/SignalUtilitiesKit/OWSSyncGroupsRequestMessage.m b/SignalUtilitiesKit/OWSSyncGroupsRequestMessage.m index 29740759a..41962325c 100644 --- a/SignalUtilitiesKit/OWSSyncGroupsRequestMessage.m +++ b/SignalUtilitiesKit/OWSSyncGroupsRequestMessage.m @@ -3,7 +3,7 @@ // #import "OWSSyncGroupsRequestMessage.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSUploadOperation.m b/SignalUtilitiesKit/OWSUploadOperation.m index 4b0d7b382..cc4160c1a 100644 --- a/SignalUtilitiesKit/OWSUploadOperation.m +++ b/SignalUtilitiesKit/OWSUploadOperation.m @@ -13,7 +13,7 @@ #import "SSKEnvironment.h" #import "TSAttachmentStream.h" #import "TSNetworkManager.h" -#import +#import #import #import @@ -117,7 +117,7 @@ static const CGFloat kAttachmentUploadProgressTheta = 0.001f; NSData *encryptionKey; NSData *digest; NSData *_Nullable encryptedAttachmentData = - [Cryptography encryptAttachmentData:attachmentData outKey:&encryptionKey outDigest:&digest]; + [Cryptography encryptAttachmentData:attachmentData shouldPad:YES outKey:&encryptionKey outDigest:&digest]; if (!encryptedAttachmentData) { OWSFailDebug(@"could not encrypt attachment data."); error = OWSErrorMakeFailedToSendOutgoingMessageError(); diff --git a/SignalUtilitiesKit/OWSVerificationStateSyncMessage.m b/SignalUtilitiesKit/OWSVerificationStateSyncMessage.m index 7b84416b9..db224c086 100644 --- a/SignalUtilitiesKit/OWSVerificationStateSyncMessage.m +++ b/SignalUtilitiesKit/OWSVerificationStateSyncMessage.m @@ -4,7 +4,7 @@ #import "OWSVerificationStateSyncMessage.h" #import "OWSIdentityManager.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/OWSWebSocket.m b/SignalUtilitiesKit/OWSWebSocket.m index 3be2ee136..d7bea5bca 100644 --- a/SignalUtilitiesKit/OWSWebSocket.m +++ b/SignalUtilitiesKit/OWSWebSocket.m @@ -20,8 +20,8 @@ #import "TSConstants.h" #import "TSErrorMessage.h" #import "TSRequest.h" -#import -#import +#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/ProtoUtils.m b/SignalUtilitiesKit/ProtoUtils.m index e02d6917f..a48a0cd0c 100644 --- a/SignalUtilitiesKit/ProtoUtils.m +++ b/SignalUtilitiesKit/ProtoUtils.m @@ -6,7 +6,7 @@ #import "ProfileManagerProtocol.h" #import "SSKEnvironment.h" #import "TSThread.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/SSKAsserts.h b/SignalUtilitiesKit/SSKAsserts.h index d8006e370..93e5d2a73 100755 --- a/SignalUtilitiesKit/SSKAsserts.h +++ b/SignalUtilitiesKit/SSKAsserts.h @@ -3,8 +3,8 @@ // #import -#import -#import +#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/SharedSenderKeysImplementation.swift b/SignalUtilitiesKit/SharedSenderKeysImplementation.swift index 4a3371bf4..6f5f8bc0d 100644 --- a/SignalUtilitiesKit/SharedSenderKeysImplementation.swift +++ b/SignalUtilitiesKit/SharedSenderKeysImplementation.swift @@ -215,6 +215,6 @@ public final class SharedSenderKeysImplementation : NSObject { public func getKeyPair(forGroupWithPublicKey groupPublicKey: String) -> ECKeyPair { let privateKey = Storage.getClosedGroupPrivateKey(for: groupPublicKey)! - return ECKeyPair(publicKey: Data(hex: groupPublicKey.removing05PrefixIfNeeded()), privateKey: Data(hex: privateKey)) + return try! ECKeyPair(publicKeyData: Data(hex: groupPublicKey.removing05PrefixIfNeeded()), privateKeyData: Data(hex: privateKey)) } } diff --git a/SignalUtilitiesKit/SignalKeyingStorage.m b/SignalUtilitiesKit/SignalKeyingStorage.m index ace4559ae..c8ad2a659 100644 --- a/SignalUtilitiesKit/SignalKeyingStorage.m +++ b/SignalUtilitiesKit/SignalKeyingStorage.m @@ -5,7 +5,7 @@ #import "SignalKeyingStorage.h" #import #import -#import +#import #define SignalKeyingCollection @"SignalKeyingCollection" diff --git a/SignalUtilitiesKit/TSAccountManager.m b/SignalUtilitiesKit/TSAccountManager.m index c8f512e18..724cdfbad 100644 --- a/SignalUtilitiesKit/TSAccountManager.m +++ b/SignalUtilitiesKit/TSAccountManager.m @@ -18,8 +18,8 @@ #import "YapDatabaseTransaction+OWS.h" #import #import -#import -#import +#import +#import #import #import #import "SSKAsserts.h" diff --git a/SignalUtilitiesKit/TSAttachmentStream.m b/SignalUtilitiesKit/TSAttachmentStream.m index f3c797b74..c42735d87 100644 --- a/SignalUtilitiesKit/TSAttachmentStream.m +++ b/SignalUtilitiesKit/TSAttachmentStream.m @@ -8,7 +8,7 @@ #import "OWSFileSystem.h" #import "TSAttachmentPointer.h" #import -#import +#import #import #import diff --git a/SignalUtilitiesKit/TSErrorMessage.m b/SignalUtilitiesKit/TSErrorMessage.m index 9ac1072d2..12b29e7b7 100644 --- a/SignalUtilitiesKit/TSErrorMessage.m +++ b/SignalUtilitiesKit/TSErrorMessage.m @@ -8,7 +8,7 @@ #import "SSKEnvironment.h" #import "TSContactThread.h" #import "TSErrorMessage_privateConstructor.h" -#import +#import #import #import diff --git a/SignalUtilitiesKit/TSGroupThread.m b/SignalUtilitiesKit/TSGroupThread.m index 903b75b31..938e198bf 100644 --- a/SignalUtilitiesKit/TSGroupThread.m +++ b/SignalUtilitiesKit/TSGroupThread.m @@ -4,7 +4,7 @@ #import "TSGroupThread.h" #import "TSAttachmentStream.h" -#import +#import #import #import #import diff --git a/SignalUtilitiesKit/TSInteraction.m b/SignalUtilitiesKit/TSInteraction.m index 725d169ca..1a94cdba6 100644 --- a/SignalUtilitiesKit/TSInteraction.m +++ b/SignalUtilitiesKit/TSInteraction.m @@ -6,7 +6,7 @@ #import "TSDatabaseSecondaryIndexes.h" #import "TSThread.h" #import "TSGroupThread.h" -#import +#import #import NS_ASSUME_NONNULL_BEGIN diff --git a/SignalUtilitiesKit/TSMessage.m b/SignalUtilitiesKit/TSMessage.m index 6e00eb845..e582b2080 100644 --- a/SignalUtilitiesKit/TSMessage.m +++ b/SignalUtilitiesKit/TSMessage.m @@ -12,7 +12,7 @@ #import "TSAttachmentStream.h" #import "TSQuotedMessage.h" #import "TSThread.h" -#import +#import #import #import #import diff --git a/SignalUtilitiesKit/TSOutgoingMessage.m b/SignalUtilitiesKit/TSOutgoingMessage.m index b8c0bcc7f..b30739593 100644 --- a/SignalUtilitiesKit/TSOutgoingMessage.m +++ b/SignalUtilitiesKit/TSOutgoingMessage.m @@ -19,7 +19,7 @@ #import "TSContactThread.h" #import "TSGroupThread.h" #import "TSQuotedMessage.h" -#import +#import #import #import #import diff --git a/SignalUtilitiesKit/TSPreKeyManager.m b/SignalUtilitiesKit/TSPreKeyManager.m index 0a5da54c2..acf3e5905 100644 --- a/SignalUtilitiesKit/TSPreKeyManager.m +++ b/SignalUtilitiesKit/TSPreKeyManager.m @@ -10,7 +10,7 @@ #import "SSKEnvironment.h" #import "TSNetworkManager.h" #import "TSStorageHeaders.h" -#import +#import #import #import diff --git a/SignalUtilitiesKit/TSThread.m b/SignalUtilitiesKit/TSThread.m index 428987440..3ef2ecaf7 100644 --- a/SignalUtilitiesKit/TSThread.m +++ b/SignalUtilitiesKit/TSThread.m @@ -15,8 +15,8 @@ #import "TSInteraction.h" #import "TSInvalidIdentityKeyReceivingErrorMessage.h" #import "TSOutgoingMessage.h" -#import -#import +#import +#import #import #import diff --git a/SignalUtilitiesKit/UIColor+OWS.m b/SignalUtilitiesKit/UIColor+OWS.m index b935233fd..da53d6d1b 100644 --- a/SignalUtilitiesKit/UIColor+OWS.m +++ b/SignalUtilitiesKit/UIColor+OWS.m @@ -4,7 +4,7 @@ #import "UIColor+OWS.h" #import "OWSMath.h" -#import +#import NS_ASSUME_NONNULL_BEGIN