NCEndToEndEncryption.m 34 KB

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