NCEndToEndEncryption.m 33 KB

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