NCEndToEndEncryption.m 35 KB

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