NCEndToEndEncryption.m 30 KB

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