NCEndToEndEncryption.m 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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 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
  264. {
  265. NSMutableData *privateKeyCipherData = [NSMutableData new];
  266. if (!_privateKeyData) {
  267. if (![self generateCertificateX509WithUserId:userId directory:directory])
  268. return nil;
  269. }
  270. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  271. NSData *saltData = [self generateSalt:AES_SALT_LENGTH];
  272. // Remove all whitespaces from passphrase
  273. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  274. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  275. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  276. NSData *tagData = [NSData new];
  277. /* ENCODE 64 privateKey JAVA compatibility */
  278. NSString *privateKeyBase64 = [_privateKeyData base64EncodedStringWithOptions:0];
  279. NSData *privateKeyBase64Data = [privateKeyBase64 dataUsingEncoding:NSUTF8StringEncoding];
  280. /* --------------------------------------- */
  281. BOOL result = [self encryptData:privateKeyBase64Data cipherData:&privateKeyCipherData keyData:keyData keyLen:AES_KEY_256_LENGTH ivData:ivData tagData:&tagData];
  282. if (result && privateKeyCipherData) {
  283. NSString *privateKeyCipherBase64 = [privateKeyCipherData base64EncodedStringWithOptions:0];
  284. NSString *initVectorBase64 = [ivData base64EncodedStringWithOptions:0];
  285. NSString *saltBase64 = [saltData base64EncodedStringWithOptions:0];
  286. NSString *privateKeyCipherWithInitVectorBase64 = [NSString stringWithFormat:@"%@%@%@%@%@", privateKeyCipherBase64, IV_DELIMITER_ENCODED, initVectorBase64, IV_DELIMITER_ENCODED, saltBase64];
  287. *privateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  288. return privateKeyCipherWithInitVectorBase64;
  289. } else {
  290. return nil;
  291. }
  292. }
  293. - (NSString *)decryptPrivateKey:(NSString *)privateKeyCipher passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey
  294. {
  295. NSMutableData *privateKeyData = [NSMutableData new];
  296. NSString *privateKey = @"";
  297. // Key (data)
  298. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  299. // Split
  300. NSArray *privateKeyCipherArray = [privateKeyCipher componentsSeparatedByString:IV_DELIMITER_ENCODED];
  301. if (privateKeyCipherArray.count != 3) {
  302. privateKeyCipherArray = [privateKeyCipher componentsSeparatedByString:IV_DELIMITER_ENCODED_OLD];
  303. if (privateKeyCipherArray.count != 3) {
  304. return nil;
  305. }
  306. }
  307. NSData *privateKeyCipherData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[0] options:0];
  308. NSString *tagBase64 = [privateKeyCipher substringWithRange:NSMakeRange([(NSString *)privateKeyCipherArray[0] length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  309. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tagBase64 options:0];
  310. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[1] options:0];
  311. NSData *saltData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[2] options:0];
  312. // Remove TAG
  313. privateKeyCipherData = [privateKeyCipherData subdataWithRange:NSMakeRange(0, privateKeyCipherData.length - AES_GCM_TAG_LENGTH)];
  314. // Remove all whitespaces from passphrase
  315. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  316. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  317. BOOL result = [self decryptData:privateKeyCipherData plainData:&privateKeyData keyData:keyData keyLen:AES_KEY_256_LENGTH ivData:ivData tagData:tagData];
  318. if (result && privateKeyData)
  319. privateKey = [self base64DecodeData:privateKeyData];
  320. if (privateKey) {
  321. NSData *encryptData = [self encryptAsymmetricString:ASYMMETRIC_STRING_TEST publicKey:publicKey privateKey:nil];
  322. if (!encryptData)
  323. return nil;
  324. NSData *decryptData = [self decryptAsymmetricData:encryptData privateKey:privateKey];
  325. NSString *decryptString = [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
  326. if (decryptString && [decryptString isEqualToString:ASYMMETRIC_STRING_TEST])
  327. return privateKey;
  328. else
  329. return nil;
  330. } else {
  331. return nil;
  332. }
  333. }
  334. #
  335. #pragma mark - Encrypt / Decrypt Encrypted Json
  336. #
  337. - (NSString *)encryptEncryptedJson:(NSString *)encrypted key:(NSString *)key
  338. {
  339. NSMutableData *cipherData;
  340. NSData *tagData = [NSData new];
  341. NSData *data = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  342. NSString *data64 = [data base64EncodedStringWithOptions:0];
  343. data = [data64 dataUsingEncoding:NSUTF8StringEncoding];
  344. // Key
  345. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  346. // IV
  347. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  348. BOOL result = [self encryptData:data cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  349. if (cipherData != nil && result) {
  350. NSString *cipherBase64 = [cipherData base64EncodedStringWithOptions:0];
  351. NSString *ivBase64 = [ivData base64EncodedStringWithOptions:0];
  352. NSString *encryptedJson = [NSString stringWithFormat:@"%@%@%@", cipherBase64, IV_DELIMITER_ENCODED, ivBase64];
  353. return encryptedJson;
  354. }
  355. return nil;
  356. }
  357. - (NSString *)decryptEncryptedJson:(NSString *)encrypted key:(NSString *)key
  358. {
  359. NSMutableData *plainData;
  360. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  361. if (range.location == NSNotFound) {
  362. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  363. if (range.location == NSNotFound) {
  364. return nil;
  365. }
  366. }
  367. // Cipher
  368. NSString *cipher = [encrypted substringToIndex:(range.location)];
  369. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  370. // Key
  371. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  372. // IV
  373. NSString *iv = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  374. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:iv options:0];
  375. // TAG
  376. NSString *tag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  377. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tag options:0];
  378. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  379. if (plainData != nil && result) {
  380. /* DENCODE 64 JAVA compatibility */
  381. NSString *plain = [self base64DecodeData:plainData];
  382. /* ---------------------------------------- */
  383. return plain;
  384. }
  385. return nil;
  386. }
  387. - (NSData *)decryptEncryptedJsonV12:(NSString *)encrypted key:(NSString *)key
  388. {
  389. NSMutableData *plainData;
  390. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  391. if (range.location == NSNotFound) {
  392. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  393. if (range.location == NSNotFound) {
  394. return nil;
  395. }
  396. }
  397. // Cipher
  398. NSString *cipher = [encrypted substringToIndex:(range.location)];
  399. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  400. // Key
  401. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  402. // IV
  403. NSString *iv = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  404. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:iv options:0];
  405. // TAG
  406. NSString *tag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  407. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tag options:0];
  408. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  409. if (plainData != nil && result) {
  410. return plainData;
  411. }
  412. return nil;
  413. }
  414. #
  415. #pragma mark - Encrypt / Decrypt file
  416. #
  417. - (void)encryptkey:(NSString **)key initializationVector:(NSString **)initializationVector
  418. {
  419. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  420. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  421. *key = [keyData base64EncodedStringWithOptions:0];
  422. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  423. }
  424. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  425. {
  426. NSMutableData *cipherData;
  427. NSData *tagData;
  428. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directory, fileName]];
  429. if (plainData == nil)
  430. return false;
  431. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  432. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  433. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  434. if (cipherData != nil && result) {
  435. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] atomically:YES];
  436. *key = [keyData base64EncodedStringWithOptions:0];
  437. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  438. *authenticationTag = [tagData base64EncodedStringWithOptions:0];
  439. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  440. return false;
  441. } else {
  442. return true;
  443. }
  444. }
  445. return false;
  446. }
  447. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  448. {
  449. NSMutableData *plainData;
  450. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  451. if (cipherData == nil)
  452. return false;
  453. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  454. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  455. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  456. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  457. if (plainData != nil && result) {
  458. [plainData writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] atomically:YES];
  459. return true;
  460. }
  461. return false;
  462. }
  463. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  464. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  465. #
  466. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  467. #
  468. #
  469. #pragma mark - Asymmetric Encrypt/Decrypt String
  470. #
  471. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey privateKey:(NSString *)privateKey
  472. {
  473. EVP_PKEY *key = NULL;
  474. int status = 0;
  475. if (publicKey != nil) {
  476. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  477. // Extract real publicKey
  478. BIO *bio = BIO_new_mem_buf(pKey, -1);
  479. if (!bio)
  480. return nil;
  481. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  482. if (!x509)
  483. return nil;
  484. key = X509_get_pubkey(x509);
  485. if (!key)
  486. return nil;
  487. }
  488. if (privateKey != nil) {
  489. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  490. BIO *bio = BIO_new_mem_buf(pKey, -1);
  491. if (!bio)
  492. return nil;
  493. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  494. if (!key)
  495. return nil;
  496. }
  497. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  498. if (!ctx)
  499. return nil;
  500. status = EVP_PKEY_encrypt_init(ctx);
  501. if (status <= 0)
  502. return nil;
  503. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  504. if (status <= 0)
  505. return nil;
  506. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  507. if (status <= 0)
  508. return nil;
  509. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  510. if (status <= 0)
  511. return nil;
  512. unsigned long outLen = 0;
  513. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  514. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  515. if (status <= 0 || outLen == 0)
  516. return nil;
  517. unsigned char *out = (unsigned char *) malloc(outLen);
  518. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  519. if (status <= 0)
  520. return nil;
  521. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  522. if (out)
  523. free(out);
  524. return outData;
  525. }
  526. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  527. {
  528. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  529. int status = 0;
  530. BIO *bio = BIO_new_mem_buf(pKey, -1);
  531. if (!bio)
  532. return nil;
  533. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  534. if (!key)
  535. return nil;
  536. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  537. if (!ctx)
  538. return nil;
  539. status = EVP_PKEY_decrypt_init(ctx);
  540. if (status <= 0)
  541. return nil;
  542. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  543. if (status <= 0)
  544. return nil;
  545. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  546. if (status <= 0)
  547. return nil;
  548. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  549. if (status <= 0)
  550. return nil;
  551. unsigned long outLen = 0;
  552. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  553. if (status <= 0 || outLen == 0)
  554. return nil;
  555. unsigned char *out = (unsigned char *) malloc(outLen);
  556. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  557. if (status <= 0)
  558. return nil;
  559. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  560. //NSString *out64 = [outData base64EncodedStringWithOptions:0];
  561. if (out)
  562. free(out);
  563. return outData;
  564. }
  565. #
  566. #pragma mark - AES/GCM/NoPadding
  567. #
  568. // Encryption using GCM mode
  569. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData **)tagData
  570. {
  571. int status = 0;
  572. int len = 0;
  573. // set up key
  574. len = keyLen;
  575. unsigned char cKey[len];
  576. bzero(cKey, sizeof(cKey));
  577. [keyData getBytes:cKey length:len];
  578. // set up ivec
  579. len = AES_IVEC_LENGTH;
  580. unsigned char cIV[len];
  581. bzero(cIV, sizeof(cIV));
  582. [ivData getBytes:cIV length:len];
  583. // set up tag
  584. len = AES_GCM_TAG_LENGTH;
  585. unsigned char cTag[len];
  586. bzero(cTag, sizeof(cTag));
  587. // Create and initialise the context
  588. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  589. if (!ctx)
  590. return NO;
  591. // Initialise the encryption operation
  592. if (keyLen == AES_KEY_128_LENGTH)
  593. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  594. else if (keyLen == AES_KEY_256_LENGTH)
  595. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  596. if (status <= 0)
  597. return NO;
  598. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  599. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  600. if (status <= 0)
  601. return NO;
  602. // Initialise key and IV
  603. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  604. if (status <= 0)
  605. return NO;
  606. // Provide the message to be encrypted, and obtain the encrypted output
  607. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  608. unsigned char * cCipher = [*cipherData mutableBytes];
  609. int cCipherLen = 0;
  610. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plainData bytes], (int)[plainData length]);
  611. if (status <= 0)
  612. return NO;
  613. // Finalise the encryption
  614. len = cCipherLen;
  615. status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  616. if (status <= 0)
  617. return NO;
  618. // Get the tag
  619. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  620. *tagData = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  621. // Append TAG
  622. [*cipherData appendData:*tagData];
  623. // Free
  624. EVP_CIPHER_CTX_free(ctx);
  625. return status; // OpenSSL uses 1 for success
  626. }
  627. // Decryption using GCM mode
  628. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData *)tagData
  629. {
  630. int status = 0;
  631. int len = 0;
  632. // set up key
  633. len = keyLen;
  634. unsigned char cKey[len];
  635. bzero(cKey, sizeof(cKey));
  636. [keyData getBytes:cKey length:len];
  637. // set up ivec
  638. len = (int)[ivData length];
  639. unsigned char cIV[len];
  640. bzero(cIV, sizeof(cIV));
  641. [ivData getBytes:cIV length:len];
  642. // set up tag
  643. len = (int)[tagData length];;
  644. unsigned char cTag[len];
  645. bzero(cTag, sizeof(cTag));
  646. [tagData getBytes:cTag length:len];
  647. // Create and initialise the context
  648. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  649. if (!ctx)
  650. return NO;
  651. // Initialise the decryption operation
  652. if (keyLen == AES_KEY_128_LENGTH)
  653. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  654. else if (keyLen == AES_KEY_256_LENGTH)
  655. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  656. if (status <= 0)
  657. return NO;
  658. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  659. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  660. if (status <= 0)
  661. return NO;
  662. // Initialise key and IV
  663. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  664. if (status <= 0)
  665. return NO;
  666. // Remove TAG JAVA compatibility
  667. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  668. // -----------------------------
  669. // Provide the message to be decrypted, and obtain the plaintext output
  670. *plainData = [NSMutableData dataWithLength:([cipherData length])];
  671. int cPlainLen = 0;
  672. unsigned char * cPlain = [*plainData mutableBytes];
  673. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipherData bytes], (int)([cipherData length]));
  674. if (status <= 0)
  675. return NO;
  676. // Tag is the last 16 bytes
  677. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  678. if (status <= 0)
  679. return NO;
  680. // Finalise the encryption
  681. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  682. // Free
  683. EVP_CIPHER_CTX_free(ctx);
  684. return status; // OpenSSL uses 1 for success
  685. }
  686. #
  687. #pragma mark - Utility
  688. #
  689. - (NSString *)createSHA512:(NSString *)string
  690. {
  691. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  692. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  693. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  694. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  695. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  696. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  697. [output appendFormat:@"%02x", digest[i]];
  698. return output;
  699. }
  700. - (NSData *)generateIV:(int)length
  701. {
  702. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  703. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  704. return ivData;
  705. }
  706. - (NSData *)generateSalt:(int)length
  707. {
  708. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  709. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  710. return saltData;
  711. }
  712. - (NSData *)generateKey:(int)length
  713. {
  714. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  715. unsigned char *pKeyData = [keyData mutableBytes];
  716. RAND_bytes(pKeyData, length);
  717. return keyData;
  718. }
  719. - (NSString *)getSHA1:(NSString *)input
  720. {
  721. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  722. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  723. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  724. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  725. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  726. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  727. [output appendFormat:@"%02x", digest[i]];
  728. return output;
  729. }
  730. - (NSData *)hashValueMD5OfData:(NSData *)data
  731. {
  732. MD5_CTX md5Ctx;
  733. unsigned char hashValue[MD5_DIGEST_LENGTH];
  734. if(!MD5_Init(&md5Ctx)) {
  735. return nil;
  736. }
  737. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  738. return nil;
  739. }
  740. if (!MD5_Final(hashValue, &md5Ctx)) {
  741. return nil;
  742. }
  743. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  744. }
  745. - (NSString *)hexadecimalString:(NSData *)input
  746. {
  747. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  748. if (!dataBuffer) {
  749. return [NSString string];
  750. }
  751. NSUInteger dataLength = [input length];
  752. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  753. for (int i = 0; i < dataLength; ++i) {
  754. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  755. }
  756. return [NSString stringWithString:hexString];
  757. }
  758. /*
  759. - (NSData *)base64Encode:(NSData *)input
  760. {
  761. void *bytes;
  762. BIO *buffer = BIO_new(BIO_s_mem());
  763. BIO *base64 = BIO_new(BIO_f_base64());
  764. buffer = BIO_push(base64, buffer);
  765. BIO_write(buffer, [input bytes], (int)[input length]);
  766. NSUInteger length = BIO_get_mem_data(buffer, &bytes);
  767. NSString *string = [[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding];
  768. BIO_free_all(buffer);
  769. return [string dataUsingEncoding:NSUTF8StringEncoding];
  770. }
  771. */
  772. - (NSString *)base64DecodeData:(NSData *)input
  773. {
  774. NSMutableData *data = [NSMutableData data];
  775. BIO *buffer = BIO_new_mem_buf((void *)[input bytes], (int)[input length]);
  776. BIO *base64 = BIO_new(BIO_f_base64());
  777. buffer = BIO_push(base64, buffer);
  778. BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
  779. char chars[input.length];
  780. int length = BIO_read(buffer, chars, (int)sizeof(chars));
  781. while (length > 0) {
  782. [data appendBytes:chars length:length];
  783. length = BIO_read(buffer, chars, (int)sizeof(chars));
  784. }
  785. BIO_free_all(buffer);
  786. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  787. }
  788. - (NSData *)base64DecodeString:(NSString *)input
  789. {
  790. NSMutableData *data = [NSMutableData data];
  791. NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding];
  792. BIO *buffer = BIO_new_mem_buf((void *)[inputData bytes], (int)[inputData length]);
  793. BIO *base64 = BIO_new(BIO_f_base64());
  794. buffer = BIO_push(base64, buffer);
  795. BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
  796. char chars[input.length];
  797. int length = BIO_read(buffer, chars, (int)sizeof(chars));
  798. while (length > 0) {
  799. [data appendBytes:chars length:length];
  800. length = BIO_read(buffer, chars, (int)sizeof(chars));
  801. }
  802. BIO_free_all(buffer);
  803. return data;
  804. }
  805. - (NSString *)derToPemPrivateKey:(NSString *)input
  806. {
  807. NSInteger substringLength = 65;
  808. NSMutableString *result = [NSMutableString stringWithString: input];
  809. for(long i=substringLength;i<=input.length;i++) {
  810. [result insertString: @"\n" atIndex: i];
  811. i+=substringLength;
  812. }
  813. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  814. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  815. return result;
  816. }
  817. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  818. {
  819. char *buf[256];
  820. FILE *pFile;
  821. NSString *pkey_string;
  822. pFile = fmemopen(buf, sizeof(buf), "w");
  823. PEM_write_PUBKEY(pFile,pubkey);
  824. fputc('\0', pFile);
  825. fclose(pFile);
  826. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  827. return pkey_string;
  828. }
  829. @end