NCEndToEndEncryption.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. //
  2. // NCEndToEndEncryption.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/09/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "NCEndToEndEncryption.h"
  24. #import "NCBridgeSwift.h"
  25. #import "CCUtility.h"
  26. #import <CommonCrypto/CommonDigest.h>
  27. #import <CommonCrypto/CommonKeyDerivation.h>
  28. #import <openssl/x509.h>
  29. #import <openssl/bio.h>
  30. #import <openssl/err.h>
  31. #import <openssl/pem.h>
  32. #import <openssl/rsa.h>
  33. #import <openssl/pkcs12.h>
  34. #import <openssl/ssl.h>
  35. #import <openssl/err.h>
  36. #import <openssl/bn.h>
  37. #import <openssl/md5.h>
  38. #define addName(field, value) X509_NAME_add_entry_by_txt(name, field, MBSTRING_ASC, (unsigned char *)value, -1, -1, 0); NSLog(@"%s: %s", field, value);
  39. #define IV_DELIMITER_ENCODED @"fA==" // "|" base64 encoded
  40. #define PBKDF2_INTERACTION_COUNT 1024
  41. #define PBKDF2_KEY_LENGTH 256
  42. #define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  43. #define RSA_CIPHER RSA_PKCS1_PADDING
  44. #define ASYMMETRIC_STRING_TEST @"Nextcloud a safe home for all your data"
  45. #define fileNameCertificate @"cert.pem"
  46. #define fileNameCSR @"csr.pem"
  47. #define fileNamePrivateKey @"privateKey.pem"
  48. #define fileNamePubliceKey @"publicKey.pem"
  49. #define AES_KEY_LENGTH 16
  50. #define AES_IVEC_LENGTH 16
  51. #define AES_GCM_TAG_LENGTH 16
  52. @interface NCEndToEndEncryption ()
  53. {
  54. NSData *_privateKeyData;
  55. NSData *_publicKeyData;
  56. NSData *_csrData;
  57. }
  58. @end
  59. @implementation NCEndToEndEncryption
  60. //Singleton
  61. + (instancetype)sharedManager {
  62. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  63. static dispatch_once_t onceToken;
  64. dispatch_once(&onceToken, ^{
  65. NCEndToEndEncryption = [self new];
  66. });
  67. return NCEndToEndEncryption;
  68. }
  69. #
  70. #pragma mark - Generate Certificate X509 - CSR - Private Key
  71. #
  72. - (BOOL)generateCertificateX509WithUserID:(NSString *)userID directoryUser:(NSString *)directoryUser
  73. {
  74. OPENSSL_init_ssl(0, NULL);
  75. OPENSSL_init_crypto(0, NULL);
  76. X509 *x509;
  77. x509 = X509_new();
  78. EVP_PKEY *pkey;
  79. NSError *keyError;
  80. pkey = [self generateRSAKey:&keyError];
  81. if (keyError) {
  82. return NO;
  83. }
  84. X509_set_pubkey(x509, pkey);
  85. EVP_PKEY_free(pkey);
  86. // Set Serial Number
  87. ASN1_INTEGER_set(X509_get_serialNumber(x509), 123);
  88. // Set Valididity Date Range
  89. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  90. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  91. X509_gmtime_adj((ASN1_TIME *)X509_get0_notBefore(x509), notBefore);
  92. X509_gmtime_adj((ASN1_TIME *)X509_get0_notAfter(x509), notAfter);
  93. X509_NAME *name = X509_get_subject_name(x509);
  94. // Now to add the subject name fields to the certificate
  95. // I use a macro here to make it cleaner.
  96. const unsigned char *cUserID = (const unsigned char *) [userID cStringUsingEncoding:NSUTF8StringEncoding];
  97. // Common Name = UserID.
  98. addName("CN", cUserID);
  99. // The organizational unit for the cert. Usually this is a department.
  100. addName("OU", "Certificate Authority");
  101. // The organization of the cert.
  102. addName("O", "Nextcloud");
  103. // The city of the organization.
  104. addName("L", "Vicenza");
  105. // The state/province of the organization.
  106. addName("S", "Italy");
  107. // The country (ISO 3166) of the organization
  108. addName("C", "IT");
  109. X509_set_issuer_name(x509, name);
  110. /*
  111. for (SANObject * san in self.options.sans) {
  112. if (!san.value || san.value.length <= 0) {
  113. continue;
  114. }
  115. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  116. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  117. NSLog(@"Add subjectAltName %@", value);
  118. X509_EXTENSION * extension = NULL;
  119. ASN1_STRING * asnValue = ASN1_STRING_new();
  120. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  121. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  122. X509_add_ext(x509, extension, -1);
  123. }
  124. */
  125. // Specify the encryption algorithm of the signature.
  126. // SHA256 should suit your needs.
  127. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  128. return NO;
  129. }
  130. X509_print_fp(stdout, x509);
  131. // Extract CSR, publicKey, privateKey
  132. int len;
  133. char *keyBytes;
  134. // CSR
  135. BIO *csrBIO = BIO_new(BIO_s_mem());
  136. X509_REQ *certReq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  137. PEM_write_bio_X509_REQ(csrBIO, certReq);
  138. len = BIO_pending(csrBIO);
  139. keyBytes = malloc(len);
  140. BIO_read(csrBIO, keyBytes, len);
  141. _csrData = [NSData dataWithBytes:keyBytes length:len];
  142. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding]);
  143. // PublicKey
  144. BIO *publicKeyBIO = BIO_new(BIO_s_mem());
  145. PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
  146. len = BIO_pending(publicKeyBIO);
  147. keyBytes = malloc(len);
  148. BIO_read(publicKeyBIO, keyBytes, len);
  149. _publicKeyData = [NSData dataWithBytes:keyBytes length:len];
  150. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding]);
  151. // PrivateKey
  152. BIO *privateKeyBIO = BIO_new(BIO_s_mem());
  153. PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
  154. len = BIO_pending(privateKeyBIO);
  155. keyBytes = malloc(len);
  156. BIO_read(privateKeyBIO, keyBytes, len);
  157. _privateKeyData = [NSData dataWithBytes:keyBytes length:len];
  158. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding]);
  159. if(keyBytes)
  160. free(keyBytes);
  161. #ifdef DEBUG
  162. // Save to disk [DEBUG MODE]
  163. [self saveToDiskPEMWithCert:x509 key:pkey directoryUser:directoryUser];
  164. #endif
  165. return YES;
  166. }
  167. - (EVP_PKEY *)generateRSAKey:(NSError **)error
  168. {
  169. EVP_PKEY *pkey = EVP_PKEY_new();
  170. if (!pkey) {
  171. return NULL;
  172. }
  173. BIGNUM *bigNumber = BN_new();
  174. int exponent = RSA_F4;
  175. RSA *rsa = RSA_new();
  176. if (BN_set_word(bigNumber, exponent) < 0) {
  177. goto cleanup;
  178. }
  179. if (RSA_generate_key_ex(rsa, 2048, bigNumber, NULL) < 0) {
  180. goto cleanup;
  181. }
  182. if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
  183. goto cleanup;
  184. }
  185. cleanup:
  186. RSA_free(rsa);
  187. BN_free(bigNumber);
  188. return pkey;
  189. }
  190. - (BOOL)saveToDiskPEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser
  191. {
  192. FILE *f;
  193. // Certificate
  194. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCertificate];
  195. f = fopen([certificatePath fileSystemRepresentation], "wb");
  196. if (PEM_write_X509(f, x509) < 0) {
  197. // Error writing to disk.
  198. fclose(f);
  199. return NO;
  200. }
  201. NSLog(@"[LOG] Saved cert to %@", certificatePath);
  202. fclose(f);
  203. // PublicKey
  204. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePubliceKey];
  205. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  206. if (PEM_write_PUBKEY(f, pkey) < 0) {
  207. // Error
  208. fclose(f);
  209. return NO;
  210. }
  211. NSLog(@"[LOG] Saved publicKey to %@", publicKeyPath);
  212. fclose(f);
  213. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  214. // file using the password and cipher you provide.
  215. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  216. // PrivateKey
  217. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey];
  218. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  219. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  220. // Error
  221. fclose(f);
  222. return NO;
  223. }
  224. NSLog(@"[LOG] Saved privatekey to %@", privatekeyPath);
  225. fclose(f);
  226. // CSR Request sha256
  227. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR];
  228. f = fopen([csrPath fileSystemRepresentation], "wb");
  229. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  230. if (PEM_write_X509_REQ(f, certreq) < 0) {
  231. // Error
  232. fclose(f);
  233. return NO;
  234. }
  235. NSLog(@"[LOG] Saved csr to %@", csrPath);
  236. fclose(f);
  237. return YES;
  238. }
  239. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  240. {
  241. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  242. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  243. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directoryUser];
  244. FILE *f = fopen([path fileSystemRepresentation], "wb");
  245. if (i2d_PKCS12_fp(f, p12) != 1) {
  246. fclose(f);
  247. return NO;
  248. }
  249. NSLog(@"[LOG] Saved p12 to %@", path);
  250. fclose(f);
  251. return YES;
  252. }
  253. #
  254. #pragma mark - Register client for Server with exists Key pair
  255. #
  256. - (NSString *)createCSR:(NSString *)userID directoryUser:(NSString *)directoryUser
  257. {
  258. // Create Certificate, if do not exists
  259. if (!_csrData) {
  260. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  261. return nil;
  262. }
  263. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  264. return csr;
  265. }
  266. - (NSString *)encryptPrivateKey:(NSString *)userID directoryUser: (NSString *)directoryUser passphrase:(NSString *)passphrase
  267. {
  268. NSMutableData *privateKeyCipherData = [NSMutableData new];
  269. if (!_privateKeyData) {
  270. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  271. return nil;
  272. }
  273. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  274. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  275. // Remove all whitespaces from passphrase
  276. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  277. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  278. NSData *initVectorData = [self generateIV:AES_IVEC_LENGTH];
  279. BOOL result = [self encryptData:_privateKeyData cipherData:&privateKeyCipherData keyData:keyData initVectorData:initVectorData tagData:nil];
  280. if (result && privateKeyCipherData) {
  281. NSString *privateKeyCipherBase64;
  282. NSString *initVectorBase64;
  283. NSString *privateKeyCipherWithInitVectorBase64;
  284. privateKeyCipherBase64 = [privateKeyCipherData base64EncodedStringWithOptions:0];
  285. initVectorBase64 = [initVectorData base64EncodedStringWithOptions:0];
  286. privateKeyCipherWithInitVectorBase64 = [NSString stringWithFormat:@"%@%@%@", privateKeyCipherBase64, IV_DELIMITER_ENCODED, initVectorBase64];
  287. return privateKeyCipherWithInitVectorBase64;
  288. } else {
  289. return nil;
  290. }
  291. }
  292. #
  293. #pragma mark - No key pair exists on the server
  294. #
  295. - (NSString *)decryptPrivateKey:(NSString *)privateKeyCipher passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey
  296. {
  297. NSMutableData *privateKeyData = [NSMutableData new];
  298. // Key (data)
  299. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  300. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  301. // Remove all whitespaces from passphrase
  302. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  303. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  304. // Split
  305. NSRange range = [privateKeyCipher rangeOfString:IV_DELIMITER_ENCODED];
  306. NSInteger idx = range.location + range.length;
  307. // PrivateKey
  308. NSString *privateKeyCipherBase64 = [privateKeyCipher substringToIndex:range.location];
  309. NSData *privateKeyCipherData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherBase64 options:0];
  310. // Init Vector
  311. NSString *initVectorBase64 = [privateKeyCipher substringFromIndex:idx];
  312. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:initVectorBase64 options:0];
  313. BOOL result = [self decryptData:privateKeyCipherData plainData:&privateKeyData keyData:keyData initVectorData:initVectorData tag:nil];
  314. if (result && privateKeyData) {
  315. NSString *privateKey = [[NSString alloc] initWithData:privateKeyData encoding:NSUTF8StringEncoding];
  316. NSData *encryptData = [self encryptAsymmetricString:ASYMMETRIC_STRING_TEST publicKey:publicKey];
  317. if (!encryptData)
  318. return nil;
  319. NSString *decryptString = [self decryptAsymmetricData:encryptData privateKey:privateKey];
  320. if (decryptString && [decryptString isEqualToString:ASYMMETRIC_STRING_TEST])
  321. return privateKey;
  322. else
  323. return nil;
  324. } else {
  325. return nil;
  326. }
  327. }
  328. #
  329. #pragma mark - Asymmetric Encrypt/Decrypt String
  330. #
  331. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey
  332. {
  333. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  334. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  335. // Extract real publicKey
  336. BIO *bio = BIO_new_mem_buf(pKey, -1);
  337. if (bio == NULL)
  338. return nil;
  339. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  340. if (x509 == NULL)
  341. return nil;
  342. EVP_PKEY *evpkey = X509_get_pubkey(x509);
  343. if (evpkey == NULL)
  344. return nil;
  345. RSA *rsa = EVP_PKEY_get1_RSA(evpkey);
  346. if (rsa == NULL)
  347. return nil;
  348. unsigned char *encrypted = (unsigned char *) malloc(4096);
  349. int encrypted_length = RSA_public_encrypt((int)[plainData length], [plainData bytes], encrypted, rsa, RSA_CIPHER);
  350. if(encrypted_length == -1) {
  351. char buffer[500];
  352. ERR_error_string(ERR_get_error(), buffer);
  353. NSLog(@"[LOG] %@",[NSString stringWithUTF8String:buffer]);
  354. return nil;
  355. }
  356. NSData *encryptData = [[NSData alloc] initWithBytes:encrypted length:encrypted_length];
  357. if (encrypted)
  358. free(encrypted);
  359. free(rsa);
  360. return encryptData;
  361. }
  362. - (NSString *)decryptAsymmetricData:(NSData *)chiperData privateKey:(NSString *)privateKey
  363. {
  364. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  365. BIO *bio = BIO_new_mem_buf(pKey, -1);
  366. if (bio == NULL)
  367. return nil;
  368. RSA *rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, 0, NULL);
  369. if (rsa == NULL)
  370. return nil;
  371. unsigned char *decrypted = (unsigned char *) malloc(4096);
  372. int decrypted_length = RSA_private_decrypt((int)[chiperData length], [chiperData bytes], decrypted, rsa, RSA_CIPHER);
  373. if(decrypted_length == -1) {
  374. char buffer[500];
  375. ERR_error_string(ERR_get_error(), buffer);
  376. NSLog(@"[LOG] %@",[NSString stringWithUTF8String:buffer]);
  377. return nil;
  378. }
  379. NSString *decryptString = [[NSString alloc] initWithBytes:decrypted length:decrypted_length encoding:NSUTF8StringEncoding];
  380. if (decrypted)
  381. free(decrypted);
  382. free(bio);
  383. free(rsa);
  384. return decryptString;
  385. }
  386. #
  387. #pragma mark - Encrypt/Decrypt Files AES/GCM/NoPadding as cipher (128 bit key size)
  388. #
  389. - (void)encryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  390. {
  391. NSMutableData *cipherData;
  392. NSData *tagData;
  393. NSString* authenticationTag;
  394. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  395. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  396. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  397. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData initVectorData:initVectorData tagData:&tagData];
  398. if (cipherData != nil && result) {
  399. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"encrypted.dms"] atomically:YES];
  400. authenticationTag = [tagData base64EncodedStringWithOptions:0];
  401. }
  402. }
  403. - (void)decryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  404. {
  405. NSMutableData *plainData;
  406. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  407. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  408. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  409. NSString *tag = @"PboI9tqHHX3QeAA22PIu4w==";
  410. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData initVectorData:initVectorData tag:tag];
  411. if (plainData != nil && result) {
  412. [plainData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"decrypted"] atomically:YES];
  413. }
  414. }
  415. // encrypt data AES 256 GCM NOPADING
  416. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tagData:(NSData **)tagData
  417. {
  418. int status = 0;
  419. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  420. // set up key
  421. unsigned char cKey[AES_KEY_LENGTH];
  422. bzero(cKey, sizeof(cKey));
  423. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  424. // set up ivec
  425. unsigned char cIv[AES_IVEC_LENGTH];
  426. bzero(cIv, AES_IVEC_LENGTH);
  427. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  428. // set up to Encrypt AES 128 GCM
  429. int numberOfBytes = 0;
  430. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  431. EVP_EncryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  432. // set the key and ivec
  433. EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  434. EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  435. unsigned char * ctBytes = [*cipherData mutableBytes];
  436. EVP_EncryptUpdate (ctx, ctBytes, &numberOfBytes, [plainData bytes], (int)[plainData length]);
  437. status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  438. if (status && tagData) {
  439. unsigned char cTag[AES_GCM_TAG_LENGTH];
  440. bzero(cTag, AES_GCM_TAG_LENGTH);
  441. status = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_LENGTH, cTag);
  442. *tagData = [NSData dataWithBytes:cTag length:AES_GCM_TAG_LENGTH];
  443. }
  444. EVP_CIPHER_CTX_free(ctx);
  445. return (status != 0); // OpenSSL uses 1 for success
  446. }
  447. // decrypt data AES 256 GCM NOPADING
  448. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tag:(NSString *)tag
  449. {
  450. int status = 0;
  451. int numberOfBytes = 0;
  452. *plainData = [NSMutableData dataWithLength:[cipherData length]];
  453. // set up key
  454. unsigned char cKey[AES_KEY_LENGTH];
  455. bzero(cKey, sizeof(cKey));
  456. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  457. // set up ivec
  458. unsigned char cIv[AES_IVEC_LENGTH];
  459. bzero(cIv, AES_IVEC_LENGTH);
  460. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  461. // set up tag
  462. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tag options:0];
  463. unsigned char cTag[AES_GCM_TAG_LENGTH];
  464. bzero(cTag, AES_GCM_TAG_LENGTH);
  465. [tagData getBytes:cTag length:AES_GCM_TAG_LENGTH];
  466. /* verify tag if exists*/
  467. if (tag) {
  468. NSData *authenticationTagData = [cipherData subdataWithRange:NSMakeRange([cipherData length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  469. NSString *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  470. if (![authenticationTag isEqualToString:tag])
  471. return NO;
  472. }
  473. /* Create and initialise the context */
  474. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  475. /* Initialise the decryption operation. */
  476. status = EVP_DecryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  477. if (! status)
  478. return NO;
  479. /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
  480. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  481. if (! status)
  482. return NO;
  483. /* Initialise key and IV */
  484. status = EVP_DecryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  485. if (! status)
  486. return NO;
  487. /* Provide the message to be decrypted, and obtain the plaintext output. */
  488. unsigned char * ctBytes = [*plainData mutableBytes];
  489. status = EVP_DecryptUpdate (ctx, ctBytes, &numberOfBytes, [cipherData bytes], (int)[cipherData length]);
  490. if (! status)
  491. return NO;
  492. /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
  493. //status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_LENGTH, cTag);
  494. //if (!status)
  495. // return NO;
  496. /* Finalise the decryption. A positive return value indicates success, anything else is a failure - the plaintext is n trustworthy. */
  497. //status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  498. //if (!status)
  499. // return NO;
  500. // Without test Final
  501. EVP_DecryptFinal_ex (ctx, NULL, &numberOfBytes);
  502. EVP_CIPHER_CTX_free(ctx);
  503. return status; // OpenSSL uses 1 for success
  504. }
  505. #
  506. #pragma mark - Utility
  507. #
  508. - (NSString *)createSHA512:(NSString *)string
  509. {
  510. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  511. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  512. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  513. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  514. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  515. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  516. [output appendFormat:@"%02x", digest[i]];
  517. return output;
  518. }
  519. - (NSData *)generateIV:(int)ivLength
  520. {
  521. NSMutableData *ivData = [NSMutableData dataWithLength:ivLength];
  522. (void)SecRandomCopyBytes(kSecRandomDefault, ivLength, ivData.mutableBytes);
  523. return ivData;
  524. }
  525. - (NSString *)getMD5:(NSString *)input
  526. {
  527. // Create pointer to the string as UTF8
  528. const char *ptr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  529. // Create byte array of unsigned chars
  530. unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  531. // Create 16 byte MD5 hash value, store in buffer
  532. CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
  533. // Convert MD5 value in the buffer to NSString of hex values
  534. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  535. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  536. [output appendFormat:@"%02x",md5Buffer[i]];
  537. return output;
  538. }
  539. - (NSString *)getSHA1:(NSString *)input
  540. {
  541. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  542. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  543. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  544. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  545. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  546. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  547. [output appendFormat:@"%02x", digest[i]];
  548. return output;
  549. }
  550. - (NSData *)hashValueMD5OfData:(NSData *)data
  551. {
  552. MD5_CTX md5Ctx;
  553. unsigned char hashValue[MD5_DIGEST_LENGTH];
  554. if(!MD5_Init(&md5Ctx)) {
  555. return nil;
  556. }
  557. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  558. return nil;
  559. }
  560. if (!MD5_Final(hashValue, &md5Ctx)) {
  561. return nil;
  562. }
  563. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  564. }
  565. - (NSString *)hexadecimalString:(NSData *)input
  566. {
  567. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  568. if (!dataBuffer) {
  569. return [NSString string];
  570. }
  571. NSUInteger dataLength = [input length];
  572. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  573. for (int i = 0; i < dataLength; ++i) {
  574. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  575. }
  576. return [NSString stringWithString:hexString];
  577. }
  578. - (NSString *)stringRemoveBeginEnd:(NSString *)input
  579. {
  580. input = [input stringByReplacingOccurrencesOfString:@"-----BEGIN CERTIFICATE-----\n" withString:@""];
  581. input = [input stringByReplacingOccurrencesOfString:@"\n-----END CERTIFICATE-----" withString:@""];
  582. input = [input stringByReplacingOccurrencesOfString:@"-----BEGIN PRIVATE KEY-----\n" withString:@""];
  583. input = [input stringByReplacingOccurrencesOfString:@"\n-----END PRIVATE KEY-----" withString:@""];
  584. return input;
  585. }
  586. @end