NCEndToEndEncryption.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. //
  2. // NCEndToEndEncryption.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/09/17.
  6. // Copyright © 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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/OpenSSL.h>
  29. #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);
  30. #define IV_DELIMITER_ENCODED_OLD @"fA=="
  31. #define IV_DELIMITER_ENCODED @"|"
  32. #define PBKDF2_INTERACTION_COUNT 1024
  33. #define PBKDF2_KEY_LENGTH 256
  34. //#define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  35. #define ASYMMETRIC_STRING_TEST @"Nextcloud a safe home for all your data"
  36. #define fileNameCertificate @"cert.pem"
  37. #define fileNameCSR @"csr.pem"
  38. #define fileNamePrivateKey @"privateKey.pem"
  39. #define fileNamePubliceKey @"publicKey.pem"
  40. #define AES_KEY_128_LENGTH 16
  41. #define AES_KEY_256_LENGTH 32
  42. #define AES_IVEC_LENGTH 16
  43. #define AES_GCM_TAG_LENGTH 16
  44. #define AES_SALT_LENGTH 40
  45. @interface NCEndToEndEncryption ()
  46. {
  47. NSData *_privateKeyData;
  48. NSData *_publicKeyData;
  49. NSData *_csrData;
  50. }
  51. @end
  52. @implementation NCEndToEndEncryption
  53. //Singleton
  54. + (instancetype)sharedManager {
  55. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  56. static dispatch_once_t onceToken;
  57. dispatch_once(&onceToken, ^{
  58. NCEndToEndEncryption = [self new];
  59. });
  60. return NCEndToEndEncryption;
  61. }
  62. #
  63. #pragma mark - Generate Certificate X509 - CSR - Private Key
  64. #
  65. - (BOOL)generateCertificateX509WithUserId:(NSString *)userId directory:(NSString *)directory
  66. {
  67. OPENSSL_init();
  68. int ret;
  69. EVP_PKEY * pkey;
  70. pkey = EVP_PKEY_new();
  71. RSA * rsa;
  72. BIGNUM *bignum = BN_new();
  73. ret = BN_set_word(bignum, RSA_F4);
  74. if (ret != 1) {
  75. return NO;
  76. }
  77. rsa = RSA_new();
  78. ret = RSA_generate_key_ex(rsa, 2048, bignum, NULL);
  79. if (ret != 1) {
  80. return NO;
  81. }
  82. EVP_PKEY_assign_RSA(pkey, rsa);
  83. X509 * x509;
  84. x509 = X509_new();
  85. ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
  86. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  87. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  88. X509_gmtime_adj(X509_get_notBefore(x509), notBefore);
  89. X509_gmtime_adj(X509_get_notAfter(x509), notAfter);
  90. X509_set_pubkey(x509, pkey);
  91. X509_NAME * name;
  92. name = X509_get_subject_name(x509);
  93. // Now to add the subject name fields to the certificate
  94. // I use a macro here to make it cleaner.
  95. const unsigned char *cUserId = (const unsigned char *) [userId cStringUsingEncoding:NSUTF8StringEncoding];
  96. // Common Name = UserID.
  97. addName("CN", cUserId);
  98. // The organizational unit for the cert. Usually this is a department.
  99. addName("OU", "Certificate Authority");
  100. // The organization of the cert.
  101. addName("O", "Nextcloud");
  102. // The city of the organization.
  103. addName("L", "Vicenza");
  104. // The state/province of the organization.
  105. addName("S", "Italy");
  106. // The country (ISO 3166) of the organization
  107. addName("C", "IT");
  108. X509_set_issuer_name(x509, name);
  109. /*
  110. for (SANObject * san in self.options.sans) {
  111. if (!san.value || san.value.length <= 0) {
  112. continue;
  113. }
  114. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  115. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  116. NSLog(@"Add subjectAltName %@", value);
  117. X509_EXTENSION * extension = NULL;
  118. ASN1_STRING * asnValue = ASN1_STRING_new();
  119. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  120. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  121. X509_add_ext(x509, extension, -1);
  122. }
  123. */
  124. // Specify the encryption algorithm of the signature.
  125. // SHA256 should suit your needs.
  126. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  127. return NO;
  128. }
  129. X509_print_fp(stdout, x509);
  130. // Extract CSR, publicKey, privateKey
  131. int len;
  132. char *keyBytes;
  133. // CSR
  134. BIO *csrBIO = BIO_new(BIO_s_mem());
  135. X509_REQ *certReq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  136. PEM_write_bio_X509_REQ(csrBIO, certReq);
  137. len = BIO_pending(csrBIO);
  138. keyBytes = malloc(len);
  139. BIO_read(csrBIO, keyBytes, len);
  140. _csrData = [NSData dataWithBytes:keyBytes length:len];
  141. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding]);
  142. // PublicKey
  143. BIO *publicKeyBIO = BIO_new(BIO_s_mem());
  144. PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
  145. len = BIO_pending(publicKeyBIO);
  146. keyBytes = malloc(len);
  147. BIO_read(publicKeyBIO, keyBytes, len);
  148. _publicKeyData = [NSData dataWithBytes:keyBytes length:len];
  149. self.generatedPublicKey = [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding];
  150. NSLog(@"[LOG] \n%@", self.generatedPublicKey);
  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. self.generatedPrivateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  159. NSLog(@"[LOG] \n%@", self.generatedPrivateKey);
  160. if(keyBytes)
  161. free(keyBytes);
  162. #ifdef DEBUG
  163. // Save to disk [DEBUG MODE]
  164. [self saveToDiskPEMWithCert:x509 key:pkey directory:directory];
  165. #endif
  166. return YES;
  167. }
  168. - (NSString *)extractPublicKeyFromCertificate:(NSString *)pemCertificate
  169. {
  170. const char *ptrCert = [pemCertificate cStringUsingEncoding:NSUTF8StringEncoding];
  171. BIO *certBio = BIO_new(BIO_s_mem());
  172. BIO_write(certBio, ptrCert,(unsigned int)strlen(ptrCert));
  173. X509 *certX509 = PEM_read_bio_X509(certBio, NULL, NULL, NULL);
  174. if (!certX509) {
  175. fprintf(stderr, "unable to parse certificate in memory\n");
  176. return nil;
  177. }
  178. EVP_PKEY *pkey;
  179. pkey = X509_get_pubkey(certX509);
  180. NSString *publicKey = [self pubKeyToString:pkey];
  181. EVP_PKEY_free(pkey);
  182. BIO_free(certBio);
  183. X509_free(certX509);
  184. NSLog(@"[LOG] \n%@", publicKey);
  185. return publicKey;
  186. }
  187. - (BOOL)saveToDiskPEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory
  188. {
  189. FILE *f;
  190. // Certificate
  191. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCertificate];
  192. f = fopen([certificatePath fileSystemRepresentation], "wb");
  193. if (PEM_write_X509(f, x509) < 0) {
  194. // Error writing to disk.
  195. fclose(f);
  196. return NO;
  197. }
  198. NSLog(@"[LOG] Saved cert to %@", certificatePath);
  199. fclose(f);
  200. // PublicKey
  201. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePubliceKey];
  202. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  203. if (PEM_write_PUBKEY(f, pkey) < 0) {
  204. // Error
  205. fclose(f);
  206. return NO;
  207. }
  208. NSLog(@"[LOG] Saved publicKey to %@", publicKeyPath);
  209. fclose(f);
  210. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  211. // file using the password and cipher you provide.
  212. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  213. // PrivateKey
  214. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePrivateKey];
  215. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  216. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  217. // Error
  218. fclose(f);
  219. return NO;
  220. }
  221. NSLog(@"[LOG] Saved privatekey to %@", privatekeyPath);
  222. fclose(f);
  223. // CSR Request sha256
  224. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCSR];
  225. f = fopen([csrPath fileSystemRepresentation], "wb");
  226. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  227. if (PEM_write_X509_REQ(f, certreq) < 0) {
  228. // Error
  229. fclose(f);
  230. return NO;
  231. }
  232. NSLog(@"[LOG] Saved csr to %@", csrPath);
  233. fclose(f);
  234. return YES;
  235. }
  236. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory finished:(void (^)(NSError *))finished
  237. {
  238. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  239. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  240. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directory];
  241. FILE *f = fopen([path fileSystemRepresentation], "wb");
  242. if (i2d_PKCS12_fp(f, p12) != 1) {
  243. fclose(f);
  244. return NO;
  245. }
  246. NSLog(@"[LOG] Saved p12 to %@", path);
  247. fclose(f);
  248. return YES;
  249. }
  250. #
  251. #pragma mark - Create CSR & Encrypt/Decrypt Private Key
  252. #
  253. - (NSString *)createCSR:(NSString *)userId directory:(NSString *)directory
  254. {
  255. // Create Certificate, if do not exists
  256. if (!_csrData) {
  257. if (![self generateCertificateX509WithUserId:userId directory:directory])
  258. return nil;
  259. }
  260. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  261. return csr;
  262. }
  263. - (NSString *)encryptPrivateKey:(NSString *)userId directory:(NSString *)directory passphrase:(NSString *)passphrase privateKey:(NSString **)privateKey
  264. {
  265. NSMutableData *privateKeyCipherData = [NSMutableData new];
  266. if (!_privateKeyData) {
  267. if (![self generateCertificateX509WithUserId:userId directory:directory])
  268. return nil;
  269. }
  270. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  271. NSData *saltData = [self generateSalt:AES_SALT_LENGTH];
  272. // Remove all whitespaces from passphrase
  273. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  274. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  275. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  276. NSData *tagData = [NSData new];
  277. NSString *pkEncoded = [_privateKeyData base64EncodedStringWithOptions:0];
  278. NSData *pkEncodedData = [pkEncoded dataUsingEncoding:NSUTF8StringEncoding];
  279. BOOL result = [self encryptData:pkEncodedData cipherData:&privateKeyCipherData keyData:keyData keyLen:AES_KEY_256_LENGTH ivData:ivData tagData:&tagData];
  280. if (result && privateKeyCipherData) {
  281. NSString *privateKeyCipherBase64 = [privateKeyCipherData base64EncodedStringWithOptions:0];
  282. NSString *initVectorBase64 = [ivData base64EncodedStringWithOptions:0];
  283. NSString *saltBase64 = [saltData base64EncodedStringWithOptions:0];
  284. NSString *privateKeyCipherWithInitVectorBase64 = [NSString stringWithFormat:@"%@%@%@%@%@", privateKeyCipherBase64, IV_DELIMITER_ENCODED, initVectorBase64, IV_DELIMITER_ENCODED, saltBase64];
  285. *privateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  286. return privateKeyCipherWithInitVectorBase64;
  287. } else {
  288. return nil;
  289. }
  290. }
  291. - (NSData *)decryptPrivateKey:(NSString *)privateKeyCipher passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey
  292. {
  293. NSMutableData *privateKeyData = [NSMutableData new];
  294. // Key (data)
  295. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  296. // Split
  297. NSArray *privateKeyCipherArray = [privateKeyCipher componentsSeparatedByString:IV_DELIMITER_ENCODED];
  298. if (privateKeyCipherArray.count != 3) {
  299. privateKeyCipherArray = [privateKeyCipher componentsSeparatedByString:IV_DELIMITER_ENCODED_OLD];
  300. if (privateKeyCipherArray.count != 3) {
  301. return nil;
  302. }
  303. }
  304. NSData *privateKeyCipherData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[0] options:0];
  305. NSString *tagBase64 = [privateKeyCipher substringWithRange:NSMakeRange([(NSString *)privateKeyCipherArray[0] length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  306. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tagBase64 options:0];
  307. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[1] options:0];
  308. NSData *saltData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[2] options:0];
  309. // Remove TAG
  310. privateKeyCipherData = [privateKeyCipherData subdataWithRange:NSMakeRange(0, privateKeyCipherData.length - AES_GCM_TAG_LENGTH)];
  311. // Remove all whitespaces from passphrase
  312. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  313. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  314. BOOL result = [self decryptData:privateKeyCipherData plainData:&privateKeyData keyData:keyData keyLen:AES_KEY_256_LENGTH ivData:ivData tagData:tagData];
  315. if (result && privateKeyData) {
  316. return privateKeyData;
  317. }
  318. return nil;
  319. }
  320. #
  321. #pragma mark - Encrypt / Decrypt file material
  322. #
  323. - (NSString *)encryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  324. {
  325. NSMutableData *cipherData;
  326. NSData *tagData = [NSData new];
  327. NSData *data = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  328. NSString *data64 = [data base64EncodedStringWithOptions:0];
  329. data = [data64 dataUsingEncoding:NSUTF8StringEncoding];
  330. // Key
  331. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  332. // IV
  333. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  334. BOOL result = [self encryptData:data cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  335. if (cipherData != nil && result) {
  336. NSString *cipherBase64 = [cipherData base64EncodedStringWithOptions:0];
  337. NSString *ivBase64 = [ivData base64EncodedStringWithOptions:0];
  338. NSString *encryptedJson = [NSString stringWithFormat:@"%@%@%@", cipherBase64, IV_DELIMITER_ENCODED, ivBase64];
  339. return encryptedJson;
  340. }
  341. return nil;
  342. }
  343. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  344. {
  345. NSMutableData *plainData;
  346. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  347. if (range.location == NSNotFound) {
  348. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  349. if (range.location == NSNotFound) {
  350. return nil;
  351. }
  352. }
  353. // Cipher
  354. NSString *cipher = [encrypted substringToIndex:(range.location)];
  355. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  356. // Key
  357. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  358. // IV
  359. NSString *iv = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  360. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:iv options:0];
  361. // TAG
  362. NSString *tag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  363. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tag options:0];
  364. // REMOVE TAG
  365. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  366. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  367. if (plainData != nil && result) {
  368. return plainData;
  369. }
  370. return nil;
  371. }
  372. #
  373. #pragma mark - Encrypt / Decrypt file
  374. #
  375. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  376. {
  377. NSMutableData *cipherData;
  378. NSData *tagData;
  379. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directory, fileName]];
  380. if (plainData == nil)
  381. return false;
  382. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  383. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  384. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  385. if (cipherData != nil && result) {
  386. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] atomically:YES];
  387. *key = [keyData base64EncodedStringWithOptions:0];
  388. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  389. *authenticationTag = [tagData base64EncodedStringWithOptions:0];
  390. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  391. return false;
  392. } else {
  393. return true;
  394. }
  395. }
  396. return false;
  397. }
  398. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  399. {
  400. NSMutableData *plainData;
  401. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  402. if (cipherData == nil)
  403. return false;
  404. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  405. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  406. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  407. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  408. if (plainData != nil && result) {
  409. [plainData writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] atomically:YES];
  410. return true;
  411. }
  412. return false;
  413. }
  414. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  415. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  416. #
  417. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  418. #
  419. #
  420. #pragma mark - Encrypt/Decrypt asymmetric
  421. #
  422. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey privateKey:(NSString *)privateKey
  423. {
  424. EVP_PKEY *key = NULL;
  425. int status = 0;
  426. if (publicKey != nil) {
  427. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  428. // Extract real publicKey
  429. BIO *bio = BIO_new_mem_buf(pKey, -1);
  430. if (!bio)
  431. return nil;
  432. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  433. if (!x509)
  434. return nil;
  435. key = X509_get_pubkey(x509);
  436. if (!key)
  437. return nil;
  438. }
  439. if (privateKey != nil) {
  440. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  441. BIO *bio = BIO_new_mem_buf(pKey, -1);
  442. if (!bio)
  443. return nil;
  444. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  445. if (!key)
  446. return nil;
  447. }
  448. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  449. if (!ctx)
  450. return nil;
  451. status = EVP_PKEY_encrypt_init(ctx);
  452. if (status <= 0)
  453. return nil;
  454. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  455. if (status <= 0)
  456. return nil;
  457. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  458. if (status <= 0)
  459. return nil;
  460. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  461. if (status <= 0)
  462. return nil;
  463. unsigned long outLen = 0;
  464. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  465. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  466. if (status <= 0 || outLen == 0)
  467. return nil;
  468. unsigned char *out = (unsigned char *) malloc(outLen);
  469. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  470. if (status <= 0)
  471. return nil;
  472. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  473. if (out)
  474. free(out);
  475. return outData;
  476. }
  477. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  478. {
  479. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  480. int status = 0;
  481. BIO *bio = BIO_new_mem_buf(pKey, -1);
  482. if (!bio)
  483. return nil;
  484. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  485. if (!key)
  486. return nil;
  487. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  488. if (!ctx)
  489. return nil;
  490. status = EVP_PKEY_decrypt_init(ctx);
  491. if (status <= 0)
  492. return nil;
  493. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  494. if (status <= 0)
  495. return nil;
  496. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  497. if (status <= 0)
  498. return nil;
  499. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  500. if (status <= 0)
  501. return nil;
  502. unsigned long outLen = 0;
  503. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  504. if (status <= 0 || outLen == 0)
  505. return nil;
  506. unsigned char *out = (unsigned char *) malloc(outLen);
  507. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  508. if (status <= 0)
  509. return nil;
  510. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  511. //NSString *out64 = [outData base64EncodedStringWithOptions:0];
  512. if (out)
  513. free(out);
  514. return outData;
  515. }
  516. #
  517. #pragma mark - AES/GCM/NoPadding
  518. #
  519. // Encryption using GCM mode
  520. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData **)tagData
  521. {
  522. int status = 0;
  523. int len = 0;
  524. // set up key
  525. len = keyLen;
  526. unsigned char cKey[len];
  527. bzero(cKey, sizeof(cKey));
  528. [keyData getBytes:cKey length:len];
  529. // set up ivec
  530. len = AES_IVEC_LENGTH;
  531. unsigned char cIV[len];
  532. bzero(cIV, sizeof(cIV));
  533. [ivData getBytes:cIV length:len];
  534. // set up tag
  535. len = AES_GCM_TAG_LENGTH;
  536. unsigned char cTag[len];
  537. bzero(cTag, sizeof(cTag));
  538. // Create and initialise the context
  539. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  540. if (!ctx)
  541. return NO;
  542. // Initialise the encryption operation
  543. if (keyLen == AES_KEY_128_LENGTH)
  544. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  545. else if (keyLen == AES_KEY_256_LENGTH)
  546. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  547. if (status <= 0)
  548. return NO;
  549. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  550. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  551. if (status <= 0)
  552. return NO;
  553. // Initialise key and IV
  554. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  555. if (status <= 0)
  556. return NO;
  557. // Provide the message to be encrypted, and obtain the encrypted output
  558. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  559. unsigned char * cCipher = [*cipherData mutableBytes];
  560. int cCipherLen = 0;
  561. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plainData bytes], (int)[plainData length]);
  562. if (status <= 0)
  563. return NO;
  564. // Finalise the encryption
  565. len = cCipherLen;
  566. status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  567. if (status <= 0)
  568. return NO;
  569. // Get the tag
  570. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  571. *tagData = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  572. // Append TAG
  573. [*cipherData appendData:*tagData];
  574. // Free
  575. EVP_CIPHER_CTX_free(ctx);
  576. return status; // OpenSSL uses 1 for success
  577. }
  578. // Decryption using GCM mode
  579. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData *)tagData
  580. {
  581. int status = 0;
  582. int len = 0;
  583. // set up key
  584. len = keyLen;
  585. unsigned char cKey[len];
  586. bzero(cKey, sizeof(cKey));
  587. [keyData getBytes:cKey length:len];
  588. // set up ivec
  589. len = (int)[ivData length];
  590. unsigned char cIV[len];
  591. bzero(cIV, sizeof(cIV));
  592. [ivData getBytes:cIV length:len];
  593. // set up tag
  594. len = (int)[tagData length];;
  595. unsigned char cTag[len];
  596. bzero(cTag, sizeof(cTag));
  597. [tagData getBytes:cTag length:len];
  598. // Create and initialise the context
  599. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  600. if (!ctx)
  601. return NO;
  602. // Initialise the decryption operation
  603. if (keyLen == AES_KEY_128_LENGTH)
  604. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  605. else if (keyLen == AES_KEY_256_LENGTH)
  606. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  607. if (status <= 0)
  608. return NO;
  609. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  610. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  611. if (status <= 0)
  612. return NO;
  613. // Initialise key and IV
  614. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  615. if (status <= 0)
  616. return NO;
  617. // Provide the message to be decrypted, and obtain the plaintext output
  618. *plainData = [NSMutableData dataWithLength:([cipherData length])];
  619. int cPlainLen = 0;
  620. unsigned char * cPlain = [*plainData mutableBytes];
  621. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipherData bytes], (int)([cipherData length]));
  622. if (status <= 0)
  623. return NO;
  624. // Tag is the last 16 bytes
  625. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  626. if (status <= 0)
  627. return NO;
  628. // Finalise the encryption
  629. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  630. // Free
  631. EVP_CIPHER_CTX_free(ctx);
  632. return status; // OpenSSL uses 1 for success
  633. }
  634. #
  635. #pragma mark - Utility
  636. #
  637. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  638. {
  639. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  640. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  641. *key = [keyData base64EncodedStringWithOptions:0];
  642. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  643. }
  644. - (NSString *)createSHA512:(NSString *)string
  645. {
  646. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  647. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  648. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  649. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  650. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  651. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  652. [output appendFormat:@"%02x", digest[i]];
  653. return output;
  654. }
  655. - (NSData *)generateIV:(int)length
  656. {
  657. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  658. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  659. return ivData;
  660. }
  661. - (NSData *)generateSalt:(int)length
  662. {
  663. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  664. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  665. return saltData;
  666. }
  667. - (NSData *)generateKey:(int)length
  668. {
  669. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  670. unsigned char *pKeyData = [keyData mutableBytes];
  671. RAND_bytes(pKeyData, length);
  672. return keyData;
  673. }
  674. - (NSData *)generateKey
  675. {
  676. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  677. unsigned char *pKeyData = [keyData mutableBytes];
  678. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  679. return keyData;
  680. }
  681. - (NSString *)getSHA1:(NSString *)input
  682. {
  683. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  684. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  685. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  686. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  687. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  688. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  689. [output appendFormat:@"%02x", digest[i]];
  690. return output;
  691. }
  692. - (NSData *)hashValueMD5OfData:(NSData *)data
  693. {
  694. MD5_CTX md5Ctx;
  695. unsigned char hashValue[MD5_DIGEST_LENGTH];
  696. if(!MD5_Init(&md5Ctx)) {
  697. return nil;
  698. }
  699. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  700. return nil;
  701. }
  702. if (!MD5_Final(hashValue, &md5Ctx)) {
  703. return nil;
  704. }
  705. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  706. }
  707. - (NSString *)hexadecimalString:(NSData *)input
  708. {
  709. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  710. if (!dataBuffer) {
  711. return [NSString string];
  712. }
  713. NSUInteger dataLength = [input length];
  714. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  715. for (int i = 0; i < dataLength; ++i) {
  716. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  717. }
  718. return [NSString stringWithString:hexString];
  719. }
  720. - (NSString *)derToPemPrivateKey:(NSString *)input
  721. {
  722. NSInteger substringLength = 65;
  723. NSMutableString *result = [NSMutableString stringWithString: input];
  724. for(long i=substringLength;i<=input.length;i++) {
  725. [result insertString: @"\n" atIndex: i];
  726. i+=substringLength;
  727. }
  728. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  729. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  730. return result;
  731. }
  732. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  733. {
  734. char *buf[256];
  735. FILE *pFile;
  736. NSString *pkey_string;
  737. pFile = fmemopen(buf, sizeof(buf), "w");
  738. PEM_write_PUBKEY(pFile,pubkey);
  739. fputc('\0', pFile);
  740. fclose(pFile);
  741. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  742. return pkey_string;
  743. }
  744. @end