NCEndToEndEncryption.m 23 KB

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