NCEndToEndEncryption.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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 AES_KEY_LENGTH 16
  40. #define AES_IVEC_LENGTH 16
  41. #define AES_GCM_TAG_LENGTH 16
  42. #define IV_DELIMITER_ENCODED @"fA==" // "|" base64 encoded
  43. #define PBKDF2_INTERACTION_COUNT 1024
  44. #define PBKDF2_KEY_LENGTH 256
  45. #define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  46. #define fileNameCertificate @"cert.pem"
  47. #define fileNameCSR @"csr.pem"
  48. #define fileNamePrivateKey @"privateKey.pem"
  49. #define fileNamePubliceKey @"publicKey.pem"
  50. @interface NCEndToEndEncryption ()
  51. {
  52. NSData *_privateKeyData;
  53. NSData *_publicKeyData;
  54. NSData *_csrData;
  55. }
  56. @end
  57. @implementation NCEndToEndEncryption
  58. //Singleton
  59. + (instancetype)sharedManager {
  60. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  61. static dispatch_once_t onceToken;
  62. dispatch_once(&onceToken, ^{
  63. NCEndToEndEncryption = [self new];
  64. });
  65. return NCEndToEndEncryption;
  66. }
  67. #
  68. #pragma mark - Generate Certificate X509 - CSR - Private Key
  69. #
  70. - (BOOL)generateCertificateX509WithUserID:(NSString *)userID directoryUser:(NSString *)directoryUser
  71. {
  72. OPENSSL_init_ssl(0, NULL);
  73. OPENSSL_init_crypto(0, NULL);
  74. X509 *x509;
  75. x509 = X509_new();
  76. EVP_PKEY *pkey;
  77. NSError *keyError;
  78. pkey = [self generateRSAKey:&keyError];
  79. if (keyError) {
  80. return NO;
  81. }
  82. X509_set_pubkey(x509, pkey);
  83. EVP_PKEY_free(pkey);
  84. // Set Serial Number
  85. ASN1_INTEGER_set(X509_get_serialNumber(x509), 123);
  86. // Set Valididity Date Range
  87. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  88. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  89. X509_gmtime_adj((ASN1_TIME *)X509_get0_notBefore(x509), notBefore);
  90. X509_gmtime_adj((ASN1_TIME *)X509_get0_notAfter(x509), notAfter);
  91. X509_NAME *name = X509_get_subject_name(x509);
  92. // Now to add the subject name fields to the certificate
  93. // I use a macro here to make it cleaner.
  94. const unsigned char *cUserID = (const unsigned char *) [userID cStringUsingEncoding:NSUTF8StringEncoding];
  95. // Common Name = UserID.
  96. addName("CN", cUserID);
  97. // The organizational unit for the cert. Usually this is a department.
  98. addName("OU", "Certificate Authority");
  99. // The organization of the cert.
  100. addName("O", "Nextcloud");
  101. // The city of the organization.
  102. addName("L", "Vicenza");
  103. // The state/province of the organization.
  104. addName("S", "Italy");
  105. // The country (ISO 3166) of the organization
  106. addName("C", "IT");
  107. X509_set_issuer_name(x509, name);
  108. /*
  109. for (SANObject * san in self.options.sans) {
  110. if (!san.value || san.value.length <= 0) {
  111. continue;
  112. }
  113. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  114. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  115. NSLog(@"Add subjectAltName %@", value);
  116. X509_EXTENSION * extension = NULL;
  117. ASN1_STRING * asnValue = ASN1_STRING_new();
  118. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  119. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  120. X509_add_ext(x509, extension, -1);
  121. }
  122. */
  123. // Specify the encryption algorithm of the signature.
  124. // SHA256 should suit your needs.
  125. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  126. return NO;
  127. }
  128. X509_print_fp(stdout, x509);
  129. // Extract CSR, publicKey, privateKey
  130. int len;
  131. char *keyBytes;
  132. // CSR
  133. BIO *csrBIO = BIO_new(BIO_s_mem());
  134. X509_REQ *certReq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  135. PEM_write_bio_X509_REQ(csrBIO, certReq);
  136. len = BIO_pending(csrBIO);
  137. keyBytes = malloc(len);
  138. BIO_read(csrBIO, keyBytes, len);
  139. _csrData = [NSData dataWithBytes:keyBytes length:len];
  140. NSLog(@"\n%@", [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding]);
  141. // PublicKey
  142. BIO *publicKeyBIO = BIO_new(BIO_s_mem());
  143. PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
  144. len = BIO_pending(publicKeyBIO);
  145. keyBytes = malloc(len);
  146. BIO_read(publicKeyBIO, keyBytes, len);
  147. _publicKeyData = [NSData dataWithBytes:keyBytes length:len];
  148. NSLog(@"\n%@", [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding]);
  149. // PrivateKey
  150. BIO *privateKeyBIO = BIO_new(BIO_s_mem());
  151. PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
  152. len = BIO_pending(privateKeyBIO);
  153. keyBytes = malloc(len);
  154. BIO_read(privateKeyBIO, keyBytes, len);
  155. _privateKeyData = [NSData dataWithBytes:keyBytes length:len];
  156. NSLog(@"\n%@", [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding]);
  157. if(keyBytes)
  158. free(keyBytes);
  159. #ifdef DEBUG
  160. // Save to disk [DEBUG MODE]
  161. [self savePEMWithCert:x509 key:pkey directoryUser:directoryUser];
  162. #endif
  163. return YES;
  164. }
  165. - (EVP_PKEY *)generateRSAKey:(NSError **)error
  166. {
  167. EVP_PKEY *pkey = EVP_PKEY_new();
  168. if (!pkey) {
  169. return NULL;
  170. }
  171. BIGNUM *bigNumber = BN_new();
  172. int exponent = RSA_F4;
  173. RSA *rsa = RSA_new();
  174. if (BN_set_word(bigNumber, exponent) < 0) {
  175. goto cleanup;
  176. }
  177. if (RSA_generate_key_ex(rsa, 2048, bigNumber, NULL) < 0) {
  178. goto cleanup;
  179. }
  180. if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
  181. goto cleanup;
  182. }
  183. cleanup:
  184. RSA_free(rsa);
  185. BN_free(bigNumber);
  186. return pkey;
  187. }
  188. - (BOOL)savePEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser
  189. {
  190. FILE *f;
  191. // Certificate
  192. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCertificate];
  193. f = fopen([certificatePath fileSystemRepresentation], "wb");
  194. if (PEM_write_X509(f, x509) < 0) {
  195. // Error writing to disk.
  196. fclose(f);
  197. return NO;
  198. }
  199. NSLog(@"Saved cert to %@", certificatePath);
  200. fclose(f);
  201. // PublicKey
  202. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePubliceKey];
  203. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  204. if (PEM_write_PUBKEY(f, pkey) < 0) {
  205. // Error
  206. fclose(f);
  207. return NO;
  208. }
  209. NSLog(@"Saved publicKey to %@", publicKeyPath);
  210. fclose(f);
  211. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  212. // file using the password and cipher you provide.
  213. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  214. // PrivateKey
  215. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey];
  216. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  217. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  218. // Error
  219. fclose(f);
  220. return NO;
  221. }
  222. NSLog(@"Saved privatekey to %@", privatekeyPath);
  223. fclose(f);
  224. // CSR Request sha256
  225. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR];
  226. f = fopen([csrPath fileSystemRepresentation], "wb");
  227. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  228. if (PEM_write_X509_REQ(f, certreq) < 0) {
  229. // Error
  230. fclose(f);
  231. return NO;
  232. }
  233. NSLog(@"Saved csr to %@", csrPath);
  234. fclose(f);
  235. return YES;
  236. }
  237. /*
  238. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  239. {
  240. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  241. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  242. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directoryUser];
  243. FILE *f = fopen([path fileSystemRepresentation], "wb");
  244. if (i2d_PKCS12_fp(f, p12) != 1) {
  245. fclose(f);
  246. return NO;
  247. }
  248. NSLog(@"Saved p12 to %@", path);
  249. fclose(f);
  250. return YES;
  251. }
  252. */
  253. - (NSString *)createCSR:(NSString *)userID directoryUser:(NSString *)directoryUser
  254. {
  255. /*
  256. // Create Certificate, if do not exists [Disk Version]
  257. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR]]) {
  258. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  259. return nil;
  260. }
  261. NSString *csr = [self getCSRFromDisk:directoryUser delete:NO];
  262. */
  263. // Create Certificate, if do not exists
  264. if (!_csrData) {
  265. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  266. return nil;
  267. }
  268. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  269. return csr;
  270. }
  271. - (NSString *)encryptPrivateKey:(NSString *)userID directoryUser: (NSString *)directoryUser passphrase:(NSString *)passphrase
  272. {
  273. NSMutableData *privateKeyCipherData = [NSMutableData new];
  274. /*
  275. // Create Certificate, if do not exists [Disk Version]
  276. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey]]) {
  277. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  278. return nil;
  279. }
  280. NSData *privateKeyData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey]];
  281. */
  282. if (!_privateKeyData) {
  283. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  284. return nil;
  285. }
  286. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  287. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  288. // Remove all whitespaces from passphrase
  289. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  290. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  291. NSData *initVectorData = [self generateIV:AES_IVEC_LENGTH];
  292. BOOL result = [self encryptData:_privateKeyData cipherData:&privateKeyCipherData keyData:keyData initVectorData:initVectorData tagData:nil];
  293. if (result && privateKeyCipherData) {
  294. NSString *privateKeyCipherBase64;
  295. NSString *initVectorBase64;
  296. NSString *privateKeyCipherWithInitVectorBase64;
  297. privateKeyCipherBase64 = [privateKeyCipherData base64EncodedStringWithOptions:0];
  298. initVectorBase64 = [initVectorData base64EncodedStringWithOptions:0];
  299. privateKeyCipherWithInitVectorBase64 = [NSString stringWithFormat:@"%@%@%@", privateKeyCipherBase64, IV_DELIMITER_ENCODED, initVectorBase64];
  300. return privateKeyCipherWithInitVectorBase64;
  301. } else {
  302. return nil;
  303. }
  304. }
  305. - (NSString *)getCSRFromDisk:(NSString *)directoryUser delete:(BOOL)delete
  306. {
  307. NSError *error;
  308. NSString *csr = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR] encoding:NSUTF8StringEncoding error:&error];
  309. if (delete)
  310. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR] error:nil];
  311. if (error)
  312. return nil;
  313. else
  314. return csr;
  315. }
  316. - (NSString *)getCSR
  317. {
  318. return [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  319. }
  320. - (NSString *)getPrivateKeyFromDisk:(NSString *)directoryUser delete:(BOOL)delete
  321. {
  322. NSError *error;
  323. NSString *privateKey = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey] encoding:NSUTF8StringEncoding error:&error];
  324. if (delete)
  325. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey] error:nil];
  326. if (error)
  327. return nil;
  328. else
  329. return privateKey;
  330. }
  331. - (NSString *)getPrivateKey
  332. {
  333. return [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  334. }
  335. #
  336. #pragma mark - Register client for Server with exists Key pair
  337. #
  338. - (NSString *)decryptPrivateKey:(NSString *)privateKeyCipher passphrase:(NSString *)passphrase
  339. {
  340. NSMutableData *privateKeyData = [NSMutableData new];
  341. // Key (data)
  342. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  343. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  344. // Remove all whitespaces from passphrase
  345. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  346. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  347. // Split
  348. NSRange range = [privateKeyCipher rangeOfString:IV_DELIMITER_ENCODED];
  349. NSInteger idx = range.location + range.length;
  350. // PrivateKey
  351. NSString *privateKeyCipherBase64 = [privateKeyCipher substringToIndex:range.location];
  352. NSData *privateKeyCipherData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherBase64 options:0];
  353. // Init Vector
  354. NSString *initVectorBase64 = [privateKeyCipher substringFromIndex:idx];
  355. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:initVectorBase64 options:0];
  356. BOOL result = [self decryptData:privateKeyCipherData plainData:&privateKeyData keyData:keyData initVectorData:initVectorData tag:nil];
  357. if (result && privateKeyData) {
  358. NSString *privateKey = [[NSString alloc] initWithData:privateKeyData encoding:NSUTF8StringEncoding];
  359. //unsigned char cPrivateKey[privateKeyData.length];
  360. //bzero(cPrivateKey, sizeof(cPrivateKey));
  361. //[privateKeyData getBytes:cPrivateKey length:privateKeyData.length];
  362. //BIO *priv_bio = BIO_new_mem_buf(cPrivateKey, privateKeyData.length);
  363. //RSA *rsaPrivKey = PEM_read_bio_RSAPrivateKey(priv_bio, NULL, NULL, NULL);
  364. // Temp test REMOVE !!
  365. if ([privateKey containsString:@"-----BEGIN PRIVATE KEY-----"] && [privateKey containsString:@"-----END PRIVATE KEY-----"])
  366. return privateKey;
  367. else
  368. return nil;
  369. } else {
  370. return nil;
  371. }
  372. }
  373. #
  374. #pragma mark - Encrypt/Decrypt AES/GCM/NoPadding as cipher (128 bit key size)
  375. #
  376. - (void)encryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  377. {
  378. NSMutableData *cipherData;
  379. NSData *tagData;
  380. NSString* authenticationTag;
  381. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  382. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  383. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  384. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData initVectorData:initVectorData tagData:&tagData];
  385. if (cipherData != nil && result) {
  386. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"encrypted.dms"] atomically:YES];
  387. authenticationTag = [tagData base64EncodedStringWithOptions:0];
  388. }
  389. }
  390. - (void)decryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  391. {
  392. NSMutableData *plainData;
  393. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  394. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  395. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  396. NSString *tag = @"PboI9tqHHX3QeAA22PIu4w==";
  397. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData initVectorData:initVectorData tag:tag];
  398. if (plainData != nil && result) {
  399. [plainData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"decrypted"] atomically:YES];
  400. }
  401. }
  402. // encrypt data AES 256 GCM NOPADING
  403. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tagData:(NSData **)tagData
  404. {
  405. int status = 0;
  406. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  407. // set up key
  408. unsigned char cKey[AES_KEY_LENGTH];
  409. bzero(cKey, sizeof(cKey));
  410. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  411. // set up ivec
  412. unsigned char cIv[AES_IVEC_LENGTH];
  413. bzero(cIv, AES_IVEC_LENGTH);
  414. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  415. // set up to Encrypt AES 128 GCM
  416. int numberOfBytes = 0;
  417. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  418. EVP_EncryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  419. // set the key and ivec
  420. EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  421. EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  422. unsigned char * ctBytes = [*cipherData mutableBytes];
  423. EVP_EncryptUpdate (ctx, ctBytes, &numberOfBytes, [plainData bytes], (int)[plainData length]);
  424. status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  425. if (status && tagData) {
  426. unsigned char cTag[AES_GCM_TAG_LENGTH];
  427. bzero(cTag, AES_GCM_TAG_LENGTH);
  428. status = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_LENGTH, cTag);
  429. *tagData = [NSData dataWithBytes:cTag length:AES_GCM_TAG_LENGTH];
  430. }
  431. EVP_CIPHER_CTX_free(ctx);
  432. return (status != 0); // OpenSSL uses 1 for success
  433. }
  434. // decrypt data AES 256 GCM NOPADING
  435. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tag:(NSString *)tag
  436. {
  437. int status = 0;
  438. int numberOfBytes = 0;
  439. *plainData = [NSMutableData dataWithLength:[cipherData length]];
  440. // set up key
  441. unsigned char cKey[AES_KEY_LENGTH];
  442. bzero(cKey, sizeof(cKey));
  443. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  444. // set up ivec
  445. unsigned char cIv[AES_IVEC_LENGTH];
  446. bzero(cIv, AES_IVEC_LENGTH);
  447. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  448. // set up tag
  449. //unsigned char cTag[AES_GCM_TAG_LENGTH];
  450. //bzero(cTag, AES_GCM_TAG_LENGTH);
  451. //[tagData getBytes:cTag length:AES_GCM_TAG_LENGTH];
  452. /* verify tag if exists*/
  453. if (tag) {
  454. NSData *authenticationTagData = [cipherData subdataWithRange:NSMakeRange([cipherData length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  455. NSString *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  456. if (![authenticationTag isEqualToString:tag])
  457. return NO;
  458. }
  459. /* Create and initialise the context */
  460. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  461. /* Initialise the decryption operation. */
  462. status = EVP_DecryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  463. if (! status)
  464. return NO;
  465. /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
  466. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  467. if (! status)
  468. return NO;
  469. /* Initialise key and IV */
  470. status = EVP_DecryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  471. if (! status)
  472. return NO;
  473. /* Provide the message to be decrypted, and obtain the plaintext output. */
  474. unsigned char * ctBytes = [*plainData mutableBytes];
  475. status = EVP_DecryptUpdate (ctx, ctBytes, &numberOfBytes, [cipherData bytes], (int)[cipherData length]);
  476. if (! status)
  477. return NO;
  478. /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
  479. //status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_LENGTH, cTag);
  480. //if (!status)
  481. // return NO;
  482. /* Finalise the decryption. A positive return value indicates success, anything else is a failure - the plaintext is n trustworthy. */
  483. //status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  484. //if (!status)
  485. // return NO;
  486. // Without test Final
  487. EVP_DecryptFinal_ex (ctx, NULL, &numberOfBytes);
  488. EVP_CIPHER_CTX_free(ctx);
  489. return status; // OpenSSL uses 1 for success
  490. }
  491. #
  492. #pragma mark - Utility
  493. #
  494. - (NSString *)createSHA512:(NSString *)string
  495. {
  496. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  497. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  498. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  499. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  500. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  501. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  502. [output appendFormat:@"%02x", digest[i]];
  503. return output;
  504. }
  505. - (NSData *)generateIV:(int)ivLength
  506. {
  507. NSMutableData *ivData = [NSMutableData dataWithLength:ivLength];
  508. (void)SecRandomCopyBytes(kSecRandomDefault, ivLength, ivData.mutableBytes);
  509. return ivData;
  510. }
  511. - (NSString *)getMD5:(NSString *)input
  512. {
  513. // Create pointer to the string as UTF8
  514. const char *ptr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  515. // Create byte array of unsigned chars
  516. unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  517. // Create 16 byte MD5 hash value, store in buffer
  518. CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
  519. // Convert MD5 value in the buffer to NSString of hex values
  520. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  521. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  522. [output appendFormat:@"%02x",md5Buffer[i]];
  523. return output;
  524. }
  525. - (NSString *)getSHA1:(NSString *)input
  526. {
  527. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  528. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  529. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  530. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  531. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  532. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  533. [output appendFormat:@"%02x", digest[i]];
  534. return output;
  535. }
  536. - (NSData *)hashValueMD5OfData:(NSData *)data
  537. {
  538. MD5_CTX md5Ctx;
  539. unsigned char hashValue[MD5_DIGEST_LENGTH];
  540. if(!MD5_Init(&md5Ctx)) {
  541. return nil;
  542. }
  543. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  544. return nil;
  545. }
  546. if (!MD5_Final(hashValue, &md5Ctx)) {
  547. return nil;
  548. }
  549. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  550. }
  551. - (NSString *)hexadecimalString:(NSData *)input
  552. {
  553. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  554. if (!dataBuffer) {
  555. return [NSString string];
  556. }
  557. NSUInteger dataLength = [input length];
  558. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  559. for (int i = 0; i < dataLength; ++i) {
  560. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  561. }
  562. return [NSString stringWithString:hexString];
  563. }
  564. - (NSString *)stringRemoveBeginEnd:(NSString *)input
  565. {
  566. input = [input stringByReplacingOccurrencesOfString:@"-----BEGIN CERTIFICATE-----\n" withString:@""];
  567. input = [input stringByReplacingOccurrencesOfString:@"\n-----END CERTIFICATE-----" withString:@""];
  568. input = [input stringByReplacingOccurrencesOfString:@"-----BEGIN PRIVATE KEY-----\n" withString:@""];
  569. input = [input stringByReplacingOccurrencesOfString:@"\n-----END PRIVATE KEY-----" withString:@""];
  570. return input;
  571. }
  572. @end