NCEndToEndEncryption.m 34 KB

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