NCEndToEndEncryption.m 29 KB

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