NCEndToEndEncryption.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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 Encrypted Json
  322. #
  323. - (NSString *)encryptEncryptedJson:(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 *)decryptEncryptedJson:(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. - (void)encryptkey:(NSString **)key initializationVector:(NSString **)initializationVector
  376. {
  377. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  378. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  379. *key = [keyData base64EncodedStringWithOptions:0];
  380. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  381. }
  382. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  383. {
  384. NSMutableData *cipherData;
  385. NSData *tagData;
  386. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directory, fileName]];
  387. if (plainData == nil)
  388. return false;
  389. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  390. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  391. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  392. if (cipherData != nil && result) {
  393. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] atomically:YES];
  394. *key = [keyData base64EncodedStringWithOptions:0];
  395. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  396. *authenticationTag = [tagData base64EncodedStringWithOptions:0];
  397. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  398. return false;
  399. } else {
  400. return true;
  401. }
  402. }
  403. return false;
  404. }
  405. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  406. {
  407. NSMutableData *plainData;
  408. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView: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 getDirectoryProviderStorageOcId:ocId fileNameView: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. EVP_PKEY *key = NULL;
  432. int status = 0;
  433. if (publicKey != nil) {
  434. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  435. // Extract real publicKey
  436. BIO *bio = BIO_new_mem_buf(pKey, -1);
  437. if (!bio)
  438. return nil;
  439. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  440. if (!x509)
  441. return nil;
  442. key = X509_get_pubkey(x509);
  443. if (!key)
  444. return nil;
  445. }
  446. if (privateKey != nil) {
  447. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  448. BIO *bio = BIO_new_mem_buf(pKey, -1);
  449. if (!bio)
  450. return nil;
  451. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  452. if (!key)
  453. return nil;
  454. }
  455. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  456. if (!ctx)
  457. return nil;
  458. status = EVP_PKEY_encrypt_init(ctx);
  459. if (status <= 0)
  460. return nil;
  461. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  462. if (status <= 0)
  463. return nil;
  464. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  465. if (status <= 0)
  466. return nil;
  467. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  468. if (status <= 0)
  469. return nil;
  470. unsigned long outLen = 0;
  471. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  472. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  473. if (status <= 0 || outLen == 0)
  474. return nil;
  475. unsigned char *out = (unsigned char *) malloc(outLen);
  476. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  477. if (status <= 0)
  478. return nil;
  479. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  480. if (out)
  481. free(out);
  482. return outData;
  483. }
  484. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  485. {
  486. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  487. int status = 0;
  488. BIO *bio = BIO_new_mem_buf(pKey, -1);
  489. if (!bio)
  490. return nil;
  491. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  492. if (!key)
  493. return nil;
  494. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  495. if (!ctx)
  496. return nil;
  497. status = EVP_PKEY_decrypt_init(ctx);
  498. if (status <= 0)
  499. return nil;
  500. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  501. if (status <= 0)
  502. return nil;
  503. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  504. if (status <= 0)
  505. return nil;
  506. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  507. if (status <= 0)
  508. return nil;
  509. unsigned long outLen = 0;
  510. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  511. if (status <= 0 || outLen == 0)
  512. return nil;
  513. unsigned char *out = (unsigned char *) malloc(outLen);
  514. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  515. if (status <= 0)
  516. return nil;
  517. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  518. //NSString *out64 = [outData base64EncodedStringWithOptions:0];
  519. if (out)
  520. free(out);
  521. return outData;
  522. }
  523. #
  524. #pragma mark - AES/GCM/NoPadding
  525. #
  526. // Encryption using GCM mode
  527. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData **)tagData
  528. {
  529. int status = 0;
  530. int len = 0;
  531. // set up key
  532. len = keyLen;
  533. unsigned char cKey[len];
  534. bzero(cKey, sizeof(cKey));
  535. [keyData getBytes:cKey length:len];
  536. // set up ivec
  537. len = AES_IVEC_LENGTH;
  538. unsigned char cIV[len];
  539. bzero(cIV, sizeof(cIV));
  540. [ivData getBytes:cIV length:len];
  541. // set up tag
  542. len = AES_GCM_TAG_LENGTH;
  543. unsigned char cTag[len];
  544. bzero(cTag, sizeof(cTag));
  545. // Create and initialise the context
  546. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  547. if (!ctx)
  548. return NO;
  549. // Initialise the encryption operation
  550. if (keyLen == AES_KEY_128_LENGTH)
  551. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  552. else if (keyLen == AES_KEY_256_LENGTH)
  553. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  554. if (status <= 0)
  555. return NO;
  556. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  557. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  558. if (status <= 0)
  559. return NO;
  560. // Initialise key and IV
  561. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  562. if (status <= 0)
  563. return NO;
  564. // Provide the message to be encrypted, and obtain the encrypted output
  565. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  566. unsigned char * cCipher = [*cipherData mutableBytes];
  567. int cCipherLen = 0;
  568. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plainData bytes], (int)[plainData length]);
  569. if (status <= 0)
  570. return NO;
  571. // Finalise the encryption
  572. len = cCipherLen;
  573. status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  574. if (status <= 0)
  575. return NO;
  576. // Get the tag
  577. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  578. *tagData = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  579. // Append TAG
  580. [*cipherData appendData:*tagData];
  581. // Free
  582. EVP_CIPHER_CTX_free(ctx);
  583. return status; // OpenSSL uses 1 for success
  584. }
  585. // Decryption using GCM mode
  586. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData *)tagData
  587. {
  588. int status = 0;
  589. int len = 0;
  590. // set up key
  591. len = keyLen;
  592. unsigned char cKey[len];
  593. bzero(cKey, sizeof(cKey));
  594. [keyData getBytes:cKey length:len];
  595. // set up ivec
  596. len = (int)[ivData length];
  597. unsigned char cIV[len];
  598. bzero(cIV, sizeof(cIV));
  599. [ivData getBytes:cIV length:len];
  600. // set up tag
  601. len = (int)[tagData length];;
  602. unsigned char cTag[len];
  603. bzero(cTag, sizeof(cTag));
  604. [tagData getBytes:cTag length:len];
  605. // Create and initialise the context
  606. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  607. if (!ctx)
  608. return NO;
  609. // Initialise the decryption operation
  610. if (keyLen == AES_KEY_128_LENGTH)
  611. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  612. else if (keyLen == AES_KEY_256_LENGTH)
  613. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  614. if (status <= 0)
  615. return NO;
  616. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  617. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  618. if (status <= 0)
  619. return NO;
  620. // Initialise key and IV
  621. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  622. if (status <= 0)
  623. return NO;
  624. // Provide the message to be decrypted, and obtain the plaintext output
  625. *plainData = [NSMutableData dataWithLength:([cipherData length])];
  626. int cPlainLen = 0;
  627. unsigned char * cPlain = [*plainData mutableBytes];
  628. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipherData bytes], (int)([cipherData length]));
  629. if (status <= 0)
  630. return NO;
  631. // Tag is the last 16 bytes
  632. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  633. if (status <= 0)
  634. return NO;
  635. // Finalise the encryption
  636. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  637. // Free
  638. EVP_CIPHER_CTX_free(ctx);
  639. return status; // OpenSSL uses 1 for success
  640. }
  641. #
  642. #pragma mark - Utility
  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. - (NSString *)getSHA1:(NSString *)input
  675. {
  676. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  677. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  678. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  679. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  680. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  681. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  682. [output appendFormat:@"%02x", digest[i]];
  683. return output;
  684. }
  685. - (NSData *)hashValueMD5OfData:(NSData *)data
  686. {
  687. MD5_CTX md5Ctx;
  688. unsigned char hashValue[MD5_DIGEST_LENGTH];
  689. if(!MD5_Init(&md5Ctx)) {
  690. return nil;
  691. }
  692. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  693. return nil;
  694. }
  695. if (!MD5_Final(hashValue, &md5Ctx)) {
  696. return nil;
  697. }
  698. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  699. }
  700. - (NSString *)hexadecimalString:(NSData *)input
  701. {
  702. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  703. if (!dataBuffer) {
  704. return [NSString string];
  705. }
  706. NSUInteger dataLength = [input length];
  707. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  708. for (int i = 0; i < dataLength; ++i) {
  709. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  710. }
  711. return [NSString stringWithString:hexString];
  712. }
  713. - (NSString *)derToPemPrivateKey:(NSString *)input
  714. {
  715. NSInteger substringLength = 65;
  716. NSMutableString *result = [NSMutableString stringWithString: input];
  717. for(long i=substringLength;i<=input.length;i++) {
  718. [result insertString: @"\n" atIndex: i];
  719. i+=substringLength;
  720. }
  721. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  722. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  723. return result;
  724. }
  725. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  726. {
  727. char *buf[256];
  728. FILE *pFile;
  729. NSString *pkey_string;
  730. pFile = fmemopen(buf, sizeof(buf), "w");
  731. PEM_write_PUBKEY(pFile,pubkey);
  732. fputc('\0', pFile);
  733. fclose(pFile);
  734. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  735. return pkey_string;
  736. }
  737. @end