NCEndToEndEncryption.m 33 KB

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