NCEndToEndEncryption.m 32 KB

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