NCEndToEndEncryption.m 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  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 streamBuffer 1024
  41. #define AES_KEY_128_LENGTH 16
  42. #define AES_KEY_256_LENGTH 32
  43. #define AES_IVEC_LENGTH 16
  44. #define AES_GCM_TAG_LENGTH 16
  45. #define AES_SALT_LENGTH 40
  46. @interface NCEndToEndEncryption ()
  47. {
  48. NSData *_privateKeyData;
  49. NSData *_publicKeyData;
  50. NSData *_csrData;
  51. }
  52. @end
  53. @implementation NCEndToEndEncryption
  54. //Singleton
  55. + (instancetype)sharedManager {
  56. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  57. static dispatch_once_t onceToken;
  58. dispatch_once(&onceToken, ^{
  59. NCEndToEndEncryption = [self new];
  60. });
  61. return NCEndToEndEncryption;
  62. }
  63. #
  64. #pragma mark - Generate Certificate X509 - CSR - Private Key
  65. #
  66. - (BOOL)generateCertificateX509WithUserId:(NSString *)userId directory:(NSString *)directory
  67. {
  68. OPENSSL_init();
  69. int ret;
  70. EVP_PKEY * pkey;
  71. pkey = EVP_PKEY_new();
  72. RSA * rsa;
  73. BIGNUM *bignum = BN_new();
  74. ret = BN_set_word(bignum, RSA_F4);
  75. if (ret != 1) {
  76. return NO;
  77. }
  78. rsa = RSA_new();
  79. ret = RSA_generate_key_ex(rsa, 2048, bignum, NULL);
  80. if (ret != 1) {
  81. return NO;
  82. }
  83. EVP_PKEY_assign_RSA(pkey, rsa);
  84. X509 * x509;
  85. x509 = X509_new();
  86. ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
  87. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  88. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  89. X509_gmtime_adj(X509_get_notBefore(x509), notBefore);
  90. X509_gmtime_adj(X509_get_notAfter(x509), notAfter);
  91. X509_set_pubkey(x509, pkey);
  92. X509_NAME * name;
  93. name = X509_get_subject_name(x509);
  94. // Now to add the subject name fields to the certificate
  95. // I use a macro here to make it cleaner.
  96. const unsigned char *cUserId = (const unsigned char *) [userId cStringUsingEncoding:NSUTF8StringEncoding];
  97. // Common Name = UserID.
  98. addName("CN", cUserId);
  99. // The organizational unit for the cert. Usually this is a department.
  100. addName("OU", "Certificate Authority");
  101. // The organization of the cert.
  102. addName("O", "Nextcloud");
  103. // The city of the organization.
  104. addName("L", "Vicenza");
  105. // The state/province of the organization.
  106. addName("S", "Italy");
  107. // The country (ISO 3166) of the organization
  108. addName("C", "IT");
  109. X509_set_issuer_name(x509, name);
  110. /*
  111. for (SANObject * san in self.options.sans) {
  112. if (!san.value || san.value.length <= 0) {
  113. continue;
  114. }
  115. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  116. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  117. NSLog(@"Add subjectAltName %@", value);
  118. X509_EXTENSION * extension = NULL;
  119. ASN1_STRING * asnValue = ASN1_STRING_new();
  120. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  121. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  122. X509_add_ext(x509, extension, -1);
  123. }
  124. */
  125. // Specify the encryption algorithm of the signature.
  126. // SHA256 should suit your needs.
  127. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  128. return NO;
  129. }
  130. X509_print_fp(stdout, x509);
  131. // Extract CSR, publicKey, privateKey
  132. int len;
  133. char *keyBytes;
  134. // CSR
  135. BIO *csrBIO = BIO_new(BIO_s_mem());
  136. X509_REQ *certReq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  137. PEM_write_bio_X509_REQ(csrBIO, certReq);
  138. len = BIO_pending(csrBIO);
  139. keyBytes = malloc(len);
  140. BIO_read(csrBIO, keyBytes, len);
  141. _csrData = [NSData dataWithBytes:keyBytes length:len];
  142. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding]);
  143. // PublicKey
  144. BIO *publicKeyBIO = BIO_new(BIO_s_mem());
  145. PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
  146. len = BIO_pending(publicKeyBIO);
  147. keyBytes = malloc(len);
  148. BIO_read(publicKeyBIO, keyBytes, len);
  149. _publicKeyData = [NSData dataWithBytes:keyBytes length:len];
  150. self.generatedPublicKey = [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding];
  151. NSLog(@"[LOG] \n%@", self.generatedPublicKey);
  152. // PrivateKey
  153. BIO *privateKeyBIO = BIO_new(BIO_s_mem());
  154. PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
  155. len = BIO_pending(privateKeyBIO);
  156. keyBytes = malloc(len);
  157. BIO_read(privateKeyBIO, keyBytes, len);
  158. _privateKeyData = [NSData dataWithBytes:keyBytes length:len];
  159. self.generatedPrivateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  160. NSLog(@"[LOG] \n%@", self.generatedPrivateKey);
  161. if(keyBytes)
  162. free(keyBytes);
  163. #ifdef DEBUG
  164. // Save to disk [DEBUG MODE]
  165. [self saveToDiskPEMWithCert:x509 key:pkey directory:directory];
  166. #endif
  167. return YES;
  168. }
  169. - (NSString *)extractPublicKeyFromCertificate:(NSString *)pemCertificate
  170. {
  171. const char *ptrCert = [pemCertificate cStringUsingEncoding:NSUTF8StringEncoding];
  172. BIO *certBio = BIO_new(BIO_s_mem());
  173. BIO_write(certBio, ptrCert,(unsigned int)strlen(ptrCert));
  174. X509 *certX509 = PEM_read_bio_X509(certBio, NULL, NULL, NULL);
  175. if (!certX509) {
  176. fprintf(stderr, "unable to parse certificate in memory\n");
  177. return nil;
  178. }
  179. EVP_PKEY *pkey;
  180. pkey = X509_get_pubkey(certX509);
  181. NSString *publicKey = [self pubKeyToString:pkey];
  182. EVP_PKEY_free(pkey);
  183. BIO_free(certBio);
  184. X509_free(certX509);
  185. NSLog(@"[LOG] \n%@", publicKey);
  186. return publicKey;
  187. }
  188. - (BOOL)saveToDiskPEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory
  189. {
  190. FILE *f;
  191. // Certificate
  192. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCertificate];
  193. f = fopen([certificatePath fileSystemRepresentation], "wb");
  194. if (PEM_write_X509(f, x509) < 0) {
  195. // Error writing to disk.
  196. fclose(f);
  197. return NO;
  198. }
  199. NSLog(@"[LOG] Saved cert to %@", certificatePath);
  200. fclose(f);
  201. // PublicKey
  202. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePubliceKey];
  203. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  204. if (PEM_write_PUBKEY(f, pkey) < 0) {
  205. // Error
  206. fclose(f);
  207. return NO;
  208. }
  209. NSLog(@"[LOG] Saved publicKey to %@", publicKeyPath);
  210. fclose(f);
  211. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  212. // file using the password and cipher you provide.
  213. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  214. // PrivateKey
  215. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePrivateKey];
  216. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  217. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  218. // Error
  219. fclose(f);
  220. return NO;
  221. }
  222. NSLog(@"[LOG] Saved privatekey to %@", privatekeyPath);
  223. fclose(f);
  224. // CSR Request sha256
  225. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCSR];
  226. f = fopen([csrPath fileSystemRepresentation], "wb");
  227. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  228. if (PEM_write_X509_REQ(f, certreq) < 0) {
  229. // Error
  230. fclose(f);
  231. return NO;
  232. }
  233. NSLog(@"[LOG] Saved csr to %@", csrPath);
  234. fclose(f);
  235. return YES;
  236. }
  237. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory finished:(void (^)(NSError *))finished
  238. {
  239. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  240. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  241. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directory];
  242. FILE *f = fopen([path fileSystemRepresentation], "wb");
  243. if (i2d_PKCS12_fp(f, p12) != 1) {
  244. fclose(f);
  245. return NO;
  246. }
  247. NSLog(@"[LOG] Saved p12 to %@", path);
  248. fclose(f);
  249. return YES;
  250. }
  251. #
  252. #pragma mark - Create CSR & Encrypt/Decrypt Private Key
  253. #
  254. - (NSString *)createCSR:(NSString *)userId directory:(NSString *)directory
  255. {
  256. // Create Certificate, if do not exists
  257. if (!_csrData) {
  258. if (![self generateCertificateX509WithUserId:userId directory:directory])
  259. return nil;
  260. }
  261. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  262. return csr;
  263. }
  264. - (NSString *)encryptPrivateKey:(NSString *)userId directory:(NSString *)directory passphrase:(NSString *)passphrase privateKey:(NSString **)privateKey
  265. {
  266. NSMutableData *cipher = [NSMutableData new];
  267. if (!_privateKeyData) {
  268. if (![self generateCertificateX509WithUserId:userId directory:directory])
  269. return nil;
  270. }
  271. NSMutableData *key = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  272. NSData *salt = [self generateSalt:AES_SALT_LENGTH];
  273. // Remove all whitespaces from passphrase
  274. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  275. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, key.mutableBytes, key.length);
  276. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  277. NSData *authenticationTag = [NSData new];
  278. NSString *pkEncoded = [_privateKeyData base64EncodedStringWithOptions:0];
  279. NSData *pkEncodedData = [pkEncoded dataUsingEncoding:NSUTF8StringEncoding];
  280. BOOL result = [self encryptData:pkEncodedData cipher:&cipher key:key keyLen:AES_KEY_256_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  281. if (result && cipher) {
  282. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  283. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  284. NSString *saltString = [salt base64EncodedStringWithOptions:0];
  285. NSString *encryptPrivateKey = [NSString stringWithFormat:@"%@%@%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString, IV_DELIMITER_ENCODED, saltString];
  286. *privateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  287. return encryptPrivateKey;
  288. } else {
  289. return nil;
  290. }
  291. }
  292. - (NSData *)decryptPrivateKey:(NSString *)privateKey passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey
  293. {
  294. NSMutableData *plain = [NSMutableData new];
  295. // Key
  296. NSMutableData *key = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  297. // Split
  298. NSArray *cipherArray = [privateKey componentsSeparatedByString:IV_DELIMITER_ENCODED];
  299. if (cipherArray.count != 3) {
  300. cipherArray = [privateKey componentsSeparatedByString:IV_DELIMITER_ENCODED_OLD];
  301. if (cipherArray.count != 3) {
  302. return nil;
  303. }
  304. }
  305. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:cipherArray[0] options:0];
  306. NSString *authenticationTagString = [privateKey substringWithRange:NSMakeRange([(NSString *)cipherArray[0] length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  307. NSData *authenticationTag = [[NSData alloc] initWithBase64EncodedString:authenticationTagString options:0];
  308. NSData *initializationVector = [[NSData alloc] initWithBase64EncodedString:cipherArray[1] options:0];
  309. NSData *salt = [[NSData alloc] initWithBase64EncodedString:cipherArray[2] options:0];
  310. // Remove Authentication Tag
  311. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  312. // Remove all whitespaces from passphrase
  313. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  314. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, key.mutableBytes, key.length);
  315. BOOL result = [self decryptData:cipher plain:&plain key:key keyLen:AES_KEY_256_LENGTH initializationVector:initializationVector authenticationTag:authenticationTag];
  316. if (result && plain) {
  317. return plain;
  318. }
  319. return nil;
  320. }
  321. #
  322. #pragma mark - Encrypt / Decrypt file material
  323. #
  324. - (NSString *)encryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  325. {
  326. NSMutableData *cipher;
  327. NSData *authenticationTag = [NSData new];
  328. NSData *encryptedData = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  329. encryptedData = [[encryptedData base64EncodedStringWithOptions:0] dataUsingEncoding:NSUTF8StringEncoding];
  330. // Key
  331. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  332. // Initialization Vector
  333. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  334. BOOL result = [self encryptData:encryptedData cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  335. if (cipher != nil && result) {
  336. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  337. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  338. NSString *payload = [NSString stringWithFormat:@"%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString];
  339. return payload;
  340. }
  341. return nil;
  342. }
  343. - (NSString *)encryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  344. {
  345. NSMutableData *cipher;
  346. NSData *authenticationTagData = [NSData new];
  347. NSData *encryptedData = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  348. encryptedData = [[encryptedData base64EncodedStringWithOptions:0] dataUsingEncoding:NSUTF8StringEncoding];
  349. // Key
  350. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  351. // Initialization Vector
  352. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  353. BOOL result = [self encryptData:encryptedData cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  354. if (cipher != nil && result) {
  355. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  356. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  357. NSString *payload = [cipher base64EncodedStringWithOptions:0];
  358. return payload;
  359. }
  360. return nil;
  361. }
  362. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  363. {
  364. NSMutableData *plain;
  365. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  366. if (range.location == NSNotFound) {
  367. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  368. if (range.location == NSNotFound) {
  369. return nil;
  370. }
  371. }
  372. // Cipher
  373. NSString *cipher = [encrypted substringToIndex:(range.location)];
  374. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  375. // Key
  376. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  377. // Initialization Vector
  378. NSString *initializationVector = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  379. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  380. // Authentication Tag
  381. NSString *authenticationTag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  382. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  383. // Remove Authentication Tag
  384. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  385. BOOL result = [self decryptData:cipherData plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  386. if (plain != nil && result) {
  387. return plain;
  388. }
  389. return nil;
  390. }
  391. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  392. {
  393. NSMutableData *plain;
  394. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:encrypted options:0];
  395. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  396. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  397. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  398. // Remove Authentication Tag
  399. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  400. BOOL result = [self decryptData:cipher plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  401. if (plain != nil && result) {
  402. return plain;
  403. }
  404. return nil;
  405. }
  406. #
  407. #pragma mark - Encrypt / Decrypt file
  408. #
  409. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  410. {
  411. NSData *authenticationTagData;
  412. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directory, fileName]];
  413. if (plainData == nil)
  414. return false;
  415. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  416. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  417. BOOL result = [self encryptFile:[NSString stringWithFormat:@"%@/%@", directory, fileName] fileNameCipher:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  418. if (result) {
  419. *key = [keyData base64EncodedStringWithOptions:0];
  420. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  421. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  422. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  423. return false;
  424. } else {
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  431. {
  432. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  433. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  434. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  435. return [self decryptFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] fileNamePlain:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  436. }
  437. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  438. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  439. #
  440. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  441. #
  442. #
  443. #pragma mark - Encrypt/Decrypt asymmetric
  444. #
  445. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey privateKey:(NSString *)privateKey
  446. {
  447. EVP_PKEY *key = NULL;
  448. int status = 0;
  449. if (publicKey != nil) {
  450. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  451. // Extract real publicKey
  452. BIO *bio = BIO_new_mem_buf(pKey, -1);
  453. if (!bio)
  454. return nil;
  455. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  456. if (!x509)
  457. return nil;
  458. key = X509_get_pubkey(x509);
  459. if (!key)
  460. return nil;
  461. }
  462. if (privateKey != nil) {
  463. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  464. BIO *bio = BIO_new_mem_buf(pKey, -1);
  465. if (!bio)
  466. return nil;
  467. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  468. if (!key)
  469. return nil;
  470. }
  471. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  472. if (!ctx)
  473. return nil;
  474. status = EVP_PKEY_encrypt_init(ctx);
  475. if (status <= 0)
  476. return nil;
  477. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  478. if (status <= 0)
  479. return nil;
  480. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  481. if (status <= 0)
  482. return nil;
  483. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  484. if (status <= 0)
  485. return nil;
  486. unsigned long outLen = 0;
  487. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  488. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  489. if (status <= 0 || outLen == 0)
  490. return nil;
  491. unsigned char *out = (unsigned char *) malloc(outLen);
  492. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  493. if (status <= 0)
  494. return nil;
  495. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  496. if (out)
  497. free(out);
  498. return outData;
  499. }
  500. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  501. {
  502. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  503. int status = 0;
  504. BIO *bio = BIO_new_mem_buf(pKey, -1);
  505. if (!bio)
  506. return nil;
  507. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  508. if (!key)
  509. return nil;
  510. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  511. if (!ctx)
  512. return nil;
  513. status = EVP_PKEY_decrypt_init(ctx);
  514. if (status <= 0)
  515. return nil;
  516. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  517. if (status <= 0)
  518. return nil;
  519. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  520. if (status <= 0)
  521. return nil;
  522. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  523. if (status <= 0)
  524. return nil;
  525. unsigned long outLen = 0;
  526. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  527. if (status <= 0 || outLen == 0)
  528. return nil;
  529. unsigned char *out = (unsigned char *) malloc(outLen);
  530. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  531. if (status <= 0)
  532. return nil;
  533. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  534. if (out)
  535. free(out);
  536. return outData;
  537. }
  538. #
  539. #pragma mark - AES/GCM/NoPadding
  540. #
  541. // Encryption data using GCM mode
  542. - (BOOL)encryptData:(NSData *)plain cipher:(NSMutableData **)cipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  543. {
  544. int status = 0;
  545. int len = 0;
  546. // set up key
  547. len = keyLen;
  548. unsigned char cKey[len];
  549. bzero(cKey, sizeof(cKey));
  550. [key getBytes:cKey length:len];
  551. // set up ivec
  552. len = AES_IVEC_LENGTH;
  553. unsigned char cIV[len];
  554. bzero(cIV, sizeof(cIV));
  555. [initializationVector getBytes:cIV length:len];
  556. // set up tag
  557. len = AES_GCM_TAG_LENGTH;
  558. unsigned char cTag[len];
  559. bzero(cTag, sizeof(cTag));
  560. // Create and initialise the context
  561. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  562. if (!ctx)
  563. return NO;
  564. // Initialise the encryption operation
  565. if (keyLen == AES_KEY_128_LENGTH)
  566. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  567. else if (keyLen == AES_KEY_256_LENGTH)
  568. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  569. if (status <= 0) {
  570. EVP_CIPHER_CTX_free(ctx);
  571. return NO;
  572. }
  573. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  574. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  575. if (status <= 0) {
  576. EVP_CIPHER_CTX_free(ctx);
  577. return NO;
  578. }
  579. // Initialise key and IV
  580. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  581. if (status <= 0) {
  582. EVP_CIPHER_CTX_free(ctx);
  583. return NO;
  584. }
  585. // Provide the message to be encrypted, and obtain the encrypted output
  586. *cipher = [NSMutableData dataWithLength:[plain length]];
  587. unsigned char * cCipher = [*cipher mutableBytes];
  588. int cCipherLen = 0;
  589. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  590. if (status <= 0) {
  591. EVP_CIPHER_CTX_free(ctx);
  592. return NO;
  593. }
  594. // Finalise the encryption
  595. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  596. if (status <= 0) {
  597. EVP_CIPHER_CTX_free(ctx);
  598. return NO;
  599. }
  600. // Get the tag
  601. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  602. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  603. // Append TAG
  604. [*cipher appendData:*authenticationTag];
  605. EVP_CIPHER_CTX_free(ctx);
  606. return status; // OpenSSL uses 1 for success
  607. }
  608. // Encryption file using GCM mode
  609. - (BOOL)encryptFile:(NSString *)fileName fileNameCipher:(NSString *)fileNameCipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  610. {
  611. int status = 0;
  612. int len = 0;
  613. // set up key
  614. len = keyLen;
  615. unsigned char cKey[len];
  616. bzero(cKey, sizeof(cKey));
  617. [key getBytes:cKey length:len];
  618. // set up ivec
  619. len = AES_IVEC_LENGTH;
  620. unsigned char cIV[len];
  621. bzero(cIV, sizeof(cIV));
  622. [initializationVector getBytes:cIV length:len];
  623. // set up tag
  624. len = AES_GCM_TAG_LENGTH;
  625. unsigned char cTag[len];
  626. bzero(cTag, sizeof(cTag));
  627. // Create and initialise the context
  628. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  629. if (!ctx) {
  630. return NO;
  631. }
  632. // Initialise the encryption operation
  633. if (keyLen == AES_KEY_128_LENGTH)
  634. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  635. else if (keyLen == AES_KEY_256_LENGTH)
  636. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  637. if (status <= 0) {
  638. EVP_CIPHER_CTX_free(ctx);
  639. return NO;
  640. }
  641. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  642. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  643. if (status <= 0) {
  644. EVP_CIPHER_CTX_free(ctx);
  645. return NO;
  646. }
  647. // Initialise key and IV
  648. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  649. if (status <= 0) {
  650. EVP_CIPHER_CTX_free(ctx);
  651. return NO;
  652. }
  653. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  654. [inStream open];
  655. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNameCipher append:false];
  656. [outStream open];
  657. Byte buffer[streamBuffer];
  658. NSInteger totalNumberOfBytesWritten = 0;
  659. int cCipherLen = 0;
  660. unsigned char *cCipher;
  661. while ([inStream hasBytesAvailable]) {
  662. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  663. if (bytesRead > 0) {
  664. cCipher = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  665. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  666. if (status <= 0) {
  667. [inStream close];
  668. [outStream close];
  669. EVP_CIPHER_CTX_free(ctx);
  670. return NO;
  671. }
  672. if ([outStream hasSpaceAvailable]) {
  673. totalNumberOfBytesWritten = [outStream write:cCipher maxLength:cCipherLen];
  674. if (totalNumberOfBytesWritten != cCipherLen) {
  675. [inStream close];
  676. [outStream close];
  677. EVP_CIPHER_CTX_free(ctx);
  678. return NO;
  679. }
  680. }
  681. }
  682. }
  683. [inStream close];
  684. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  685. if (status <= 0) {
  686. [outStream close];
  687. EVP_CIPHER_CTX_free(ctx);
  688. return NO;
  689. }
  690. // Get the tag
  691. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  692. if (status <= 0) {
  693. [outStream close];
  694. EVP_CIPHER_CTX_free(ctx);
  695. return NO;
  696. }
  697. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  698. // Append TAG
  699. if ([outStream hasSpaceAvailable]) {
  700. totalNumberOfBytesWritten = [outStream write:cTag maxLength:sizeof(cTag)];
  701. if (totalNumberOfBytesWritten != sizeof(cTag)) {
  702. status = NO;
  703. }
  704. } else {
  705. status = NO;
  706. }
  707. [outStream close];
  708. EVP_CIPHER_CTX_free(ctx);
  709. return status; // OpenSSL uses 1 for success
  710. }
  711. // Decryption data using GCM mode
  712. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  713. {
  714. int status = 0;
  715. int len = 0;
  716. // set up key
  717. len = keyLen;
  718. unsigned char cKey[len];
  719. bzero(cKey, sizeof(cKey));
  720. [key getBytes:cKey length:len];
  721. // set up ivec
  722. len = (int)[initializationVector length];
  723. unsigned char cIV[len];
  724. bzero(cIV, sizeof(cIV));
  725. [initializationVector getBytes:cIV length:len];
  726. // set up tag
  727. len = (int)[authenticationTag length];;
  728. unsigned char cTag[len];
  729. bzero(cTag, sizeof(cTag));
  730. [authenticationTag getBytes:cTag length:len];
  731. // Create and initialise the context
  732. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  733. if (!ctx)
  734. return NO;
  735. // Initialise the decryption operation
  736. if (keyLen == AES_KEY_128_LENGTH)
  737. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  738. else if (keyLen == AES_KEY_256_LENGTH)
  739. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  740. if (status <= 0) {
  741. EVP_CIPHER_CTX_free(ctx);
  742. return NO;
  743. }
  744. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  745. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  746. if (status <= 0) {
  747. EVP_CIPHER_CTX_free(ctx);
  748. return NO;
  749. }
  750. // Initialise key and IV
  751. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  752. if (status <= 0) {
  753. EVP_CIPHER_CTX_free(ctx);
  754. return NO;
  755. }
  756. // Provide the message to be decrypted, and obtain the plaintext output
  757. *plain = [NSMutableData dataWithLength:([cipher length])];
  758. int cPlainLen = 0;
  759. unsigned char * cPlain = [*plain mutableBytes];
  760. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  761. if (status <= 0) {
  762. EVP_CIPHER_CTX_free(ctx);
  763. return NO;
  764. }
  765. // Tag is the last 16 bytes
  766. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  767. if (status <= 0) {
  768. EVP_CIPHER_CTX_free(ctx);
  769. return NO;
  770. }
  771. // Finalise the encryption
  772. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  773. // Free
  774. EVP_CIPHER_CTX_free(ctx);
  775. return status; // OpenSSL uses 1 for success
  776. }
  777. // Decryption file using GCM mode
  778. - (BOOL)decryptFile:(NSString *)fileName fileNamePlain:(NSString *)fileNamePlain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  779. {
  780. int status = 0;
  781. int len = 0;
  782. // set up key
  783. len = keyLen;
  784. unsigned char cKey[len];
  785. bzero(cKey, sizeof(cKey));
  786. [key getBytes:cKey length:len];
  787. // set up ivec
  788. len = (int)[initializationVector length];
  789. unsigned char cIV[len];
  790. bzero(cIV, sizeof(cIV));
  791. [initializationVector getBytes:cIV length:len];
  792. // set up tag
  793. len = (int)[authenticationTag length];;
  794. unsigned char cTag[len];
  795. bzero(cTag, sizeof(cTag));
  796. [authenticationTag getBytes:cTag length:len];
  797. // Create and initialise the context
  798. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  799. if (!ctx)
  800. return NO;
  801. // Initialise the decryption operation
  802. if (keyLen == AES_KEY_128_LENGTH)
  803. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  804. else if (keyLen == AES_KEY_256_LENGTH)
  805. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  806. if (status <= 0) {
  807. EVP_CIPHER_CTX_free(ctx);
  808. return NO;
  809. }
  810. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  811. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  812. if (status <= 0) {
  813. EVP_CIPHER_CTX_free(ctx);
  814. return NO;
  815. }
  816. // Initialise key and IV
  817. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  818. if (status <= 0) {
  819. EVP_CIPHER_CTX_free(ctx);
  820. return NO;
  821. }
  822. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  823. [inStream open];
  824. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNamePlain append:false];
  825. [outStream open];
  826. Byte buffer[streamBuffer];
  827. NSInteger totalNumberOfBytesWritten = 0;
  828. int cPlainLen = 0;
  829. unsigned char *cPlain;
  830. while ([inStream hasBytesAvailable]) {
  831. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  832. if (bytesRead > 0) {
  833. cPlain = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  834. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  835. if (status <= 0) {
  836. [inStream close];
  837. [outStream close];
  838. EVP_CIPHER_CTX_free(ctx);
  839. return NO;
  840. }
  841. if ([outStream hasSpaceAvailable]) {
  842. totalNumberOfBytesWritten = [outStream write:cPlain maxLength:cPlainLen];
  843. if (totalNumberOfBytesWritten != cPlainLen) {
  844. [inStream close];
  845. [outStream close];
  846. EVP_CIPHER_CTX_free(ctx);
  847. return NO;
  848. }
  849. }
  850. }
  851. }
  852. [inStream close];
  853. [outStream close];
  854. // Tag is the last 16 bytes
  855. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  856. if (status <= 0)
  857. return NO;
  858. // Finalise the encryption
  859. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  860. // Free
  861. EVP_CIPHER_CTX_free(ctx);
  862. return status; // OpenSSL uses 1 for success
  863. }
  864. #
  865. #pragma mark - CMS
  866. #
  867. - (NSData *)generateSignatureCMS:(NSData *)data certificate:(NSString *)certificate privateKey:(NSString *)privateKey publicKey:(NSString *)publicKey userId:(NSString *)userId
  868. {
  869. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  870. unsigned char *certKey = (unsigned char *)[certificate UTF8String];
  871. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  872. BIO *certKeyBIO = BIO_new_mem_buf(certKey, -1);
  873. if (!certKeyBIO)
  874. return nil;
  875. X509 *x509 = PEM_read_bio_X509(certKeyBIO, NULL, 0, NULL);
  876. if (!x509)
  877. return nil;
  878. BIO *pkeyBIO = BIO_new_mem_buf(pKey, -1);
  879. EVP_PKEY *key = PEM_read_bio_PrivateKey(pkeyBIO, NULL, NULL, NULL);
  880. if (!key)
  881. return nil;
  882. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  883. CMS_ContentInfo *contentInfo = CMS_sign(x509, key, NULL, dataBIO, CMS_DETACHED);
  884. if (contentInfo == nil)
  885. return nil;
  886. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  887. PEM_write_bio_CMS(printBIO, contentInfo);
  888. BIO *i2dCmsBioOut = BIO_new(BIO_s_mem());
  889. if (i2d_CMS_bio(i2dCmsBioOut, contentInfo) != 1)
  890. return nil;
  891. int len = BIO_pending(i2dCmsBioOut);
  892. char *keyBytes = malloc(len);
  893. BIO_read(i2dCmsBioOut, keyBytes, len);
  894. NSData *i2dCmsData = [NSData dataWithBytes:keyBytes length:len];
  895. // TEST
  896. [self verifySignatureCMS:i2dCmsData data:data publicKey:publicKey userId:userId];
  897. BIO_free(printBIO);
  898. BIO_free(certKeyBIO);
  899. BIO_free(pkeyBIO);
  900. BIO_free(dataBIO);
  901. BIO_free(i2dCmsBioOut);
  902. return i2dCmsData;
  903. }
  904. - (BOOL)verifySignatureCMS:(NSData *)cmsContent data:(NSData *)data publicKey:(NSString *)publicKey userId:(NSString *)userId
  905. {
  906. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  907. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  908. BIO *cmsBIO = BIO_new_mem_buf(cmsContent.bytes, (int)cmsContent.length);
  909. CMS_ContentInfo *contentInfo = d2i_CMS_bio(cmsBIO, NULL);
  910. unsigned char *publicKeyUTF8 = (unsigned char *)[publicKey UTF8String];
  911. BIO *publicKeyBIO = BIO_new_mem_buf(publicKeyUTF8, -1);
  912. EVP_PKEY *pkey = PEM_read_bio_PUBKEY(publicKeyBIO, NULL, NULL, NULL);
  913. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  914. BOOL verifyResult = CMS_verify(contentInfo, NULL, NULL, dataBIO, NULL, CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY);
  915. if (verifyResult) {
  916. STACK_OF(X509) *signers = CMS_get0_signers(contentInfo);
  917. int numSigners = sk_X509_num(signers);
  918. for (int i = 0; i < numSigners; ++i) {
  919. X509 *signer = sk_X509_value(signers, i);
  920. int result = X509_verify(signer, pkey);
  921. if (result <= 0) {
  922. verifyResult = false;
  923. break;
  924. }
  925. int cnDataLength = X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, 0, 0);
  926. cnDataLength += 1;
  927. NSMutableData* cnData = [NSMutableData dataWithLength:cnDataLength];
  928. X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, [cnData mutableBytes], cnDataLength);
  929. NSString *cn = [[NSString alloc] initWithCString:[cnData mutableBytes] encoding:NSUTF8StringEncoding];
  930. if ([userId isEqualToString:cn]) {
  931. verifyResult = true;
  932. break;
  933. } else {
  934. verifyResult = false;
  935. }
  936. }
  937. if (signers) {
  938. sk_X509_free(signers);
  939. }
  940. signers = NULL;
  941. }
  942. BIO_free(dataBIO);
  943. BIO_free(printBIO);
  944. BIO_free(cmsBIO);
  945. BIO_free(publicKeyBIO);
  946. return verifyResult;
  947. }
  948. #
  949. #pragma mark - Utility
  950. #
  951. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  952. {
  953. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  954. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  955. *key = [keyData base64EncodedStringWithOptions:0];
  956. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  957. }
  958. - (NSString *)createSHA256:(NSString *)string
  959. {
  960. const char *cstr = [string cStringUsingEncoding:NSASCIIStringEncoding];
  961. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  962. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  963. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  964. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  965. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  966. [output appendFormat:@"%02x", digest[i]];
  967. return output;
  968. }
  969. - (NSString *)createSHA512:(NSString *)string
  970. {
  971. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  972. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  973. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  974. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  975. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  976. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  977. [output appendFormat:@"%02x", digest[i]];
  978. return output;
  979. }
  980. - (NSData *)generateIV:(int)length
  981. {
  982. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  983. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  984. return ivData;
  985. }
  986. - (NSData *)generateSalt:(int)length
  987. {
  988. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  989. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  990. return saltData;
  991. }
  992. - (NSData *)generateKey:(int)length
  993. {
  994. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  995. unsigned char *pKeyData = [keyData mutableBytes];
  996. RAND_bytes(pKeyData, length);
  997. return keyData;
  998. }
  999. - (NSData *)generateKey
  1000. {
  1001. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  1002. unsigned char *pKeyData = [keyData mutableBytes];
  1003. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  1004. return keyData;
  1005. }
  1006. - (NSString *)getSHA1:(NSString *)input
  1007. {
  1008. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  1009. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  1010. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  1011. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  1012. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  1013. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  1014. [output appendFormat:@"%02x", digest[i]];
  1015. return output;
  1016. }
  1017. - (NSData *)hashValueMD5OfData:(NSData *)data
  1018. {
  1019. MD5_CTX md5Ctx;
  1020. unsigned char hashValue[MD5_DIGEST_LENGTH];
  1021. if(!MD5_Init(&md5Ctx)) {
  1022. return nil;
  1023. }
  1024. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  1025. return nil;
  1026. }
  1027. if (!MD5_Final(hashValue, &md5Ctx)) {
  1028. return nil;
  1029. }
  1030. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  1031. }
  1032. - (NSString *)hexadecimalString:(NSData *)input
  1033. {
  1034. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  1035. if (!dataBuffer) {
  1036. return [NSString string];
  1037. }
  1038. NSUInteger dataLength = [input length];
  1039. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  1040. for (int i = 0; i < dataLength; ++i) {
  1041. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  1042. }
  1043. return [NSString stringWithString:hexString];
  1044. }
  1045. - (NSString *)derToPemPrivateKey:(NSString *)input
  1046. {
  1047. NSInteger substringLength = 65;
  1048. NSMutableString *result = [NSMutableString stringWithString: input];
  1049. for(long i=substringLength;i<=input.length;i++) {
  1050. [result insertString: @"\n" atIndex: i];
  1051. i+=substringLength;
  1052. }
  1053. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  1054. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  1055. return result;
  1056. }
  1057. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  1058. {
  1059. char *buf[256];
  1060. FILE *pFile;
  1061. NSString *pkey_string;
  1062. pFile = fmemopen(buf, sizeof(buf), "w");
  1063. PEM_write_PUBKEY(pFile,pubkey);
  1064. fputc('\0', pFile);
  1065. fclose(pFile);
  1066. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  1067. return pkey_string;
  1068. }
  1069. @end