NCEndToEndEncryption.m 45 KB

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