NCEndToEndEncryption.m 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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 <CommonCrypto/CommonDigest.h>
  26. #import <CommonCrypto/CommonKeyDerivation.h>
  27. #import <OpenSSL/OpenSSL.h>
  28. #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);
  29. #define IV_DELIMITER_ENCODED_OLD @"fA=="
  30. #define IV_DELIMITER_ENCODED @"|"
  31. #define PBKDF2_KEY_LENGTH 256
  32. //#define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  33. #define ASYMMETRIC_STRING_TEST @"Nextcloud a safe home for all your data"
  34. #define fileNameCertificate @"cert.pem"
  35. #define fileNameCSR @"csr.pem"
  36. #define fileNamePrivateKey @"privateKey.pem"
  37. #define fileNamePubliceKey @"publicKey.pem"
  38. #define streamBuffer 1024
  39. #define AES_KEY_128_LENGTH 16
  40. #define AES_KEY_256_LENGTH 32
  41. #define AES_IVEC_LENGTH 16
  42. #define AES_GCM_TAG_LENGTH 16
  43. #define AES_SALT_LENGTH 40
  44. @interface NCEndToEndEncryption ()
  45. {
  46. NSData *_privateKeyData;
  47. NSData *_publicKeyData;
  48. NSData *_csrData;
  49. }
  50. @end
  51. @implementation NCEndToEndEncryption
  52. //Singleton
  53. + (instancetype)shared {
  54. static dispatch_once_t once;
  55. static NCEndToEndEncryption *shared;
  56. dispatch_once(&once, ^{
  57. shared = [self new];
  58. });
  59. return shared;
  60. }
  61. #
  62. #pragma mark - Generate Certificate X509 - CSR - Private Key
  63. #
  64. - (BOOL)generateCertificateX509WithUserId:(NSString *)userId directory:(NSString *)directory
  65. {
  66. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
  67. if (!ctx) {
  68. return FALSE;
  69. }
  70. // Generate an new RSA KEY
  71. if (EVP_PKEY_keygen_init(ctx) <= 0) {
  72. EVP_PKEY_CTX_free(ctx);
  73. return FALSE;
  74. }
  75. if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) <= 0) {
  76. EVP_PKEY_CTX_free(ctx);
  77. return FALSE;
  78. }
  79. EVP_PKEY *pkey = NULL;
  80. if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
  81. EVP_PKEY_CTX_free(ctx);
  82. return FALSE;
  83. }
  84. X509 *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(@"[INFO] \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(@"[INFO] \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(@"[INFO] \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(@"[INFO] \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(@"[INFO] 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(@"[INFO] 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(@"[INFO] 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(@"[INFO] 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(@"[INFO] 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 iterationCount:(unsigned int)iterationCount
  264. {
  265. NSMutableData *cipher = [NSMutableData new];
  266. if (!_privateKeyData) {
  267. if (![self generateCertificateX509WithUserId:userId directory:directory])
  268. return nil;
  269. }
  270. NSMutableData *key = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  271. NSData *salt = [self generateSalt:AES_SALT_LENGTH];
  272. // Remove all whitespaces from passphrase
  273. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  274. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA1, iterationCount, key.mutableBytes, key.length);
  275. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  276. NSData *authenticationTag = [NSData new];
  277. NSString *pkEncoded = [_privateKeyData base64EncodedStringWithOptions:0];
  278. NSData *pkEncodedData = [pkEncoded dataUsingEncoding:NSUTF8StringEncoding];
  279. BOOL result = [self encryptData:pkEncodedData cipher:&cipher key:key keyLen:AES_KEY_256_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  280. if (result && cipher) {
  281. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  282. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  283. NSString *saltString = [salt base64EncodedStringWithOptions:0];
  284. NSString *encryptPrivateKey = [NSString stringWithFormat:@"%@%@%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString, IV_DELIMITER_ENCODED, saltString];
  285. *privateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  286. return encryptPrivateKey;
  287. } else {
  288. return nil;
  289. }
  290. }
  291. - (NSData *)decryptPrivateKey:(NSString *)privateKey passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey iterationCount:(unsigned int)iterationCount
  292. {
  293. NSMutableData *plain = [NSMutableData new];
  294. // Key
  295. NSMutableData *key = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  296. // Split
  297. NSArray *cipherArray = [privateKey componentsSeparatedByString:IV_DELIMITER_ENCODED];
  298. if (cipherArray.count != 3) {
  299. cipherArray = [privateKey componentsSeparatedByString:IV_DELIMITER_ENCODED_OLD];
  300. if (cipherArray.count != 3) {
  301. return nil;
  302. }
  303. }
  304. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:cipherArray[0] options:0];
  305. NSString *authenticationTagString = [privateKey substringWithRange:NSMakeRange([(NSString *)cipherArray[0] length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  306. NSData *authenticationTag = [[NSData alloc] initWithBase64EncodedString:authenticationTagString options:0];
  307. NSData *initializationVector = [[NSData alloc] initWithBase64EncodedString:cipherArray[1] options:0];
  308. NSData *salt = [[NSData alloc] initWithBase64EncodedString:cipherArray[2] options:0];
  309. // Remove Authentication Tag
  310. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  311. // Remove all whitespaces from passphrase
  312. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  313. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA1, iterationCount, key.mutableBytes, key.length);
  314. BOOL result = [self decryptData:cipher plain:&plain key:key keyLen:AES_KEY_256_LENGTH initializationVector:initializationVector authenticationTag:authenticationTag];
  315. if (result && plain) {
  316. return plain;
  317. }
  318. return nil;
  319. }
  320. #
  321. #pragma mark - Encrypt / Decrypt file material
  322. #
  323. - (NSString *)encryptPayloadFile:(NSData *)encrypted key:(NSString *)key
  324. {
  325. NSMutableData *cipher;
  326. NSData *authenticationTag = [NSData new];
  327. // Key
  328. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  329. // Initialization Vector
  330. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  331. BOOL result = [self encryptData:encrypted cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  332. if (cipher != nil && result) {
  333. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  334. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  335. NSString *payload = [NSString stringWithFormat:@"%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString];
  336. return payload;
  337. }
  338. return nil;
  339. }
  340. - (NSString *)encryptPayloadFile:(NSData *)encrypted key:(NSString *)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  341. {
  342. NSMutableData *cipher;
  343. NSData *authenticationTagData = [NSData new];
  344. // Key
  345. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  346. // Initialization Vector
  347. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  348. BOOL result = [self encryptData:encrypted cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  349. if (cipher != nil && result) {
  350. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  351. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  352. NSString *payload = [cipher base64EncodedStringWithOptions:0];
  353. return payload;
  354. }
  355. return nil;
  356. }
  357. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  358. {
  359. NSMutableData *plain;
  360. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  361. if (range.location == NSNotFound) {
  362. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  363. if (range.location == NSNotFound) {
  364. return nil;
  365. }
  366. }
  367. // Cipher
  368. NSString *cipher = [encrypted substringToIndex:(range.location)];
  369. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  370. // Key
  371. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  372. // Initialization Vector
  373. NSString *initializationVector = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  374. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  375. // Authentication Tag
  376. NSString *authenticationTag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  377. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  378. // Remove Authentication Tag
  379. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  380. BOOL result = [self decryptData:cipherData plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  381. if (plain != nil && result) {
  382. return plain;
  383. }
  384. return nil;
  385. }
  386. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  387. {
  388. NSMutableData *plain;
  389. // Remove initializationVector Tag if exists [ANDROID]
  390. NSString *android = [@"|" stringByAppendingString: initializationVector];
  391. encrypted = [encrypted stringByReplacingOccurrencesOfString:android withString:@""];
  392. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:encrypted options:0];
  393. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  394. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  395. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  396. // Remove Authentication Tag
  397. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  398. BOOL result = [self decryptData:cipher plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  399. if (plain != nil && result && plain.length > 0) {
  400. return plain;
  401. }
  402. return nil;
  403. }
  404. #
  405. #pragma mark - Encrypt / Decrypt file
  406. #
  407. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  408. {
  409. NSData *authenticationTagData;
  410. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  411. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  412. BOOL result = [self encryptFile:[NSString stringWithFormat:@"%@/%@", directory, fileName] fileNameCipher:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  413. if (result) {
  414. *key = [keyData base64EncodedStringWithOptions:0];
  415. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  416. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  417. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  418. return false;
  419. } else {
  420. return true;
  421. }
  422. }
  423. return false;
  424. }
  425. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  426. {
  427. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  428. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  429. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  430. return [self decryptFile:[[[NCUtilityFileSystem alloc] init] getDirectoryProviderStorageOcId:ocId fileNameView:fileName] fileNamePlain:[[[NCUtilityFileSystem alloc] init] getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  431. }
  432. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  433. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  434. #
  435. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  436. #
  437. #
  438. #pragma mark - Encrypt/Decrypt asymmetric
  439. #
  440. - (NSData *)encryptAsymmetricData:(NSData *)plainData certificate:(NSString *)certificate
  441. {
  442. EVP_PKEY *key = NULL;
  443. int status = 0;
  444. unsigned char *pKey = (unsigned char *)[certificate UTF8String];
  445. // Extract real publicKey
  446. BIO *bio = BIO_new_mem_buf(pKey, -1);
  447. if (!bio)
  448. return nil;
  449. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  450. if (!x509)
  451. return nil;
  452. key = X509_get_pubkey(x509);
  453. if (!key)
  454. return nil;
  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. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  472. if (status <= 0 || outLen == 0)
  473. return nil;
  474. unsigned char *out = (unsigned char *) malloc(outLen);
  475. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  476. if (status <= 0)
  477. return nil;
  478. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  479. if (out)
  480. free(out);
  481. return outData;
  482. }
  483. - (NSData *)encryptAsymmetricData:(NSData *)plainData privateKey:(NSString *)privateKey
  484. {
  485. EVP_PKEY *key = NULL;
  486. int status = 0;
  487. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  488. BIO *bio = BIO_new_mem_buf(pKey, -1);
  489. if (!bio)
  490. return nil;
  491. 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_encrypt_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_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  511. if (status <= 0 || outLen == 0)
  512. return nil;
  513. unsigned char *out = (unsigned char *) malloc(outLen);
  514. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  515. if (status <= 0)
  516. return nil;
  517. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  518. if (out)
  519. free(out);
  520. return outData;
  521. }
  522. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  523. {
  524. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  525. int status = 0;
  526. BIO *bio = BIO_new_mem_buf(pKey, -1);
  527. if (!bio)
  528. return nil;
  529. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  530. if (!key)
  531. return nil;
  532. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  533. if (!ctx)
  534. return nil;
  535. status = EVP_PKEY_decrypt_init(ctx);
  536. if (status <= 0)
  537. return nil;
  538. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  539. if (status <= 0)
  540. return nil;
  541. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  542. if (status <= 0)
  543. return nil;
  544. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  545. if (status <= 0)
  546. return nil;
  547. unsigned long outLen = 0;
  548. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  549. if (status <= 0 || outLen == 0)
  550. return nil;
  551. unsigned char *out = (unsigned char *) malloc(outLen);
  552. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  553. if (status <= 0)
  554. return nil;
  555. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  556. if (out)
  557. free(out);
  558. return outData;
  559. }
  560. #
  561. #pragma mark - AES/GCM/NoPadding
  562. #
  563. // Encryption data using GCM mode
  564. - (BOOL)encryptData:(NSData *)plain cipher:(NSMutableData **)cipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  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. [key getBytes:cKey length:len];
  573. // set up ivec
  574. len = AES_IVEC_LENGTH;
  575. unsigned char cIV[len];
  576. bzero(cIV, sizeof(cIV));
  577. [initializationVector getBytes:cIV length:len];
  578. // set up tag
  579. len = AES_GCM_TAG_LENGTH;
  580. unsigned char cTag[len];
  581. bzero(cTag, sizeof(cTag));
  582. // Create and initialise the context
  583. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  584. if (!ctx)
  585. return NO;
  586. // Initialise the encryption operation
  587. if (keyLen == AES_KEY_128_LENGTH)
  588. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  589. else if (keyLen == AES_KEY_256_LENGTH)
  590. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  591. if (status <= 0) {
  592. EVP_CIPHER_CTX_free(ctx);
  593. return NO;
  594. }
  595. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  596. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  597. if (status <= 0) {
  598. EVP_CIPHER_CTX_free(ctx);
  599. return NO;
  600. }
  601. // Initialise key and IV
  602. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  603. if (status <= 0) {
  604. EVP_CIPHER_CTX_free(ctx);
  605. return NO;
  606. }
  607. // Provide the message to be encrypted, and obtain the encrypted output
  608. *cipher = [NSMutableData dataWithLength:[plain length]];
  609. unsigned char * cCipher = [*cipher mutableBytes];
  610. int cCipherLen = 0;
  611. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  612. if (status <= 0) {
  613. EVP_CIPHER_CTX_free(ctx);
  614. return NO;
  615. }
  616. // Finalise the encryption
  617. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  618. if (status <= 0) {
  619. EVP_CIPHER_CTX_free(ctx);
  620. return NO;
  621. }
  622. // Get the tag
  623. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  624. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  625. // Append TAG
  626. [*cipher appendData:*authenticationTag];
  627. EVP_CIPHER_CTX_free(ctx);
  628. return status; // OpenSSL uses 1 for success
  629. }
  630. // Encryption file using GCM mode
  631. - (BOOL)encryptFile:(NSString *)fileName fileNameCipher:(NSString *)fileNameCipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  632. {
  633. int status = 0;
  634. int len = 0;
  635. // set up key
  636. len = keyLen;
  637. unsigned char cKey[len];
  638. bzero(cKey, sizeof(cKey));
  639. [key getBytes:cKey length:len];
  640. // set up ivec
  641. len = AES_IVEC_LENGTH;
  642. unsigned char cIV[len];
  643. bzero(cIV, sizeof(cIV));
  644. [initializationVector getBytes:cIV length:len];
  645. // set up tag
  646. len = AES_GCM_TAG_LENGTH;
  647. unsigned char cTag[len];
  648. bzero(cTag, sizeof(cTag));
  649. // Create and initialise the context
  650. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  651. if (!ctx) {
  652. return NO;
  653. }
  654. // Initialise the encryption operation
  655. if (keyLen == AES_KEY_128_LENGTH)
  656. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  657. else if (keyLen == AES_KEY_256_LENGTH)
  658. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  659. if (status <= 0) {
  660. EVP_CIPHER_CTX_free(ctx);
  661. return NO;
  662. }
  663. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  664. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  665. if (status <= 0) {
  666. EVP_CIPHER_CTX_free(ctx);
  667. return NO;
  668. }
  669. // Initialise key and IV
  670. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  671. if (status <= 0) {
  672. EVP_CIPHER_CTX_free(ctx);
  673. return NO;
  674. }
  675. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  676. [inStream open];
  677. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNameCipher append:false];
  678. [outStream open];
  679. Byte buffer[streamBuffer];
  680. NSInteger totalNumberOfBytesWritten = 0;
  681. int cCipherLen = 0;
  682. unsigned char *cCipher;
  683. while ([inStream hasBytesAvailable]) {
  684. @autoreleasepool {
  685. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  686. if (bytesRead > 0) {
  687. cCipher = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  688. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  689. if (status <= 0) {
  690. [inStream close];
  691. [outStream close];
  692. EVP_CIPHER_CTX_free(ctx);
  693. return NO;
  694. }
  695. if ([outStream hasSpaceAvailable]) {
  696. totalNumberOfBytesWritten = [outStream write:cCipher maxLength:cCipherLen];
  697. if (totalNumberOfBytesWritten != cCipherLen) {
  698. [inStream close];
  699. [outStream close];
  700. EVP_CIPHER_CTX_free(ctx);
  701. return NO;
  702. }
  703. }
  704. }
  705. }
  706. }
  707. [inStream close];
  708. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  709. if (status <= 0) {
  710. [outStream close];
  711. EVP_CIPHER_CTX_free(ctx);
  712. return NO;
  713. }
  714. // Get the tag
  715. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  716. if (status <= 0) {
  717. [outStream close];
  718. EVP_CIPHER_CTX_free(ctx);
  719. return NO;
  720. }
  721. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  722. // Append TAG
  723. if ([outStream hasSpaceAvailable]) {
  724. totalNumberOfBytesWritten = [outStream write:cTag maxLength:sizeof(cTag)];
  725. if (totalNumberOfBytesWritten != sizeof(cTag)) {
  726. status = NO;
  727. }
  728. } else {
  729. status = NO;
  730. }
  731. [outStream close];
  732. EVP_CIPHER_CTX_free(ctx);
  733. return status; // OpenSSL uses 1 for success
  734. }
  735. // Decryption data using GCM mode
  736. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  737. {
  738. int status = 0;
  739. int len = 0;
  740. // set up key
  741. len = keyLen;
  742. unsigned char cKey[len];
  743. bzero(cKey, sizeof(cKey));
  744. [key getBytes:cKey length:len];
  745. // set up ivec
  746. len = (int)[initializationVector length];
  747. unsigned char cIV[len];
  748. bzero(cIV, sizeof(cIV));
  749. [initializationVector getBytes:cIV length:len];
  750. // set up tag
  751. len = (int)[authenticationTag length];;
  752. unsigned char cTag[len];
  753. bzero(cTag, sizeof(cTag));
  754. [authenticationTag getBytes:cTag length:len];
  755. // Create and initialise the context
  756. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  757. if (!ctx)
  758. return NO;
  759. // Initialise the decryption operation
  760. if (keyLen == AES_KEY_128_LENGTH)
  761. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  762. else if (keyLen == AES_KEY_256_LENGTH)
  763. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  764. if (status <= 0) {
  765. EVP_CIPHER_CTX_free(ctx);
  766. return NO;
  767. }
  768. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  769. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  770. if (status <= 0) {
  771. EVP_CIPHER_CTX_free(ctx);
  772. return NO;
  773. }
  774. // Initialise key and IV
  775. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  776. if (status <= 0) {
  777. EVP_CIPHER_CTX_free(ctx);
  778. return NO;
  779. }
  780. // Provide the message to be decrypted, and obtain the plaintext output
  781. *plain = [NSMutableData dataWithLength:([cipher length])];
  782. int cPlainLen = 0;
  783. unsigned char * cPlain = [*plain mutableBytes];
  784. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  785. if (status <= 0) {
  786. EVP_CIPHER_CTX_free(ctx);
  787. return NO;
  788. }
  789. // Tag is the last 16 bytes
  790. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  791. if (status <= 0) {
  792. EVP_CIPHER_CTX_free(ctx);
  793. return NO;
  794. }
  795. // Finalise the encryption
  796. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  797. // Free
  798. EVP_CIPHER_CTX_free(ctx);
  799. return status; // OpenSSL uses 1 for success
  800. }
  801. // Decryption file using GCM mode
  802. - (BOOL)decryptFile:(NSString *)fileName fileNamePlain:(NSString *)fileNamePlain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  803. {
  804. int status = 0;
  805. int len = 0;
  806. // set up key
  807. len = keyLen;
  808. unsigned char cKey[len];
  809. bzero(cKey, sizeof(cKey));
  810. [key getBytes:cKey length:len];
  811. // set up ivec
  812. len = (int)[initializationVector length];
  813. unsigned char cIV[len];
  814. bzero(cIV, sizeof(cIV));
  815. [initializationVector getBytes:cIV length:len];
  816. // set up tag
  817. len = (int)[authenticationTag length];;
  818. unsigned char cTag[len];
  819. bzero(cTag, sizeof(cTag));
  820. [authenticationTag getBytes:cTag length:len];
  821. // Create and initialise the context
  822. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  823. if (!ctx)
  824. return NO;
  825. // Initialise the decryption operation
  826. if (keyLen == AES_KEY_128_LENGTH)
  827. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  828. else if (keyLen == AES_KEY_256_LENGTH)
  829. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  830. if (status <= 0) {
  831. EVP_CIPHER_CTX_free(ctx);
  832. return NO;
  833. }
  834. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  835. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  836. if (status <= 0) {
  837. EVP_CIPHER_CTX_free(ctx);
  838. return NO;
  839. }
  840. // Initialise key and IV
  841. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  842. if (status <= 0) {
  843. EVP_CIPHER_CTX_free(ctx);
  844. return NO;
  845. }
  846. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  847. [inStream open];
  848. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNamePlain append:false];
  849. [outStream open];
  850. Byte buffer[streamBuffer];
  851. NSInteger totalNumberOfBytesWritten = 0;
  852. int cPlainLen = 0;
  853. unsigned char *cPlain;
  854. while ([inStream hasBytesAvailable]) {
  855. @autoreleasepool {
  856. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  857. if (bytesRead > 0) {
  858. cPlain = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  859. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  860. if (status <= 0) {
  861. [inStream close];
  862. [outStream close];
  863. EVP_CIPHER_CTX_free(ctx);
  864. return NO;
  865. }
  866. if ([outStream hasSpaceAvailable]) {
  867. totalNumberOfBytesWritten = [outStream write:cPlain maxLength:cPlainLen];
  868. if (totalNumberOfBytesWritten != cPlainLen) {
  869. [inStream close];
  870. [outStream close];
  871. EVP_CIPHER_CTX_free(ctx);
  872. return NO;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. [inStream close];
  879. [outStream close];
  880. // Tag is the last 16 bytes
  881. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  882. if (status <= 0)
  883. return NO;
  884. // Finalise the encryption
  885. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  886. // Free
  887. EVP_CIPHER_CTX_free(ctx);
  888. return status; // OpenSSL uses 1 for success
  889. }
  890. #
  891. #pragma mark - CMS
  892. #
  893. - (NSData *)generateSignatureCMS:(NSData *)data certificate:(NSString *)certificate privateKey:(NSString *)privateKey userId:(NSString *)userId
  894. {
  895. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  896. unsigned char *certKey = (unsigned char *)[certificate UTF8String];
  897. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  898. BIO *certKeyBIO = BIO_new_mem_buf(certKey, -1);
  899. if (!certKeyBIO)
  900. return nil;
  901. X509 *x509 = PEM_read_bio_X509(certKeyBIO, NULL, 0, NULL);
  902. if (!x509)
  903. return nil;
  904. BIO *pkeyBIO = BIO_new_mem_buf(pKey, -1);
  905. EVP_PKEY *key = PEM_read_bio_PrivateKey(pkeyBIO, NULL, NULL, NULL);
  906. if (!key)
  907. return nil;
  908. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  909. CMS_ContentInfo *contentInfo = CMS_sign(x509, key, NULL, dataBIO, CMS_DETACHED);
  910. if (contentInfo == nil)
  911. return nil;
  912. // DEBUG CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  913. PEM_write_bio_CMS(printBIO, contentInfo);
  914. BIO *i2dCmsBioOut = BIO_new(BIO_s_mem());
  915. if (i2d_CMS_bio(i2dCmsBioOut, contentInfo) != 1)
  916. return nil;
  917. int len = BIO_pending(i2dCmsBioOut);
  918. char *keyBytes = malloc(len);
  919. BIO_read(i2dCmsBioOut, keyBytes, len);
  920. NSData *i2dCmsData = [NSData dataWithBytes:keyBytes length:len];
  921. BIO_free(printBIO);
  922. BIO_free(certKeyBIO);
  923. BIO_free(pkeyBIO);
  924. BIO_free(dataBIO);
  925. BIO_free(i2dCmsBioOut);
  926. return i2dCmsData;
  927. }
  928. - (BOOL)verifySignatureCMS:(NSData *)cmsContent data:(NSData *)data publicKey:(NSString *)publicKey userId:(NSString *)userId
  929. {
  930. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  931. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  932. BIO *cmsBIO = BIO_new_mem_buf(cmsContent.bytes, (int)cmsContent.length);
  933. CMS_ContentInfo *contentInfo = d2i_CMS_bio(cmsBIO, NULL);
  934. unsigned char *publicKeyUTF8 = (unsigned char *)[publicKey UTF8String];
  935. BIO *publicKeyBIO = BIO_new_mem_buf(publicKeyUTF8, -1);
  936. EVP_PKEY *pkey = PEM_read_bio_PUBKEY(publicKeyBIO, NULL, NULL, NULL);
  937. // DEBUG CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  938. BOOL verifyResult = CMS_verify(contentInfo, NULL, NULL, dataBIO, NULL, CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY);
  939. if (verifyResult) {
  940. STACK_OF(X509) *signers = CMS_get0_signers(contentInfo);
  941. int numSigners = sk_X509_num(signers);
  942. for (int i = 0; i < numSigners; ++i) {
  943. X509 *signer = sk_X509_value(signers, i);
  944. int result = X509_verify(signer, pkey);
  945. if (result <= 0) {
  946. verifyResult = false;
  947. break;
  948. }
  949. int cnDataLength = X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, 0, 0);
  950. cnDataLength += 1;
  951. NSMutableData* cnData = [NSMutableData dataWithLength:cnDataLength];
  952. X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, [cnData mutableBytes], cnDataLength);
  953. NSString *cn = [[NSString alloc] initWithCString:[cnData mutableBytes] encoding:NSUTF8StringEncoding];
  954. if ([userId isEqualToString:cn]) {
  955. verifyResult = true;
  956. break;
  957. } else {
  958. verifyResult = false;
  959. }
  960. }
  961. if (signers) {
  962. sk_X509_free(signers);
  963. }
  964. signers = NULL;
  965. }
  966. BIO_free(dataBIO);
  967. BIO_free(printBIO);
  968. BIO_free(cmsBIO);
  969. BIO_free(publicKeyBIO);
  970. return verifyResult;
  971. }
  972. - (BOOL)verifySignatureCMS:(NSData *)cmsContent data:(NSData *)data certificates:(NSArray*)certificates
  973. {
  974. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  975. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  976. BIO *cmsBIO = BIO_new_mem_buf(cmsContent.bytes, (int)cmsContent.length);
  977. CMS_ContentInfo *contentInfo = d2i_CMS_bio(cmsBIO, NULL);
  978. // DEBUG CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  979. BOOL verifyResult = CMS_verify(contentInfo, NULL, NULL, dataBIO, NULL, CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY);
  980. BIO_free(dataBIO);
  981. BIO_free(printBIO);
  982. BIO_free(cmsBIO);
  983. if (verifyResult) {
  984. struct stack_st_CMS_SignerInfo* signerInfos = CMS_get0_SignerInfos(contentInfo);
  985. STACK_OF(X509) *signers = CMS_get0_signers(contentInfo);
  986. int numSigners = sk_X509_num(signers);
  987. for (NSString *certificate in certificates) {
  988. const char *ptrCertificate = [certificate cStringUsingEncoding:NSUTF8StringEncoding];
  989. BIO *certBio = BIO_new(BIO_s_mem());
  990. BIO_write(certBio, ptrCertificate,(unsigned int)strlen(ptrCertificate));
  991. X509 *certX509 = PEM_read_bio_X509(certBio, NULL, NULL, NULL);
  992. if (!certX509) {
  993. continue;
  994. }
  995. for (int i = 0; i < numSigners; ++i) {
  996. struct CMS_SignerInfo_st *signerInfo = sk_CMS_SignerInfo_value(signerInfos, i);
  997. if (CMS_SignerInfo_cert_cmp(signerInfo, certX509) == 0) {
  998. BIO_free(certBio);
  999. return true;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. return verifyResult;
  1005. }
  1006. #
  1007. #pragma mark - Utility
  1008. #
  1009. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  1010. {
  1011. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  1012. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  1013. *key = [keyData base64EncodedStringWithOptions:0];
  1014. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  1015. }
  1016. - (NSString *)createSHA256:(NSData *)data
  1017. {
  1018. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  1019. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  1020. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  1021. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  1022. [output appendFormat:@"%02x", digest[i]];
  1023. return output;
  1024. }
  1025. - (NSString *)createSHA512:(NSString *)string
  1026. {
  1027. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  1028. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  1029. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  1030. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  1031. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  1032. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  1033. [output appendFormat:@"%02x", digest[i]];
  1034. return output;
  1035. }
  1036. - (NSData *)generateIV:(int)length
  1037. {
  1038. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  1039. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  1040. return ivData;
  1041. }
  1042. - (NSData *)generateSalt:(int)length
  1043. {
  1044. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  1045. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  1046. return saltData;
  1047. }
  1048. - (NSData *)generateKey:(int)length
  1049. {
  1050. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  1051. unsigned char *pKeyData = [keyData mutableBytes];
  1052. RAND_bytes(pKeyData, length);
  1053. return keyData;
  1054. }
  1055. - (NSData *)generateKey
  1056. {
  1057. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  1058. unsigned char *pKeyData = [keyData mutableBytes];
  1059. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  1060. return keyData;
  1061. }
  1062. - (NSString *)getSHA1:(NSString *)input
  1063. {
  1064. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  1065. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  1066. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  1067. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  1068. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  1069. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  1070. [output appendFormat:@"%02x", digest[i]];
  1071. return output;
  1072. }
  1073. - (NSString *)hexadecimalString:(NSData *)input
  1074. {
  1075. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  1076. if (!dataBuffer) {
  1077. return [NSString string];
  1078. }
  1079. NSUInteger dataLength = [input length];
  1080. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  1081. for (int i = 0; i < dataLength; ++i) {
  1082. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  1083. }
  1084. return [NSString stringWithString:hexString];
  1085. }
  1086. - (NSString *)derToPemPrivateKey:(NSString *)input
  1087. {
  1088. NSInteger substringLength = 65;
  1089. NSMutableString *result = [NSMutableString stringWithString: input];
  1090. for(long i=substringLength;i<=input.length;i++) {
  1091. [result insertString: @"\n" atIndex: i];
  1092. i+=substringLength;
  1093. }
  1094. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  1095. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  1096. return result;
  1097. }
  1098. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  1099. {
  1100. char *buf[256];
  1101. FILE *pFile;
  1102. NSString *pkey_string;
  1103. pFile = fmemopen(buf, sizeof(buf), "w");
  1104. PEM_write_PUBKEY(pFile,pubkey);
  1105. fputc('\0', pFile);
  1106. fclose(pFile);
  1107. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  1108. return pkey_string;
  1109. }
  1110. @end