NCEndToEndEncryption.m 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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 *keyData = [self generateKey:AES_KEY_128_LENGTH];
  413. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  414. BOOL result = [self encryptFile:[NSString stringWithFormat:@"%@/%@", directory, fileName] fileNameCipher:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  415. if (result) {
  416. *key = [keyData base64EncodedStringWithOptions:0];
  417. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  418. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  419. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  420. return false;
  421. } else {
  422. return true;
  423. }
  424. }
  425. return false;
  426. }
  427. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  428. {
  429. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  430. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  431. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  432. 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];
  433. }
  434. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  435. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  436. #
  437. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  438. #
  439. #
  440. #pragma mark - Encrypt/Decrypt asymmetric
  441. #
  442. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey privateKey:(NSString *)privateKey
  443. {
  444. EVP_PKEY *key = NULL;
  445. int status = 0;
  446. if (publicKey != nil) {
  447. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  448. // Extract real publicKey
  449. BIO *bio = BIO_new_mem_buf(pKey, -1);
  450. if (!bio)
  451. return nil;
  452. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  453. if (!x509)
  454. return nil;
  455. key = X509_get_pubkey(x509);
  456. if (!key)
  457. return nil;
  458. }
  459. if (privateKey != nil) {
  460. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  461. BIO *bio = BIO_new_mem_buf(pKey, -1);
  462. if (!bio)
  463. return nil;
  464. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  465. if (!key)
  466. return nil;
  467. }
  468. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  469. if (!ctx)
  470. return nil;
  471. status = EVP_PKEY_encrypt_init(ctx);
  472. if (status <= 0)
  473. return nil;
  474. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  475. if (status <= 0)
  476. return nil;
  477. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  478. if (status <= 0)
  479. return nil;
  480. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  481. if (status <= 0)
  482. return nil;
  483. unsigned long outLen = 0;
  484. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  485. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  486. if (status <= 0 || outLen == 0)
  487. return nil;
  488. unsigned char *out = (unsigned char *) malloc(outLen);
  489. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  490. if (status <= 0)
  491. return nil;
  492. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  493. if (out)
  494. free(out);
  495. return outData;
  496. }
  497. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  498. {
  499. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  500. int status = 0;
  501. BIO *bio = BIO_new_mem_buf(pKey, -1);
  502. if (!bio)
  503. return nil;
  504. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  505. if (!key)
  506. return nil;
  507. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  508. if (!ctx)
  509. return nil;
  510. status = EVP_PKEY_decrypt_init(ctx);
  511. if (status <= 0)
  512. return nil;
  513. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  514. if (status <= 0)
  515. return nil;
  516. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  517. if (status <= 0)
  518. return nil;
  519. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  520. if (status <= 0)
  521. return nil;
  522. unsigned long outLen = 0;
  523. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  524. if (status <= 0 || outLen == 0)
  525. return nil;
  526. unsigned char *out = (unsigned char *) malloc(outLen);
  527. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  528. if (status <= 0)
  529. return nil;
  530. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  531. if (out)
  532. free(out);
  533. return outData;
  534. }
  535. #
  536. #pragma mark - AES/GCM/NoPadding
  537. #
  538. // Encryption data using GCM mode
  539. - (BOOL)encryptData:(NSData *)plain cipher:(NSMutableData **)cipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  540. {
  541. int status = 0;
  542. int len = 0;
  543. // set up key
  544. len = keyLen;
  545. unsigned char cKey[len];
  546. bzero(cKey, sizeof(cKey));
  547. [key getBytes:cKey length:len];
  548. // set up ivec
  549. len = AES_IVEC_LENGTH;
  550. unsigned char cIV[len];
  551. bzero(cIV, sizeof(cIV));
  552. [initializationVector getBytes:cIV length:len];
  553. // set up tag
  554. len = AES_GCM_TAG_LENGTH;
  555. unsigned char cTag[len];
  556. bzero(cTag, sizeof(cTag));
  557. // Create and initialise the context
  558. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  559. if (!ctx)
  560. return NO;
  561. // Initialise the encryption operation
  562. if (keyLen == AES_KEY_128_LENGTH)
  563. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  564. else if (keyLen == AES_KEY_256_LENGTH)
  565. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  566. if (status <= 0) {
  567. EVP_CIPHER_CTX_free(ctx);
  568. return NO;
  569. }
  570. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  571. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  572. if (status <= 0) {
  573. EVP_CIPHER_CTX_free(ctx);
  574. return NO;
  575. }
  576. // Initialise key and IV
  577. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  578. if (status <= 0) {
  579. EVP_CIPHER_CTX_free(ctx);
  580. return NO;
  581. }
  582. // Provide the message to be encrypted, and obtain the encrypted output
  583. *cipher = [NSMutableData dataWithLength:[plain length]];
  584. unsigned char * cCipher = [*cipher mutableBytes];
  585. int cCipherLen = 0;
  586. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  587. if (status <= 0) {
  588. EVP_CIPHER_CTX_free(ctx);
  589. return NO;
  590. }
  591. // Finalise the encryption
  592. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  593. if (status <= 0) {
  594. EVP_CIPHER_CTX_free(ctx);
  595. return NO;
  596. }
  597. // Get the tag
  598. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  599. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  600. // Append TAG
  601. [*cipher appendData:*authenticationTag];
  602. EVP_CIPHER_CTX_free(ctx);
  603. return status; // OpenSSL uses 1 for success
  604. }
  605. // Encryption file using GCM mode
  606. - (BOOL)encryptFile:(NSString *)fileName fileNameCipher:(NSString *)fileNameCipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  607. {
  608. int status = 0;
  609. int len = 0;
  610. // set up key
  611. len = keyLen;
  612. unsigned char cKey[len];
  613. bzero(cKey, sizeof(cKey));
  614. [key getBytes:cKey length:len];
  615. // set up ivec
  616. len = AES_IVEC_LENGTH;
  617. unsigned char cIV[len];
  618. bzero(cIV, sizeof(cIV));
  619. [initializationVector getBytes:cIV length:len];
  620. // set up tag
  621. len = AES_GCM_TAG_LENGTH;
  622. unsigned char cTag[len];
  623. bzero(cTag, sizeof(cTag));
  624. // Create and initialise the context
  625. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  626. if (!ctx) {
  627. return NO;
  628. }
  629. // Initialise the encryption operation
  630. if (keyLen == AES_KEY_128_LENGTH)
  631. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  632. else if (keyLen == AES_KEY_256_LENGTH)
  633. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  634. if (status <= 0) {
  635. EVP_CIPHER_CTX_free(ctx);
  636. return NO;
  637. }
  638. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  639. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  640. if (status <= 0) {
  641. EVP_CIPHER_CTX_free(ctx);
  642. return NO;
  643. }
  644. // Initialise key and IV
  645. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  646. if (status <= 0) {
  647. EVP_CIPHER_CTX_free(ctx);
  648. return NO;
  649. }
  650. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  651. [inStream open];
  652. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNameCipher append:false];
  653. [outStream open];
  654. Byte buffer[streamBuffer];
  655. NSInteger totalNumberOfBytesWritten = 0;
  656. int cCipherLen = 0;
  657. unsigned char *cCipher;
  658. while ([inStream hasBytesAvailable]) {
  659. @autoreleasepool {
  660. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  661. if (bytesRead > 0) {
  662. cCipher = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  663. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  664. if (status <= 0) {
  665. [inStream close];
  666. [outStream close];
  667. EVP_CIPHER_CTX_free(ctx);
  668. return NO;
  669. }
  670. if ([outStream hasSpaceAvailable]) {
  671. totalNumberOfBytesWritten = [outStream write:cCipher maxLength:cCipherLen];
  672. if (totalNumberOfBytesWritten != cCipherLen) {
  673. [inStream close];
  674. [outStream close];
  675. EVP_CIPHER_CTX_free(ctx);
  676. return NO;
  677. }
  678. }
  679. }
  680. }
  681. }
  682. [inStream close];
  683. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  684. if (status <= 0) {
  685. [outStream close];
  686. EVP_CIPHER_CTX_free(ctx);
  687. return NO;
  688. }
  689. // Get the tag
  690. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  691. if (status <= 0) {
  692. [outStream close];
  693. EVP_CIPHER_CTX_free(ctx);
  694. return NO;
  695. }
  696. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  697. // Append TAG
  698. if ([outStream hasSpaceAvailable]) {
  699. totalNumberOfBytesWritten = [outStream write:cTag maxLength:sizeof(cTag)];
  700. if (totalNumberOfBytesWritten != sizeof(cTag)) {
  701. status = NO;
  702. }
  703. } else {
  704. status = NO;
  705. }
  706. [outStream close];
  707. EVP_CIPHER_CTX_free(ctx);
  708. return status; // OpenSSL uses 1 for success
  709. }
  710. // Decryption data using GCM mode
  711. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  712. {
  713. int status = 0;
  714. int len = 0;
  715. // set up key
  716. len = keyLen;
  717. unsigned char cKey[len];
  718. bzero(cKey, sizeof(cKey));
  719. [key getBytes:cKey length:len];
  720. // set up ivec
  721. len = (int)[initializationVector length];
  722. unsigned char cIV[len];
  723. bzero(cIV, sizeof(cIV));
  724. [initializationVector getBytes:cIV length:len];
  725. // set up tag
  726. len = (int)[authenticationTag length];;
  727. unsigned char cTag[len];
  728. bzero(cTag, sizeof(cTag));
  729. [authenticationTag getBytes:cTag length:len];
  730. // Create and initialise the context
  731. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  732. if (!ctx)
  733. return NO;
  734. // Initialise the decryption operation
  735. if (keyLen == AES_KEY_128_LENGTH)
  736. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  737. else if (keyLen == AES_KEY_256_LENGTH)
  738. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  739. if (status <= 0) {
  740. EVP_CIPHER_CTX_free(ctx);
  741. return NO;
  742. }
  743. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  744. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  745. if (status <= 0) {
  746. EVP_CIPHER_CTX_free(ctx);
  747. return NO;
  748. }
  749. // Initialise key and IV
  750. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  751. if (status <= 0) {
  752. EVP_CIPHER_CTX_free(ctx);
  753. return NO;
  754. }
  755. // Provide the message to be decrypted, and obtain the plaintext output
  756. *plain = [NSMutableData dataWithLength:([cipher length])];
  757. int cPlainLen = 0;
  758. unsigned char * cPlain = [*plain mutableBytes];
  759. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  760. if (status <= 0) {
  761. EVP_CIPHER_CTX_free(ctx);
  762. return NO;
  763. }
  764. // Tag is the last 16 bytes
  765. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  766. if (status <= 0) {
  767. EVP_CIPHER_CTX_free(ctx);
  768. return NO;
  769. }
  770. // Finalise the encryption
  771. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  772. // Free
  773. EVP_CIPHER_CTX_free(ctx);
  774. return status; // OpenSSL uses 1 for success
  775. }
  776. // Decryption file using GCM mode
  777. - (BOOL)decryptFile:(NSString *)fileName fileNamePlain:(NSString *)fileNamePlain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  778. {
  779. int status = 0;
  780. int len = 0;
  781. // set up key
  782. len = keyLen;
  783. unsigned char cKey[len];
  784. bzero(cKey, sizeof(cKey));
  785. [key getBytes:cKey length:len];
  786. // set up ivec
  787. len = (int)[initializationVector length];
  788. unsigned char cIV[len];
  789. bzero(cIV, sizeof(cIV));
  790. [initializationVector getBytes:cIV length:len];
  791. // set up tag
  792. len = (int)[authenticationTag length];;
  793. unsigned char cTag[len];
  794. bzero(cTag, sizeof(cTag));
  795. [authenticationTag getBytes:cTag length:len];
  796. // Create and initialise the context
  797. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  798. if (!ctx)
  799. return NO;
  800. // Initialise the decryption operation
  801. if (keyLen == AES_KEY_128_LENGTH)
  802. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  803. else if (keyLen == AES_KEY_256_LENGTH)
  804. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  805. if (status <= 0) {
  806. EVP_CIPHER_CTX_free(ctx);
  807. return NO;
  808. }
  809. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  810. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  811. if (status <= 0) {
  812. EVP_CIPHER_CTX_free(ctx);
  813. return NO;
  814. }
  815. // Initialise key and IV
  816. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  817. if (status <= 0) {
  818. EVP_CIPHER_CTX_free(ctx);
  819. return NO;
  820. }
  821. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  822. [inStream open];
  823. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNamePlain append:false];
  824. [outStream open];
  825. Byte buffer[streamBuffer];
  826. NSInteger totalNumberOfBytesWritten = 0;
  827. int cPlainLen = 0;
  828. unsigned char *cPlain;
  829. while ([inStream hasBytesAvailable]) {
  830. @autoreleasepool {
  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. }
  853. [inStream close];
  854. [outStream close];
  855. // Tag is the last 16 bytes
  856. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  857. if (status <= 0)
  858. return NO;
  859. // Finalise the encryption
  860. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  861. // Free
  862. EVP_CIPHER_CTX_free(ctx);
  863. return status; // OpenSSL uses 1 for success
  864. }
  865. #
  866. #pragma mark - CMS
  867. #
  868. - (NSData *)generateSignatureCMS:(NSData *)data certificate:(NSString *)certificate privateKey:(NSString *)privateKey publicKey:(NSString *)publicKey userId:(NSString *)userId
  869. {
  870. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  871. unsigned char *certKey = (unsigned char *)[certificate UTF8String];
  872. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  873. BIO *certKeyBIO = BIO_new_mem_buf(certKey, -1);
  874. if (!certKeyBIO)
  875. return nil;
  876. X509 *x509 = PEM_read_bio_X509(certKeyBIO, NULL, 0, NULL);
  877. if (!x509)
  878. return nil;
  879. BIO *pkeyBIO = BIO_new_mem_buf(pKey, -1);
  880. EVP_PKEY *key = PEM_read_bio_PrivateKey(pkeyBIO, NULL, NULL, NULL);
  881. if (!key)
  882. return nil;
  883. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  884. CMS_ContentInfo *contentInfo = CMS_sign(x509, key, NULL, dataBIO, CMS_DETACHED);
  885. if (contentInfo == nil)
  886. return nil;
  887. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  888. PEM_write_bio_CMS(printBIO, contentInfo);
  889. BIO *i2dCmsBioOut = BIO_new(BIO_s_mem());
  890. if (i2d_CMS_bio(i2dCmsBioOut, contentInfo) != 1)
  891. return nil;
  892. int len = BIO_pending(i2dCmsBioOut);
  893. char *keyBytes = malloc(len);
  894. BIO_read(i2dCmsBioOut, keyBytes, len);
  895. NSData *i2dCmsData = [NSData dataWithBytes:keyBytes length:len];
  896. // TEST
  897. [self verifySignatureCMS:i2dCmsData data:data publicKey:publicKey userId:userId];
  898. BIO_free(printBIO);
  899. BIO_free(certKeyBIO);
  900. BIO_free(pkeyBIO);
  901. BIO_free(dataBIO);
  902. BIO_free(i2dCmsBioOut);
  903. return i2dCmsData;
  904. }
  905. - (BOOL)verifySignatureCMS:(NSData *)cmsContent data:(NSData *)data publicKey:(NSString *)publicKey userId:(NSString *)userId
  906. {
  907. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  908. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  909. BIO *cmsBIO = BIO_new_mem_buf(cmsContent.bytes, (int)cmsContent.length);
  910. CMS_ContentInfo *contentInfo = d2i_CMS_bio(cmsBIO, NULL);
  911. unsigned char *publicKeyUTF8 = (unsigned char *)[publicKey UTF8String];
  912. BIO *publicKeyBIO = BIO_new_mem_buf(publicKeyUTF8, -1);
  913. EVP_PKEY *pkey = PEM_read_bio_PUBKEY(publicKeyBIO, NULL, NULL, NULL);
  914. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  915. BOOL verifyResult = CMS_verify(contentInfo, NULL, NULL, dataBIO, NULL, CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY);
  916. if (verifyResult) {
  917. STACK_OF(X509) *signers = CMS_get0_signers(contentInfo);
  918. int numSigners = sk_X509_num(signers);
  919. for (int i = 0; i < numSigners; ++i) {
  920. X509 *signer = sk_X509_value(signers, i);
  921. int result = X509_verify(signer, pkey);
  922. if (result <= 0) {
  923. verifyResult = false;
  924. break;
  925. }
  926. int cnDataLength = X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, 0, 0);
  927. cnDataLength += 1;
  928. NSMutableData* cnData = [NSMutableData dataWithLength:cnDataLength];
  929. X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, [cnData mutableBytes], cnDataLength);
  930. NSString *cn = [[NSString alloc] initWithCString:[cnData mutableBytes] encoding:NSUTF8StringEncoding];
  931. if ([userId isEqualToString:cn]) {
  932. verifyResult = true;
  933. break;
  934. } else {
  935. verifyResult = false;
  936. }
  937. }
  938. if (signers) {
  939. sk_X509_free(signers);
  940. }
  941. signers = NULL;
  942. }
  943. BIO_free(dataBIO);
  944. BIO_free(printBIO);
  945. BIO_free(cmsBIO);
  946. BIO_free(publicKeyBIO);
  947. return verifyResult;
  948. }
  949. #
  950. #pragma mark - Utility
  951. #
  952. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  953. {
  954. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  955. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  956. *key = [keyData base64EncodedStringWithOptions:0];
  957. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  958. }
  959. - (NSString *)createSHA256:(NSString *)string
  960. {
  961. const char *cstr = [string cStringUsingEncoding:NSASCIIStringEncoding];
  962. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  963. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  964. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  965. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  966. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  967. [output appendFormat:@"%02x", digest[i]];
  968. return output;
  969. }
  970. - (NSString *)createSHA512:(NSString *)string
  971. {
  972. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  973. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  974. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  975. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  976. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  977. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  978. [output appendFormat:@"%02x", digest[i]];
  979. return output;
  980. }
  981. - (NSData *)generateIV:(int)length
  982. {
  983. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  984. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  985. return ivData;
  986. }
  987. - (NSData *)generateSalt:(int)length
  988. {
  989. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  990. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  991. return saltData;
  992. }
  993. - (NSData *)generateKey:(int)length
  994. {
  995. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  996. unsigned char *pKeyData = [keyData mutableBytes];
  997. RAND_bytes(pKeyData, length);
  998. return keyData;
  999. }
  1000. - (NSData *)generateKey
  1001. {
  1002. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  1003. unsigned char *pKeyData = [keyData mutableBytes];
  1004. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  1005. return keyData;
  1006. }
  1007. - (NSString *)getSHA1:(NSString *)input
  1008. {
  1009. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  1010. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  1011. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  1012. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  1013. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  1014. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  1015. [output appendFormat:@"%02x", digest[i]];
  1016. return output;
  1017. }
  1018. - (NSData *)hashValueMD5OfData:(NSData *)data
  1019. {
  1020. MD5_CTX md5Ctx;
  1021. unsigned char hashValue[MD5_DIGEST_LENGTH];
  1022. if(!MD5_Init(&md5Ctx)) {
  1023. return nil;
  1024. }
  1025. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  1026. return nil;
  1027. }
  1028. if (!MD5_Final(hashValue, &md5Ctx)) {
  1029. return nil;
  1030. }
  1031. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  1032. }
  1033. - (NSString *)hexadecimalString:(NSData *)input
  1034. {
  1035. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  1036. if (!dataBuffer) {
  1037. return [NSString string];
  1038. }
  1039. NSUInteger dataLength = [input length];
  1040. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  1041. for (int i = 0; i < dataLength; ++i) {
  1042. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  1043. }
  1044. return [NSString stringWithString:hexString];
  1045. }
  1046. - (NSString *)derToPemPrivateKey:(NSString *)input
  1047. {
  1048. NSInteger substringLength = 65;
  1049. NSMutableString *result = [NSMutableString stringWithString: input];
  1050. for(long i=substringLength;i<=input.length;i++) {
  1051. [result insertString: @"\n" atIndex: i];
  1052. i+=substringLength;
  1053. }
  1054. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  1055. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  1056. return result;
  1057. }
  1058. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  1059. {
  1060. char *buf[256];
  1061. FILE *pFile;
  1062. NSString *pkey_string;
  1063. pFile = fmemopen(buf, sizeof(buf), "w");
  1064. PEM_write_PUBKEY(pFile,pubkey);
  1065. fputc('\0', pFile);
  1066. fclose(pFile);
  1067. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  1068. return pkey_string;
  1069. }
  1070. @end