NCEndToEndEncryption.m 34 KB

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