NCPushNotificationsUtils.m 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. #import "NCPushNotificationsUtils.h"
  6. #import <openssl/rsa.h>
  7. #import <openssl/pem.h>
  8. #import <openssl/bio.h>
  9. #import <openssl/bn.h>
  10. #import <openssl/sha.h>
  11. #import <openssl/err.h>
  12. @implementation NCPushNotificationsUtils
  13. + (NSString *)decryptPushNotification:(NSString *)message withDevicePrivateKey:(NSData *)privateKey
  14. {
  15. NSString *privateKeyString = [[NSString alloc] initWithData:privateKey encoding:NSUTF8StringEncoding];
  16. NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:message options:0];
  17. char *privKey = (char *)[privateKeyString UTF8String];
  18. // Get Device Private Key from PEM
  19. BIO *bio = BIO_new(BIO_s_mem());
  20. BIO_write(bio, privKey, (int)strlen(privKey));
  21. EVP_PKEY* pkey = 0;
  22. PEM_read_bio_PrivateKey(bio, &pkey, 0, 0);
  23. RSA* rsa = EVP_PKEY_get1_RSA(pkey);
  24. // Decrypt the message
  25. unsigned char *decrypted = (unsigned char *) malloc(4096);
  26. int decrypted_length = RSA_private_decrypt((int)[decodedData length], [decodedData bytes], decrypted, rsa, RSA_PKCS1_PADDING);
  27. if(decrypted_length == -1) {
  28. char buffer[500];
  29. ERR_error_string(ERR_get_error(), buffer);
  30. NSLog(@"%@",[NSString stringWithUTF8String:buffer]);
  31. return nil;
  32. }
  33. NSString *decryptString = [[NSString alloc] initWithBytes:decrypted length:decrypted_length encoding:NSUTF8StringEncoding];
  34. if (decrypted)
  35. free(decrypted);
  36. free(bio);
  37. free(rsa);
  38. return decryptString;
  39. }
  40. @end