NCEndToEndEncryption.m 33 KB

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