PushPayloadDecryptor.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2018-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "AppGroup.h"
  21. #import "NaClCrypto.h"
  22. #import "PushPayloadDecryptor.h"
  23. #ifdef DEBUG
  24. static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
  25. #else
  26. static const DDLogLevel ddLogLevel = DDLogLevelWarning;
  27. #endif
  28. @implementation PushPayloadDecryptor
  29. + (NSDictionary*)decryptPushPayload:(NSDictionary*)encryptedPayload {
  30. NSString *box_base64 = [encryptedPayload objectForKey:@"box"];
  31. NSString *nonce_base64 = [encryptedPayload objectForKey:@"nonce"];
  32. if (!box_base64 || !nonce_base64)
  33. return encryptedPayload; // not really encrypted
  34. NSData *box = [[NSData alloc] initWithBase64EncodedString:box_base64 options:0];
  35. NSData *nonce = [[NSData alloc] initWithBase64EncodedString:nonce_base64 options:0];
  36. NSData *payloadJson = [[NaClCrypto sharedCrypto] symmetricDecryptData:box withKey:[self pushEncryptionKey] nonce:nonce];
  37. if (payloadJson == nil) {
  38. DDLogError(@"Cannot decrypt push payload: %@", encryptedPayload);
  39. return encryptedPayload;
  40. }
  41. NSError *error = nil;
  42. NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:payloadJson options:0 error:&error];
  43. if (payload == nil) {
  44. DDLogError(@"Error parsing decrypted JSON payload: %@, %@", error, [error userInfo]);
  45. return encryptedPayload;
  46. }
  47. return payload;
  48. }
  49. + (NSData*)pushEncryptionKey {
  50. // Generate new push encryption key if necessary
  51. NSData *pushEncryptionKey = [[AppGroup userDefaults] objectForKey:kPushNotificationEncryptionKey];
  52. if (pushEncryptionKey == nil) {
  53. pushEncryptionKey = [[NaClCrypto sharedCrypto] randomBytes:kNaClCryptoSymmKeySize];
  54. [[AppGroup userDefaults] setObject:pushEncryptionKey forKey:kPushNotificationEncryptionKey];
  55. }
  56. return pushEncryptionKey;
  57. }
  58. @end