NCEndToEndEncryption.m 34 KB

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