NCEndToEndEncryption.m 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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 @"|" //@"fA==" // "|" base64 encoded
  31. #define PBKDF2_INTERACTION_COUNT 1024
  32. #define PBKDF2_KEY_LENGTH 256
  33. //#define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  34. #define ASYMMETRIC_STRING_TEST @"Nextcloud a safe home for all your data"
  35. #define fileNameCertificate @"cert.pem"
  36. #define fileNameCSR @"csr.pem"
  37. #define fileNamePrivateKey @"privateKey.pem"
  38. #define fileNamePubliceKey @"publicKey.pem"
  39. #define AES_KEY_128_LENGTH 16
  40. #define AES_KEY_256_LENGTH 32
  41. #define AES_IVEC_LENGTH 16
  42. #define AES_GCM_TAG_LENGTH 16
  43. #define AES_SALT_LENGTH 40
  44. @interface NCEndToEndEncryption ()
  45. {
  46. NSData *_privateKeyData;
  47. NSData *_publicKeyData;
  48. NSData *_csrData;
  49. }
  50. @end
  51. @implementation NCEndToEndEncryption
  52. //Singleton
  53. + (instancetype)sharedManager {
  54. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  55. static dispatch_once_t onceToken;
  56. dispatch_once(&onceToken, ^{
  57. NCEndToEndEncryption = [self new];
  58. });
  59. return NCEndToEndEncryption;
  60. }
  61. #
  62. #pragma mark - Generate Certificate X509 - CSR - Private Key
  63. #
  64. - (BOOL)generateCertificateX509WithUserID:(NSString *)userID directory:(NSString *)directory
  65. {
  66. OPENSSL_init();
  67. EVP_PKEY * pkey;
  68. pkey = EVP_PKEY_new();
  69. RSA * rsa;
  70. rsa = RSA_generate_key(
  71. 2048, /* number of bits for the key - 2048 is a sensible value */
  72. RSA_F4, /* exponent - RSA_F4 is defined as 0x10001L */
  73. NULL, /* callback - can be NULL if we aren't displaying progress */
  74. NULL /* callback argument - not needed in this case */
  75. );
  76. EVP_PKEY_assign_RSA(pkey, rsa);
  77. X509 * x509;
  78. x509 = X509_new();
  79. ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
  80. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  81. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  82. X509_gmtime_adj(X509_get_notBefore(x509), notBefore);
  83. X509_gmtime_adj(X509_get_notAfter(x509), notAfter);
  84. X509_set_pubkey(x509, pkey);
  85. X509_NAME * name;
  86. name = X509_get_subject_name(x509);
  87. // Now to add the subject name fields to the certificate
  88. // I use a macro here to make it cleaner.
  89. const unsigned char *cUserID = (const unsigned char *) [userID cStringUsingEncoding:NSUTF8StringEncoding];
  90. // Common Name = UserID.
  91. addName("CN", cUserID);
  92. // The organizational unit for the cert. Usually this is a department.
  93. addName("OU", "Certificate Authority");
  94. // The organization of the cert.
  95. addName("O", "Nextcloud");
  96. // The city of the organization.
  97. addName("L", "Vicenza");
  98. // The state/province of the organization.
  99. addName("S", "Italy");
  100. // The country (ISO 3166) of the organization
  101. addName("C", "IT");
  102. X509_set_issuer_name(x509, name);
  103. /*
  104. for (SANObject * san in self.options.sans) {
  105. if (!san.value || san.value.length <= 0) {
  106. continue;
  107. }
  108. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  109. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  110. NSLog(@"Add subjectAltName %@", value);
  111. X509_EXTENSION * extension = NULL;
  112. ASN1_STRING * asnValue = ASN1_STRING_new();
  113. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  114. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  115. X509_add_ext(x509, extension, -1);
  116. }
  117. */
  118. // Specify the encryption algorithm of the signature.
  119. // SHA256 should suit your needs.
  120. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  121. return NO;
  122. }
  123. X509_print_fp(stdout, x509);
  124. // Extract CSR, publicKey, privateKey
  125. int len;
  126. char *keyBytes;
  127. // CSR
  128. BIO *csrBIO = BIO_new(BIO_s_mem());
  129. X509_REQ *certReq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  130. PEM_write_bio_X509_REQ(csrBIO, certReq);
  131. len = BIO_pending(csrBIO);
  132. keyBytes = malloc(len);
  133. BIO_read(csrBIO, keyBytes, len);
  134. _csrData = [NSData dataWithBytes:keyBytes length:len];
  135. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding]);
  136. // PublicKey
  137. BIO *publicKeyBIO = BIO_new(BIO_s_mem());
  138. PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
  139. len = BIO_pending(publicKeyBIO);
  140. keyBytes = malloc(len);
  141. BIO_read(publicKeyBIO, keyBytes, len);
  142. _publicKeyData = [NSData dataWithBytes:keyBytes length:len];
  143. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding]);
  144. // PrivateKey
  145. BIO *privateKeyBIO = BIO_new(BIO_s_mem());
  146. PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
  147. len = BIO_pending(privateKeyBIO);
  148. keyBytes = malloc(len);
  149. BIO_read(privateKeyBIO, keyBytes, len);
  150. _privateKeyData = [NSData dataWithBytes:keyBytes length:len];
  151. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding]);
  152. if(keyBytes)
  153. free(keyBytes);
  154. #ifdef DEBUG
  155. // Save to disk [DEBUG MODE]
  156. [self saveToDiskPEMWithCert:x509 key:pkey directory:directory];
  157. #endif
  158. return YES;
  159. }
  160. - (BOOL)saveToDiskPEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory
  161. {
  162. FILE *f;
  163. // Certificate
  164. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCertificate];
  165. f = fopen([certificatePath fileSystemRepresentation], "wb");
  166. if (PEM_write_X509(f, x509) < 0) {
  167. // Error writing to disk.
  168. fclose(f);
  169. return NO;
  170. }
  171. NSLog(@"[LOG] Saved cert to %@", certificatePath);
  172. fclose(f);
  173. // PublicKey
  174. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePubliceKey];
  175. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  176. if (PEM_write_PUBKEY(f, pkey) < 0) {
  177. // Error
  178. fclose(f);
  179. return NO;
  180. }
  181. NSLog(@"[LOG] Saved publicKey to %@", publicKeyPath);
  182. fclose(f);
  183. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  184. // file using the password and cipher you provide.
  185. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  186. // PrivateKey
  187. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePrivateKey];
  188. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  189. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  190. // Error
  191. fclose(f);
  192. return NO;
  193. }
  194. NSLog(@"[LOG] Saved privatekey to %@", privatekeyPath);
  195. fclose(f);
  196. // CSR Request sha256
  197. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCSR];
  198. f = fopen([csrPath fileSystemRepresentation], "wb");
  199. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  200. if (PEM_write_X509_REQ(f, certreq) < 0) {
  201. // Error
  202. fclose(f);
  203. return NO;
  204. }
  205. NSLog(@"[LOG] Saved csr to %@", csrPath);
  206. fclose(f);
  207. return YES;
  208. }
  209. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory finished:(void (^)(NSError *))finished
  210. {
  211. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  212. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  213. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directory];
  214. FILE *f = fopen([path fileSystemRepresentation], "wb");
  215. if (i2d_PKCS12_fp(f, p12) != 1) {
  216. fclose(f);
  217. return NO;
  218. }
  219. NSLog(@"[LOG] Saved p12 to %@", path);
  220. fclose(f);
  221. return YES;
  222. }
  223. #
  224. #pragma mark - Create CSR & Encrypt/Decrypt Private Key
  225. #
  226. - (NSString *)createCSR:(NSString *)userID directory:(NSString *)directory
  227. {
  228. // Create Certificate, if do not exists
  229. if (!_csrData) {
  230. if (![self generateCertificateX509WithUserID:userID directory:directory])
  231. return nil;
  232. }
  233. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  234. return csr;
  235. }
  236. - (NSString *)encryptPrivateKey:(NSString *)userID directory:(NSString *)directory passphrase:(NSString *)passphrase privateKey:(NSString **)privateKey
  237. {
  238. NSMutableData *privateKeyCipherData = [NSMutableData new];
  239. if (!_privateKeyData) {
  240. if (![self generateCertificateX509WithUserID:userID directory:directory])
  241. return nil;
  242. }
  243. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  244. NSData *saltData = [self generateSalt:AES_SALT_LENGTH];
  245. // Remove all whitespaces from passphrase
  246. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  247. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  248. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  249. NSData *tagData = [NSData new];
  250. /* ENCODE 64 privateKey JAVA compatibility */
  251. NSString *privateKeyBase64 = [_privateKeyData base64EncodedStringWithOptions:0];
  252. NSData *privateKeyBase64Data = [privateKeyBase64 dataUsingEncoding:NSUTF8StringEncoding];
  253. /* --------------------------------------- */
  254. BOOL result = [self encryptData:privateKeyBase64Data cipherData:&privateKeyCipherData keyData:keyData keyLen:AES_KEY_256_LENGTH ivData:ivData tagData:&tagData];
  255. if (result && privateKeyCipherData) {
  256. NSString *privateKeyCipherBase64 = [privateKeyCipherData base64EncodedStringWithOptions:0];
  257. NSString *initVectorBase64 = [ivData base64EncodedStringWithOptions:0];
  258. NSString *saltBase64 = [saltData base64EncodedStringWithOptions:0];
  259. NSString *privateKeyCipherWithInitVectorBase64 = [NSString stringWithFormat:@"%@%@%@%@%@", privateKeyCipherBase64, IV_DELIMITER_ENCODED, initVectorBase64, IV_DELIMITER_ENCODED, saltBase64];
  260. *privateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  261. return privateKeyCipherWithInitVectorBase64;
  262. } else {
  263. return nil;
  264. }
  265. }
  266. - (NSString *)decryptPrivateKey:(NSString *)privateKeyCipher passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey
  267. {
  268. NSMutableData *privateKeyData = [NSMutableData new];
  269. NSString *privateKey;
  270. // Key (data)
  271. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  272. // Split
  273. NSArray *privateKeyCipherArray = [privateKeyCipher componentsSeparatedByString:IV_DELIMITER_ENCODED];
  274. NSData *privateKeyCipherData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[0] options:0];
  275. NSString *tagBase64 = [privateKeyCipher substringWithRange:NSMakeRange([(NSString *)privateKeyCipherArray[0] length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  276. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tagBase64 options:0];
  277. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[1] options:0];
  278. NSData *saltData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherArray[2] options:0];
  279. // Remove all whitespaces from passphrase
  280. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  281. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  282. BOOL result = [self decryptData:privateKeyCipherData plainData:&privateKeyData keyData:keyData keyLen:AES_KEY_256_LENGTH ivData:ivData tagData:tagData];
  283. if (result && privateKeyData)
  284. /* DENCODE 64 privateKey JAVA compatibility */
  285. privateKey = [self base64DecodeData:privateKeyData];
  286. /* ---------------------------------------- */
  287. if (privateKey) {
  288. NSData *encryptData = [self encryptAsymmetricString:ASYMMETRIC_STRING_TEST publicKey:publicKey privateKey:nil];
  289. if (!encryptData)
  290. return nil;
  291. NSString *decryptString = [self decryptAsymmetricData:encryptData privateKey:privateKey];
  292. if (decryptString && [decryptString isEqualToString:ASYMMETRIC_STRING_TEST])
  293. return privateKey;
  294. else
  295. return nil;
  296. return privateKey;
  297. } else {
  298. return nil;
  299. }
  300. }
  301. #
  302. #pragma mark - Encrypt / Decrypt Encrypted Json
  303. #
  304. - (NSString *)encryptEncryptedJson:(NSString *)encrypted key:(NSString *)key
  305. {
  306. NSMutableData *cipherData;
  307. NSData *tagData = [NSData new];
  308. // ENCODE 64 encrypted JAVA compatibility */
  309. NSData *encryptedData = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  310. NSString *encryptedDataBase64 = [encryptedData base64EncodedStringWithOptions:0];
  311. NSData *encryptedData64Data = [encryptedDataBase64 dataUsingEncoding:NSUTF8StringEncoding];
  312. /* --------------------------------------- */
  313. // Key
  314. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  315. // IV
  316. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  317. BOOL result = [self encryptData:encryptedData64Data cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  318. if (cipherData != nil && result) {
  319. NSString *cipherBase64 = [cipherData base64EncodedStringWithOptions:0];
  320. NSString *ivBase64 = [ivData base64EncodedStringWithOptions:0];
  321. NSString *encryptedJson = [NSString stringWithFormat:@"%@%@%@", cipherBase64, IV_DELIMITER_ENCODED, ivBase64];
  322. return encryptedJson;
  323. }
  324. return nil;
  325. }
  326. - (NSString *)decryptEncryptedJson:(NSString *)encrypted key:(NSString *)key
  327. {
  328. NSMutableData *plainData;
  329. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  330. // Cipher
  331. NSString *cipher = [encrypted substringToIndex:(range.location)];
  332. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  333. // Key
  334. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  335. // IV
  336. NSString *iv = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  337. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:iv options:0];
  338. // TAG
  339. NSString *tag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  340. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:tag options:0];
  341. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  342. if (plainData != nil && result) {
  343. /* DENCODE 64 JAVA compatibility */
  344. NSString *plain = [self base64DecodeData:plainData];
  345. /* ---------------------------------------- */
  346. return plain;
  347. }
  348. return nil;
  349. }
  350. #
  351. #pragma mark - Encrypt / Decrypt file
  352. #
  353. - (void)encryptkey:(NSString **)key initializationVector:(NSString **)initializationVector
  354. {
  355. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  356. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  357. *key = [keyData base64EncodedStringWithOptions:0];
  358. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  359. }
  360. - (BOOL)encryptFileName:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  361. {
  362. NSMutableData *cipherData;
  363. NSData *tagData;
  364. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directory, fileName]];
  365. if (plainData == nil)
  366. return false;
  367. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  368. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  369. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:&tagData];
  370. if (cipherData != nil && result) {
  371. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] atomically:YES];
  372. *key = [keyData base64EncodedStringWithOptions:0];
  373. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  374. *authenticationTag = [tagData base64EncodedStringWithOptions:0];
  375. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  376. return false;
  377. } else {
  378. return true;
  379. }
  380. }
  381. return false;
  382. }
  383. - (BOOL)decryptFileName:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  384. {
  385. NSMutableData *plainData;
  386. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  387. if (cipherData == nil)
  388. return false;
  389. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  390. NSData *ivData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  391. NSData *tagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  392. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData keyLen:AES_KEY_128_LENGTH ivData:ivData tagData:tagData];
  393. if (plainData != nil && result) {
  394. [plainData writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] atomically:YES];
  395. return true;
  396. }
  397. return false;
  398. }
  399. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  400. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  401. #
  402. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  403. #
  404. #
  405. #pragma mark - Asymmetric Encrypt/Decrypt String
  406. #
  407. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey privateKey:(NSString *)privateKey
  408. {
  409. ENGINE *eng = ENGINE_get_default_RSA();
  410. EVP_PKEY *key = NULL;
  411. int status = 0;
  412. if (publicKey != nil) {
  413. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  414. // Extract real publicKey
  415. BIO *bio = BIO_new_mem_buf(pKey, -1);
  416. if (!bio)
  417. return nil;
  418. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  419. if (!x509)
  420. return nil;
  421. key = X509_get_pubkey(x509);
  422. if (!key)
  423. return nil;
  424. }
  425. if (privateKey != nil) {
  426. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  427. BIO *bio = BIO_new_mem_buf(pKey, -1);
  428. if (!bio)
  429. return nil;
  430. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  431. if (!key)
  432. return nil;
  433. }
  434. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, eng);
  435. if (!ctx)
  436. return nil;
  437. status = EVP_PKEY_encrypt_init(ctx);
  438. if (status <= 0)
  439. return nil;
  440. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  441. if (status <= 0)
  442. return nil;
  443. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  444. if (status <= 0)
  445. return nil;
  446. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  447. if (status <= 0)
  448. return nil;
  449. unsigned long outLen = 0;
  450. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  451. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  452. if (status <= 0 || outLen == 0)
  453. return nil;
  454. unsigned char *out = (unsigned char *) malloc(outLen);
  455. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  456. if (status <= 0)
  457. return nil;
  458. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  459. if (out)
  460. free(out);
  461. return outData;
  462. }
  463. - (NSString *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  464. {
  465. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  466. ENGINE *eng = ENGINE_get_default_RSA();
  467. int status = 0;
  468. BIO *bio = BIO_new_mem_buf(pKey, -1);
  469. if (!bio)
  470. return nil;
  471. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  472. if (!key)
  473. return nil;
  474. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, eng);
  475. if (!ctx)
  476. return nil;
  477. status = EVP_PKEY_decrypt_init(ctx);
  478. if (status <= 0)
  479. return nil;
  480. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  481. if (status <= 0)
  482. return nil;
  483. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  484. if (status <= 0)
  485. return nil;
  486. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  487. if (status <= 0)
  488. return nil;
  489. unsigned long outLen = 0;
  490. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  491. if (status <= 0 || outLen == 0)
  492. return nil;
  493. unsigned char *out = (unsigned char *) malloc(outLen);
  494. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  495. if (status <= 0)
  496. return nil;
  497. NSString *outString = [[NSString alloc] initWithBytes:out length:outLen encoding:NSUTF8StringEncoding];
  498. if (out)
  499. free(out);
  500. return outString;
  501. }
  502. #
  503. #pragma mark - AES/GCM/NoPadding
  504. #
  505. // Encryption using GCM mode
  506. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData **)tagData
  507. {
  508. int status = 0;
  509. int len = 0;
  510. // set up key
  511. len = keyLen;
  512. unsigned char cKey[len];
  513. bzero(cKey, sizeof(cKey));
  514. [keyData getBytes:cKey length:len];
  515. // set up ivec
  516. len = AES_IVEC_LENGTH;
  517. unsigned char cIV[len];
  518. bzero(cIV, sizeof(cIV));
  519. [ivData getBytes:cIV length:len];
  520. // set up tag
  521. len = AES_GCM_TAG_LENGTH;
  522. unsigned char cTag[len];
  523. bzero(cTag, sizeof(cTag));
  524. // Create and initialise the context
  525. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  526. if (!ctx)
  527. return NO;
  528. // Initialise the encryption operation
  529. if (keyLen == AES_KEY_128_LENGTH)
  530. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  531. else if (keyLen == AES_KEY_256_LENGTH)
  532. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  533. if (status <= 0)
  534. return NO;
  535. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  536. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  537. if (status <= 0)
  538. return NO;
  539. // Initialise key and IV
  540. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  541. if (status <= 0)
  542. return NO;
  543. // Provide the message to be encrypted, and obtain the encrypted output
  544. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  545. unsigned char * cCipher = [*cipherData mutableBytes];
  546. int cCipherLen = 0;
  547. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plainData bytes], (int)[plainData length]);
  548. if (status <= 0)
  549. return NO;
  550. // Finalise the encryption
  551. len = cCipherLen;
  552. status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  553. if (status <= 0)
  554. return NO;
  555. // Get the tag
  556. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  557. *tagData = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  558. // Add TAG JAVA compatibility
  559. [*cipherData appendData:*tagData];
  560. // --------------------------
  561. // Free
  562. EVP_CIPHER_CTX_free(ctx);
  563. return status; // OpenSSL uses 1 for success
  564. }
  565. // Decryption using GCM mode
  566. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData keyLen:(int)keyLen ivData:(NSData *)ivData tagData:(NSData *)tagData
  567. {
  568. int status = 0;
  569. int len = 0;
  570. // set up key
  571. len = keyLen;
  572. unsigned char cKey[len];
  573. bzero(cKey, sizeof(cKey));
  574. [keyData getBytes:cKey length:len];
  575. // set up ivec
  576. len = (int)[ivData length];
  577. unsigned char cIV[len];
  578. bzero(cIV, sizeof(cIV));
  579. [ivData getBytes:cIV length:len];
  580. // set up tag
  581. len = (int)[tagData length];;
  582. unsigned char cTag[len];
  583. bzero(cTag, sizeof(cTag));
  584. [tagData getBytes:cTag length:len];
  585. // Create and initialise the context
  586. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  587. if (!ctx)
  588. return NO;
  589. // Initialise the decryption operation
  590. if (keyLen == AES_KEY_128_LENGTH)
  591. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  592. else if (keyLen == AES_KEY_256_LENGTH)
  593. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  594. if (status <= 0)
  595. return NO;
  596. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  597. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  598. if (status <= 0)
  599. return NO;
  600. // Initialise key and IV
  601. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  602. if (status <= 0)
  603. return NO;
  604. // Remove TAG JAVA compatibility
  605. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  606. // -----------------------------
  607. // Provide the message to be decrypted, and obtain the plaintext output
  608. *plainData = [NSMutableData dataWithLength:([cipherData length])];
  609. int cPlainLen = 0;
  610. unsigned char * cPlain = [*plainData mutableBytes];
  611. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipherData bytes], (int)([cipherData length]));
  612. if (status <= 0)
  613. return NO;
  614. // Tag is the last 16 bytes
  615. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  616. if (status <= 0)
  617. return NO;
  618. // Finalise the encryption
  619. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  620. // Free
  621. EVP_CIPHER_CTX_free(ctx);
  622. return status; // OpenSSL uses 1 for success
  623. }
  624. #
  625. #pragma mark - Utility
  626. #
  627. - (NSString *)createSHA512:(NSString *)string
  628. {
  629. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  630. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  631. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  632. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  633. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  634. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  635. [output appendFormat:@"%02x", digest[i]];
  636. return output;
  637. }
  638. - (NSData *)generateIV:(int)length
  639. {
  640. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  641. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  642. return ivData;
  643. }
  644. - (NSData *)generateSalt:(int)length
  645. {
  646. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  647. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  648. return saltData;
  649. }
  650. - (NSData *)generateKey:(int)length
  651. {
  652. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  653. unsigned char *pKeyData = [keyData mutableBytes];
  654. RAND_bytes(pKeyData, length);
  655. return keyData;
  656. }
  657. - (NSString *)getMD5:(NSString *)input
  658. {
  659. // Create pointer to the string as UTF8
  660. const char *ptr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  661. // Create byte array of unsigned chars
  662. unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  663. // Create 16 byte MD5 hash value, store in buffer
  664. CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
  665. // Convert MD5 value in the buffer to NSString of hex values
  666. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  667. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  668. [output appendFormat:@"%02x",md5Buffer[i]];
  669. return output;
  670. }
  671. - (NSString *)getSHA1:(NSString *)input
  672. {
  673. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  674. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  675. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  676. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  677. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  678. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  679. [output appendFormat:@"%02x", digest[i]];
  680. return output;
  681. }
  682. - (NSData *)hashValueMD5OfData:(NSData *)data
  683. {
  684. MD5_CTX md5Ctx;
  685. unsigned char hashValue[MD5_DIGEST_LENGTH];
  686. if(!MD5_Init(&md5Ctx)) {
  687. return nil;
  688. }
  689. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  690. return nil;
  691. }
  692. if (!MD5_Final(hashValue, &md5Ctx)) {
  693. return nil;
  694. }
  695. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  696. }
  697. - (NSString *)hexadecimalString:(NSData *)input
  698. {
  699. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  700. if (!dataBuffer) {
  701. return [NSString string];
  702. }
  703. NSUInteger dataLength = [input length];
  704. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  705. for (int i = 0; i < dataLength; ++i) {
  706. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  707. }
  708. return [NSString stringWithString:hexString];
  709. }
  710. /*
  711. - (NSData *)base64Encode:(NSData *)input
  712. {
  713. void *bytes;
  714. BIO *buffer = BIO_new(BIO_s_mem());
  715. BIO *base64 = BIO_new(BIO_f_base64());
  716. buffer = BIO_push(base64, buffer);
  717. BIO_write(buffer, [input bytes], (int)[input length]);
  718. NSUInteger length = BIO_get_mem_data(buffer, &bytes);
  719. NSString *string = [[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding];
  720. BIO_free_all(buffer);
  721. return [string dataUsingEncoding:NSUTF8StringEncoding];
  722. }
  723. */
  724. - (NSString *)base64DecodeData:(NSData *)input
  725. {
  726. NSMutableData *data = [NSMutableData data];
  727. BIO *buffer = BIO_new_mem_buf((void *)[input bytes], (int)[input length]);
  728. BIO *base64 = BIO_new(BIO_f_base64());
  729. buffer = BIO_push(base64, buffer);
  730. BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
  731. char chars[input.length];
  732. int length = BIO_read(buffer, chars, (int)sizeof(chars));
  733. while (length > 0) {
  734. [data appendBytes:chars length:length];
  735. length = BIO_read(buffer, chars, (int)sizeof(chars));
  736. }
  737. BIO_free_all(buffer);
  738. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  739. }
  740. - (NSData *)base64DecodeString:(NSString *)input
  741. {
  742. NSMutableData *data = [NSMutableData data];
  743. NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding];
  744. BIO *buffer = BIO_new_mem_buf((void *)[inputData bytes], (int)[inputData length]);
  745. BIO *base64 = BIO_new(BIO_f_base64());
  746. buffer = BIO_push(base64, buffer);
  747. BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
  748. char chars[input.length];
  749. int length = BIO_read(buffer, chars, (int)sizeof(chars));
  750. while (length > 0) {
  751. [data appendBytes:chars length:length];
  752. length = BIO_read(buffer, chars, (int)sizeof(chars));
  753. }
  754. BIO_free_all(buffer);
  755. return data;
  756. }
  757. - (NSString *)derToPemPrivateKey:(NSString *)input
  758. {
  759. NSInteger substringLength = 65;
  760. NSMutableString *result = [NSMutableString stringWithString: input];
  761. for(long i=substringLength;i<=input.length;i++) {
  762. [result insertString: @"\n" atIndex: i];
  763. i+=substringLength;
  764. }
  765. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  766. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  767. return result;
  768. }
  769. @end