NCEndToEndEncryption.m 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. //
  2. // NCEndToEndEncryption.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/09/17.
  6. // Copyright © 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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/OpenSSL.h>
  29. #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);
  30. #define IV_DELIMITER_ENCODED_OLD @"fA=="
  31. #define IV_DELIMITER_ENCODED @"|"
  32. #define PBKDF2_KEY_LENGTH 256
  33. //#define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  34. #define ASYMMETRIC_STRING_TEST @"Nextcloud a safe home for all your data"
  35. #define fileNameCertificate @"cert.pem"
  36. #define fileNameCSR @"csr.pem"
  37. #define fileNamePrivateKey @"privateKey.pem"
  38. #define fileNamePubliceKey @"publicKey.pem"
  39. #define streamBuffer 1024
  40. #define AES_KEY_128_LENGTH 16
  41. #define AES_KEY_256_LENGTH 32
  42. #define AES_IVEC_LENGTH 16
  43. #define AES_GCM_TAG_LENGTH 16
  44. #define AES_SALT_LENGTH 40
  45. @interface NCEndToEndEncryption ()
  46. {
  47. NSData *_privateKeyData;
  48. NSData *_publicKeyData;
  49. NSData *_csrData;
  50. }
  51. @end
  52. @implementation NCEndToEndEncryption
  53. //Singleton
  54. + (instancetype)sharedManager {
  55. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  56. static dispatch_once_t onceToken;
  57. dispatch_once(&onceToken, ^{
  58. NCEndToEndEncryption = [self new];
  59. });
  60. return NCEndToEndEncryption;
  61. }
  62. #
  63. #pragma mark - Generate Certificate X509 - CSR - Private Key
  64. #
  65. - (BOOL)generateCertificateX509WithUserId:(NSString *)userId directory:(NSString *)directory
  66. {
  67. OPENSSL_init();
  68. int ret;
  69. EVP_PKEY * pkey;
  70. pkey = EVP_PKEY_new();
  71. RSA * rsa;
  72. BIGNUM *bignum = BN_new();
  73. ret = BN_set_word(bignum, RSA_F4);
  74. if (ret != 1) {
  75. return NO;
  76. }
  77. rsa = RSA_new();
  78. ret = RSA_generate_key_ex(rsa, 2048, bignum, NULL);
  79. if (ret != 1) {
  80. return NO;
  81. }
  82. EVP_PKEY_assign_RSA(pkey, rsa);
  83. X509 * x509;
  84. x509 = X509_new();
  85. ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
  86. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  87. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  88. X509_gmtime_adj(X509_get_notBefore(x509), notBefore);
  89. X509_gmtime_adj(X509_get_notAfter(x509), notAfter);
  90. X509_set_pubkey(x509, pkey);
  91. X509_NAME * name;
  92. name = X509_get_subject_name(x509);
  93. // Now to add the subject name fields to the certificate
  94. // I use a macro here to make it cleaner.
  95. const unsigned char *cUserId = (const unsigned char *) [userId cStringUsingEncoding:NSUTF8StringEncoding];
  96. // Common Name = UserID.
  97. addName("CN", cUserId);
  98. // The organizational unit for the cert. Usually this is a department.
  99. addName("OU", "Certificate Authority");
  100. // The organization of the cert.
  101. addName("O", "Nextcloud");
  102. // The city of the organization.
  103. addName("L", "Vicenza");
  104. // The state/province of the organization.
  105. addName("S", "Italy");
  106. // The country (ISO 3166) of the organization
  107. addName("C", "IT");
  108. X509_set_issuer_name(x509, name);
  109. /*
  110. for (SANObject * san in self.options.sans) {
  111. if (!san.value || san.value.length <= 0) {
  112. continue;
  113. }
  114. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  115. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  116. NSLog(@"Add subjectAltName %@", value);
  117. X509_EXTENSION * extension = NULL;
  118. ASN1_STRING * asnValue = ASN1_STRING_new();
  119. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  120. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  121. X509_add_ext(x509, extension, -1);
  122. }
  123. */
  124. // Specify the encryption algorithm of the signature.
  125. // SHA256 should suit your needs.
  126. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  127. return NO;
  128. }
  129. X509_print_fp(stdout, x509);
  130. // Extract CSR, publicKey, privateKey
  131. int len;
  132. char *keyBytes;
  133. // CSR
  134. BIO *csrBIO = BIO_new(BIO_s_mem());
  135. X509_REQ *certReq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  136. PEM_write_bio_X509_REQ(csrBIO, certReq);
  137. len = BIO_pending(csrBIO);
  138. keyBytes = malloc(len);
  139. BIO_read(csrBIO, keyBytes, len);
  140. _csrData = [NSData dataWithBytes:keyBytes length:len];
  141. NSLog(@"[LOG] \n%@", [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding]);
  142. // PublicKey
  143. BIO *publicKeyBIO = BIO_new(BIO_s_mem());
  144. PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
  145. len = BIO_pending(publicKeyBIO);
  146. keyBytes = malloc(len);
  147. BIO_read(publicKeyBIO, keyBytes, len);
  148. _publicKeyData = [NSData dataWithBytes:keyBytes length:len];
  149. self.generatedPublicKey = [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding];
  150. NSLog(@"[LOG] \n%@", self.generatedPublicKey);
  151. // PrivateKey
  152. BIO *privateKeyBIO = BIO_new(BIO_s_mem());
  153. PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
  154. len = BIO_pending(privateKeyBIO);
  155. keyBytes = malloc(len);
  156. BIO_read(privateKeyBIO, keyBytes, len);
  157. _privateKeyData = [NSData dataWithBytes:keyBytes length:len];
  158. self.generatedPrivateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  159. NSLog(@"[LOG] \n%@", self.generatedPrivateKey);
  160. if(keyBytes)
  161. free(keyBytes);
  162. #ifdef DEBUG
  163. // Save to disk [DEBUG MODE]
  164. [self saveToDiskPEMWithCert:x509 key:pkey directory:directory];
  165. #endif
  166. return YES;
  167. }
  168. - (NSString *)extractPublicKeyFromCertificate:(NSString *)pemCertificate
  169. {
  170. const char *ptrCert = [pemCertificate cStringUsingEncoding:NSUTF8StringEncoding];
  171. BIO *certBio = BIO_new(BIO_s_mem());
  172. BIO_write(certBio, ptrCert,(unsigned int)strlen(ptrCert));
  173. X509 *certX509 = PEM_read_bio_X509(certBio, NULL, NULL, NULL);
  174. if (!certX509) {
  175. fprintf(stderr, "unable to parse certificate in memory\n");
  176. return nil;
  177. }
  178. EVP_PKEY *pkey;
  179. pkey = X509_get_pubkey(certX509);
  180. NSString *publicKey = [self pubKeyToString:pkey];
  181. EVP_PKEY_free(pkey);
  182. BIO_free(certBio);
  183. X509_free(certX509);
  184. NSLog(@"[LOG] \n%@", publicKey);
  185. return publicKey;
  186. }
  187. - (BOOL)saveToDiskPEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory
  188. {
  189. FILE *f;
  190. // Certificate
  191. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCertificate];
  192. f = fopen([certificatePath fileSystemRepresentation], "wb");
  193. if (PEM_write_X509(f, x509) < 0) {
  194. // Error writing to disk.
  195. fclose(f);
  196. return NO;
  197. }
  198. NSLog(@"[LOG] Saved cert to %@", certificatePath);
  199. fclose(f);
  200. // PublicKey
  201. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePubliceKey];
  202. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  203. if (PEM_write_PUBKEY(f, pkey) < 0) {
  204. // Error
  205. fclose(f);
  206. return NO;
  207. }
  208. NSLog(@"[LOG] Saved publicKey to %@", publicKeyPath);
  209. fclose(f);
  210. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  211. // file using the password and cipher you provide.
  212. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  213. // PrivateKey
  214. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directory, fileNamePrivateKey];
  215. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  216. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  217. // Error
  218. fclose(f);
  219. return NO;
  220. }
  221. NSLog(@"[LOG] Saved privatekey to %@", privatekeyPath);
  222. fclose(f);
  223. // CSR Request sha256
  224. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directory, fileNameCSR];
  225. f = fopen([csrPath fileSystemRepresentation], "wb");
  226. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  227. if (PEM_write_X509_REQ(f, certreq) < 0) {
  228. // Error
  229. fclose(f);
  230. return NO;
  231. }
  232. NSLog(@"[LOG] Saved csr to %@", csrPath);
  233. fclose(f);
  234. return YES;
  235. }
  236. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directory:(NSString *)directory finished:(void (^)(NSError *))finished
  237. {
  238. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  239. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  240. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directory];
  241. FILE *f = fopen([path fileSystemRepresentation], "wb");
  242. if (i2d_PKCS12_fp(f, p12) != 1) {
  243. fclose(f);
  244. return NO;
  245. }
  246. NSLog(@"[LOG] Saved p12 to %@", path);
  247. fclose(f);
  248. return YES;
  249. }
  250. #
  251. #pragma mark - Create CSR & Encrypt/Decrypt Private Key
  252. #
  253. - (NSString *)createCSR:(NSString *)userId directory:(NSString *)directory
  254. {
  255. // Create Certificate, if do not exists
  256. if (!_csrData) {
  257. if (![self generateCertificateX509WithUserId:userId directory:directory])
  258. return nil;
  259. }
  260. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  261. return csr;
  262. }
  263. - (NSString *)encryptPrivateKey:(NSString *)userId directory:(NSString *)directory passphrase:(NSString *)passphrase privateKey:(NSString **)privateKey iterationCount:(unsigned int)iterationCount
  264. {
  265. NSMutableData *cipher = [NSMutableData new];
  266. if (!_privateKeyData) {
  267. if (![self generateCertificateX509WithUserId:userId directory:directory])
  268. return nil;
  269. }
  270. NSMutableData *key = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  271. NSData *salt = [self generateSalt:AES_SALT_LENGTH];
  272. // Remove all whitespaces from passphrase
  273. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  274. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA1, iterationCount, key.mutableBytes, key.length);
  275. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  276. NSData *authenticationTag = [NSData new];
  277. NSString *pkEncoded = [_privateKeyData base64EncodedStringWithOptions:0];
  278. NSData *pkEncodedData = [pkEncoded dataUsingEncoding:NSUTF8StringEncoding];
  279. BOOL result = [self encryptData:pkEncodedData cipher:&cipher key:key keyLen:AES_KEY_256_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  280. if (result && cipher) {
  281. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  282. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  283. NSString *saltString = [salt base64EncodedStringWithOptions:0];
  284. NSString *encryptPrivateKey = [NSString stringWithFormat:@"%@%@%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString, IV_DELIMITER_ENCODED, saltString];
  285. *privateKey = [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding];
  286. return encryptPrivateKey;
  287. } else {
  288. return nil;
  289. }
  290. }
  291. - (NSData *)decryptPrivateKey:(NSString *)privateKey passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey iterationCount:(unsigned int)iterationCount
  292. {
  293. NSMutableData *plain = [NSMutableData new];
  294. // Key
  295. NSMutableData *key = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH/8];
  296. // Split
  297. NSArray *cipherArray = [privateKey componentsSeparatedByString:IV_DELIMITER_ENCODED];
  298. if (cipherArray.count != 3) {
  299. cipherArray = [privateKey componentsSeparatedByString:IV_DELIMITER_ENCODED_OLD];
  300. if (cipherArray.count != 3) {
  301. return nil;
  302. }
  303. }
  304. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:cipherArray[0] options:0];
  305. NSString *authenticationTagString = [privateKey substringWithRange:NSMakeRange([(NSString *)cipherArray[0] length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  306. NSData *authenticationTag = [[NSData alloc] initWithBase64EncodedString:authenticationTagString options:0];
  307. NSData *initializationVector = [[NSData alloc] initWithBase64EncodedString:cipherArray[1] options:0];
  308. NSData *salt = [[NSData alloc] initWithBase64EncodedString:cipherArray[2] options:0];
  309. // Remove Authentication Tag
  310. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  311. // Remove all whitespaces from passphrase
  312. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  313. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA1, iterationCount, key.mutableBytes, key.length);
  314. BOOL result = [self decryptData:cipher plain:&plain key:key keyLen:AES_KEY_256_LENGTH initializationVector:initializationVector authenticationTag:authenticationTag];
  315. if (result && plain) {
  316. return plain;
  317. }
  318. return nil;
  319. }
  320. #
  321. #pragma mark - Encrypt / Decrypt file material
  322. #
  323. - (NSString *)encryptPayloadFile:(NSData *)encrypted key:(NSString *)key
  324. {
  325. NSMutableData *cipher;
  326. NSData *authenticationTag = [NSData new];
  327. encrypted = [[encrypted base64EncodedStringWithOptions:0] dataUsingEncoding:NSUTF8StringEncoding];
  328. // Key
  329. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  330. // Initialization Vector
  331. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  332. BOOL result = [self encryptData:encrypted cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  333. if (cipher != nil && result) {
  334. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  335. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  336. NSString *payload = [NSString stringWithFormat:@"%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString];
  337. return payload;
  338. }
  339. return nil;
  340. }
  341. - (NSString *)encryptPayloadFile:(NSData *)encrypted key:(NSString *)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  342. {
  343. NSMutableData *cipher;
  344. NSData *authenticationTagData = [NSData new];
  345. encrypted = [[encrypted base64EncodedStringWithOptions:0] dataUsingEncoding:NSUTF8StringEncoding];
  346. // Key
  347. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  348. // Initialization Vector
  349. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  350. BOOL result = [self encryptData:encrypted cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  351. if (cipher != nil && result) {
  352. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  353. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  354. NSString *payload = [cipher base64EncodedStringWithOptions:0];
  355. return payload;
  356. }
  357. return nil;
  358. }
  359. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  360. {
  361. NSMutableData *plain;
  362. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  363. if (range.location == NSNotFound) {
  364. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  365. if (range.location == NSNotFound) {
  366. return nil;
  367. }
  368. }
  369. // Cipher
  370. NSString *cipher = [encrypted substringToIndex:(range.location)];
  371. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  372. // Key
  373. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  374. // Initialization Vector
  375. NSString *initializationVector = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  376. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  377. // Authentication Tag
  378. NSString *authenticationTag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  379. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  380. // Remove Authentication Tag
  381. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  382. BOOL result = [self decryptData:cipherData plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  383. if (plain != nil && result) {
  384. return plain;
  385. }
  386. return nil;
  387. }
  388. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  389. {
  390. NSMutableData *plain;
  391. // Remove initializationVector Tag if exists [ANDROID]
  392. NSString *android = [@"|" stringByAppendingString: initializationVector];
  393. encrypted = [encrypted stringByReplacingOccurrencesOfString:android withString:@""];
  394. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:encrypted options:0];
  395. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  396. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  397. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  398. // Remove Authentication Tag
  399. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  400. BOOL result = [self decryptData:cipher plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  401. if (plain != nil && result && plain.length > 0) {
  402. return plain;
  403. }
  404. return nil;
  405. }
  406. #
  407. #pragma mark - Encrypt / Decrypt file
  408. #
  409. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  410. {
  411. NSData *authenticationTagData;
  412. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  413. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  414. BOOL result = [self encryptFile:[NSString stringWithFormat:@"%@/%@", directory, fileName] fileNameCipher:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  415. if (result) {
  416. *key = [keyData base64EncodedStringWithOptions:0];
  417. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  418. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  419. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  420. return false;
  421. } else {
  422. return true;
  423. }
  424. }
  425. return false;
  426. }
  427. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  428. {
  429. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  430. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  431. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  432. return [self decryptFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] fileNamePlain:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  433. }
  434. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  435. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  436. #
  437. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  438. #
  439. #
  440. #pragma mark - Encrypt/Decrypt asymmetric
  441. #
  442. - (NSData *)encryptAsymmetricData:(NSData *)plainData privateKey:(NSString *)privateKey
  443. {
  444. EVP_PKEY *key = NULL;
  445. int status = 0;
  446. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  447. BIO *bio = BIO_new_mem_buf(pKey, -1);
  448. if (!bio)
  449. return nil;
  450. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  451. if (!key)
  452. return nil;
  453. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  454. if (!ctx)
  455. return nil;
  456. status = EVP_PKEY_encrypt_init(ctx);
  457. if (status <= 0)
  458. return nil;
  459. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  460. if (status <= 0)
  461. return nil;
  462. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  463. if (status <= 0)
  464. return nil;
  465. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  466. if (status <= 0)
  467. return nil;
  468. unsigned long outLen = 0;
  469. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  470. if (status <= 0 || outLen == 0)
  471. return nil;
  472. unsigned char *out = (unsigned char *) malloc(outLen);
  473. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  474. if (status <= 0)
  475. return nil;
  476. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  477. if (out)
  478. free(out);
  479. return outData;
  480. }
  481. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  482. {
  483. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  484. int status = 0;
  485. BIO *bio = BIO_new_mem_buf(pKey, -1);
  486. if (!bio)
  487. return nil;
  488. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  489. if (!key)
  490. return nil;
  491. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  492. if (!ctx)
  493. return nil;
  494. status = EVP_PKEY_decrypt_init(ctx);
  495. if (status <= 0)
  496. return nil;
  497. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  498. if (status <= 0)
  499. return nil;
  500. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  501. if (status <= 0)
  502. return nil;
  503. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  504. if (status <= 0)
  505. return nil;
  506. unsigned long outLen = 0;
  507. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  508. if (status <= 0 || outLen == 0)
  509. return nil;
  510. unsigned char *out = (unsigned char *) malloc(outLen);
  511. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  512. if (status <= 0)
  513. return nil;
  514. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  515. if (out)
  516. free(out);
  517. return outData;
  518. }
  519. #
  520. #pragma mark - AES/GCM/NoPadding
  521. #
  522. // Encryption data using GCM mode
  523. - (BOOL)encryptData:(NSData *)plain cipher:(NSMutableData **)cipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  524. {
  525. int status = 0;
  526. int len = 0;
  527. // set up key
  528. len = keyLen;
  529. unsigned char cKey[len];
  530. bzero(cKey, sizeof(cKey));
  531. [key getBytes:cKey length:len];
  532. // set up ivec
  533. len = AES_IVEC_LENGTH;
  534. unsigned char cIV[len];
  535. bzero(cIV, sizeof(cIV));
  536. [initializationVector getBytes:cIV length:len];
  537. // set up tag
  538. len = AES_GCM_TAG_LENGTH;
  539. unsigned char cTag[len];
  540. bzero(cTag, sizeof(cTag));
  541. // Create and initialise the context
  542. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  543. if (!ctx)
  544. return NO;
  545. // Initialise the encryption operation
  546. if (keyLen == AES_KEY_128_LENGTH)
  547. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  548. else if (keyLen == AES_KEY_256_LENGTH)
  549. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  550. if (status <= 0) {
  551. EVP_CIPHER_CTX_free(ctx);
  552. return NO;
  553. }
  554. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  555. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  556. if (status <= 0) {
  557. EVP_CIPHER_CTX_free(ctx);
  558. return NO;
  559. }
  560. // Initialise key and IV
  561. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  562. if (status <= 0) {
  563. EVP_CIPHER_CTX_free(ctx);
  564. return NO;
  565. }
  566. // Provide the message to be encrypted, and obtain the encrypted output
  567. *cipher = [NSMutableData dataWithLength:[plain length]];
  568. unsigned char * cCipher = [*cipher mutableBytes];
  569. int cCipherLen = 0;
  570. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  571. if (status <= 0) {
  572. EVP_CIPHER_CTX_free(ctx);
  573. return NO;
  574. }
  575. // Finalise the encryption
  576. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  577. if (status <= 0) {
  578. EVP_CIPHER_CTX_free(ctx);
  579. return NO;
  580. }
  581. // Get the tag
  582. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  583. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  584. // Append TAG
  585. [*cipher appendData:*authenticationTag];
  586. EVP_CIPHER_CTX_free(ctx);
  587. return status; // OpenSSL uses 1 for success
  588. }
  589. // Encryption file using GCM mode
  590. - (BOOL)encryptFile:(NSString *)fileName fileNameCipher:(NSString *)fileNameCipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  591. {
  592. int status = 0;
  593. int len = 0;
  594. // set up key
  595. len = keyLen;
  596. unsigned char cKey[len];
  597. bzero(cKey, sizeof(cKey));
  598. [key getBytes:cKey length:len];
  599. // set up ivec
  600. len = AES_IVEC_LENGTH;
  601. unsigned char cIV[len];
  602. bzero(cIV, sizeof(cIV));
  603. [initializationVector getBytes:cIV length:len];
  604. // set up tag
  605. len = AES_GCM_TAG_LENGTH;
  606. unsigned char cTag[len];
  607. bzero(cTag, sizeof(cTag));
  608. // Create and initialise the context
  609. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  610. if (!ctx) {
  611. return NO;
  612. }
  613. // Initialise the encryption operation
  614. if (keyLen == AES_KEY_128_LENGTH)
  615. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  616. else if (keyLen == AES_KEY_256_LENGTH)
  617. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  618. if (status <= 0) {
  619. EVP_CIPHER_CTX_free(ctx);
  620. return NO;
  621. }
  622. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  623. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  624. if (status <= 0) {
  625. EVP_CIPHER_CTX_free(ctx);
  626. return NO;
  627. }
  628. // Initialise key and IV
  629. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  630. if (status <= 0) {
  631. EVP_CIPHER_CTX_free(ctx);
  632. return NO;
  633. }
  634. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  635. [inStream open];
  636. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNameCipher append:false];
  637. [outStream open];
  638. Byte buffer[streamBuffer];
  639. NSInteger totalNumberOfBytesWritten = 0;
  640. int cCipherLen = 0;
  641. unsigned char *cCipher;
  642. while ([inStream hasBytesAvailable]) {
  643. @autoreleasepool {
  644. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  645. if (bytesRead > 0) {
  646. cCipher = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  647. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  648. if (status <= 0) {
  649. [inStream close];
  650. [outStream close];
  651. EVP_CIPHER_CTX_free(ctx);
  652. return NO;
  653. }
  654. if ([outStream hasSpaceAvailable]) {
  655. totalNumberOfBytesWritten = [outStream write:cCipher maxLength:cCipherLen];
  656. if (totalNumberOfBytesWritten != cCipherLen) {
  657. [inStream close];
  658. [outStream close];
  659. EVP_CIPHER_CTX_free(ctx);
  660. return NO;
  661. }
  662. }
  663. }
  664. }
  665. }
  666. [inStream close];
  667. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  668. if (status <= 0) {
  669. [outStream close];
  670. EVP_CIPHER_CTX_free(ctx);
  671. return NO;
  672. }
  673. // Get the tag
  674. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  675. if (status <= 0) {
  676. [outStream close];
  677. EVP_CIPHER_CTX_free(ctx);
  678. return NO;
  679. }
  680. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  681. // Append TAG
  682. if ([outStream hasSpaceAvailable]) {
  683. totalNumberOfBytesWritten = [outStream write:cTag maxLength:sizeof(cTag)];
  684. if (totalNumberOfBytesWritten != sizeof(cTag)) {
  685. status = NO;
  686. }
  687. } else {
  688. status = NO;
  689. }
  690. [outStream close];
  691. EVP_CIPHER_CTX_free(ctx);
  692. return status; // OpenSSL uses 1 for success
  693. }
  694. // Decryption data using GCM mode
  695. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  696. {
  697. int status = 0;
  698. int len = 0;
  699. // set up key
  700. len = keyLen;
  701. unsigned char cKey[len];
  702. bzero(cKey, sizeof(cKey));
  703. [key getBytes:cKey length:len];
  704. // set up ivec
  705. len = (int)[initializationVector length];
  706. unsigned char cIV[len];
  707. bzero(cIV, sizeof(cIV));
  708. [initializationVector getBytes:cIV length:len];
  709. // set up tag
  710. len = (int)[authenticationTag length];;
  711. unsigned char cTag[len];
  712. bzero(cTag, sizeof(cTag));
  713. [authenticationTag getBytes:cTag length:len];
  714. // Create and initialise the context
  715. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  716. if (!ctx)
  717. return NO;
  718. // Initialise the decryption operation
  719. if (keyLen == AES_KEY_128_LENGTH)
  720. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  721. else if (keyLen == AES_KEY_256_LENGTH)
  722. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  723. if (status <= 0) {
  724. EVP_CIPHER_CTX_free(ctx);
  725. return NO;
  726. }
  727. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  728. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  729. if (status <= 0) {
  730. EVP_CIPHER_CTX_free(ctx);
  731. return NO;
  732. }
  733. // Initialise key and IV
  734. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  735. if (status <= 0) {
  736. EVP_CIPHER_CTX_free(ctx);
  737. return NO;
  738. }
  739. // Provide the message to be decrypted, and obtain the plaintext output
  740. *plain = [NSMutableData dataWithLength:([cipher length])];
  741. int cPlainLen = 0;
  742. unsigned char * cPlain = [*plain mutableBytes];
  743. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  744. if (status <= 0) {
  745. EVP_CIPHER_CTX_free(ctx);
  746. return NO;
  747. }
  748. // Tag is the last 16 bytes
  749. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  750. if (status <= 0) {
  751. EVP_CIPHER_CTX_free(ctx);
  752. return NO;
  753. }
  754. // Finalise the encryption
  755. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  756. // Free
  757. EVP_CIPHER_CTX_free(ctx);
  758. return status; // OpenSSL uses 1 for success
  759. }
  760. // Decryption file using GCM mode
  761. - (BOOL)decryptFile:(NSString *)fileName fileNamePlain:(NSString *)fileNamePlain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  762. {
  763. int status = 0;
  764. int len = 0;
  765. // set up key
  766. len = keyLen;
  767. unsigned char cKey[len];
  768. bzero(cKey, sizeof(cKey));
  769. [key getBytes:cKey length:len];
  770. // set up ivec
  771. len = (int)[initializationVector length];
  772. unsigned char cIV[len];
  773. bzero(cIV, sizeof(cIV));
  774. [initializationVector getBytes:cIV length:len];
  775. // set up tag
  776. len = (int)[authenticationTag length];;
  777. unsigned char cTag[len];
  778. bzero(cTag, sizeof(cTag));
  779. [authenticationTag getBytes:cTag length:len];
  780. // Create and initialise the context
  781. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  782. if (!ctx)
  783. return NO;
  784. // Initialise the decryption operation
  785. if (keyLen == AES_KEY_128_LENGTH)
  786. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  787. else if (keyLen == AES_KEY_256_LENGTH)
  788. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  789. if (status <= 0) {
  790. EVP_CIPHER_CTX_free(ctx);
  791. return NO;
  792. }
  793. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  794. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  795. if (status <= 0) {
  796. EVP_CIPHER_CTX_free(ctx);
  797. return NO;
  798. }
  799. // Initialise key and IV
  800. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  801. if (status <= 0) {
  802. EVP_CIPHER_CTX_free(ctx);
  803. return NO;
  804. }
  805. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  806. [inStream open];
  807. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNamePlain append:false];
  808. [outStream open];
  809. Byte buffer[streamBuffer];
  810. NSInteger totalNumberOfBytesWritten = 0;
  811. int cPlainLen = 0;
  812. unsigned char *cPlain;
  813. while ([inStream hasBytesAvailable]) {
  814. @autoreleasepool {
  815. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  816. if (bytesRead > 0) {
  817. cPlain = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  818. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  819. if (status <= 0) {
  820. [inStream close];
  821. [outStream close];
  822. EVP_CIPHER_CTX_free(ctx);
  823. return NO;
  824. }
  825. if ([outStream hasSpaceAvailable]) {
  826. totalNumberOfBytesWritten = [outStream write:cPlain maxLength:cPlainLen];
  827. if (totalNumberOfBytesWritten != cPlainLen) {
  828. [inStream close];
  829. [outStream close];
  830. EVP_CIPHER_CTX_free(ctx);
  831. return NO;
  832. }
  833. }
  834. }
  835. }
  836. }
  837. [inStream close];
  838. [outStream close];
  839. // Tag is the last 16 bytes
  840. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  841. if (status <= 0)
  842. return NO;
  843. // Finalise the encryption
  844. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  845. // Free
  846. EVP_CIPHER_CTX_free(ctx);
  847. return status; // OpenSSL uses 1 for success
  848. }
  849. #
  850. #pragma mark - CMS
  851. #
  852. - (NSData *)generateSignatureCMS:(NSData *)data certificate:(NSString *)certificate privateKey:(NSString *)privateKey publicKey:(NSString *)publicKey userId:(NSString *)userId
  853. {
  854. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  855. unsigned char *certKey = (unsigned char *)[certificate UTF8String];
  856. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  857. BIO *certKeyBIO = BIO_new_mem_buf(certKey, -1);
  858. if (!certKeyBIO)
  859. return nil;
  860. X509 *x509 = PEM_read_bio_X509(certKeyBIO, NULL, 0, NULL);
  861. if (!x509)
  862. return nil;
  863. BIO *pkeyBIO = BIO_new_mem_buf(pKey, -1);
  864. EVP_PKEY *key = PEM_read_bio_PrivateKey(pkeyBIO, NULL, NULL, NULL);
  865. if (!key)
  866. return nil;
  867. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  868. CMS_ContentInfo *contentInfo = CMS_sign(x509, key, NULL, dataBIO, CMS_DETACHED);
  869. if (contentInfo == nil)
  870. return nil;
  871. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  872. PEM_write_bio_CMS(printBIO, contentInfo);
  873. BIO *i2dCmsBioOut = BIO_new(BIO_s_mem());
  874. if (i2d_CMS_bio(i2dCmsBioOut, contentInfo) != 1)
  875. return nil;
  876. int len = BIO_pending(i2dCmsBioOut);
  877. char *keyBytes = malloc(len);
  878. BIO_read(i2dCmsBioOut, keyBytes, len);
  879. NSData *i2dCmsData = [NSData dataWithBytes:keyBytes length:len];
  880. // TEST
  881. [self verifySignatureCMS:i2dCmsData data:data publicKey:publicKey userId:userId];
  882. BIO_free(printBIO);
  883. BIO_free(certKeyBIO);
  884. BIO_free(pkeyBIO);
  885. BIO_free(dataBIO);
  886. BIO_free(i2dCmsBioOut);
  887. return i2dCmsData;
  888. }
  889. - (BOOL)verifySignatureCMS:(NSData *)cmsContent data:(NSData *)data publicKey:(NSString *)publicKey userId:(NSString *)userId
  890. {
  891. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  892. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  893. BIO *cmsBIO = BIO_new_mem_buf(cmsContent.bytes, (int)cmsContent.length);
  894. CMS_ContentInfo *contentInfo = d2i_CMS_bio(cmsBIO, NULL);
  895. unsigned char *publicKeyUTF8 = (unsigned char *)[publicKey UTF8String];
  896. BIO *publicKeyBIO = BIO_new_mem_buf(publicKeyUTF8, -1);
  897. EVP_PKEY *pkey = PEM_read_bio_PUBKEY(publicKeyBIO, NULL, NULL, NULL);
  898. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  899. BOOL verifyResult = CMS_verify(contentInfo, NULL, NULL, dataBIO, NULL, CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY);
  900. if (verifyResult) {
  901. STACK_OF(X509) *signers = CMS_get0_signers(contentInfo);
  902. int numSigners = sk_X509_num(signers);
  903. for (int i = 0; i < numSigners; ++i) {
  904. X509 *signer = sk_X509_value(signers, i);
  905. int result = X509_verify(signer, pkey);
  906. if (result <= 0) {
  907. verifyResult = false;
  908. break;
  909. }
  910. int cnDataLength = X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, 0, 0);
  911. cnDataLength += 1;
  912. NSMutableData* cnData = [NSMutableData dataWithLength:cnDataLength];
  913. X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, [cnData mutableBytes], cnDataLength);
  914. NSString *cn = [[NSString alloc] initWithCString:[cnData mutableBytes] encoding:NSUTF8StringEncoding];
  915. if ([userId isEqualToString:cn]) {
  916. verifyResult = true;
  917. break;
  918. } else {
  919. verifyResult = false;
  920. }
  921. }
  922. if (signers) {
  923. sk_X509_free(signers);
  924. }
  925. signers = NULL;
  926. }
  927. BIO_free(dataBIO);
  928. BIO_free(printBIO);
  929. BIO_free(cmsBIO);
  930. BIO_free(publicKeyBIO);
  931. return verifyResult;
  932. }
  933. #
  934. #pragma mark - Utility
  935. #
  936. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  937. {
  938. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  939. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  940. *key = [keyData base64EncodedStringWithOptions:0];
  941. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  942. }
  943. - (NSString *)createSHA256:(NSData *)data
  944. {
  945. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  946. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  947. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  948. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  949. [output appendFormat:@"%02x", digest[i]];
  950. return output;
  951. }
  952. - (NSString *)createSHA512:(NSString *)string
  953. {
  954. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  955. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  956. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  957. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  958. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  959. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  960. [output appendFormat:@"%02x", digest[i]];
  961. return output;
  962. }
  963. - (NSData *)generateIV:(int)length
  964. {
  965. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  966. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  967. return ivData;
  968. }
  969. - (NSData *)generateSalt:(int)length
  970. {
  971. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  972. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  973. return saltData;
  974. }
  975. - (NSData *)generateKey:(int)length
  976. {
  977. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  978. unsigned char *pKeyData = [keyData mutableBytes];
  979. RAND_bytes(pKeyData, length);
  980. return keyData;
  981. }
  982. - (NSData *)generateKey
  983. {
  984. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  985. unsigned char *pKeyData = [keyData mutableBytes];
  986. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  987. return keyData;
  988. }
  989. - (NSString *)getSHA1:(NSString *)input
  990. {
  991. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  992. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  993. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  994. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  995. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  996. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  997. [output appendFormat:@"%02x", digest[i]];
  998. return output;
  999. }
  1000. - (NSData *)hashValueMD5OfData:(NSData *)data
  1001. {
  1002. MD5_CTX md5Ctx;
  1003. unsigned char hashValue[MD5_DIGEST_LENGTH];
  1004. if(!MD5_Init(&md5Ctx)) {
  1005. return nil;
  1006. }
  1007. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  1008. return nil;
  1009. }
  1010. if (!MD5_Final(hashValue, &md5Ctx)) {
  1011. return nil;
  1012. }
  1013. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  1014. }
  1015. - (NSString *)hexadecimalString:(NSData *)input
  1016. {
  1017. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  1018. if (!dataBuffer) {
  1019. return [NSString string];
  1020. }
  1021. NSUInteger dataLength = [input length];
  1022. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  1023. for (int i = 0; i < dataLength; ++i) {
  1024. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  1025. }
  1026. return [NSString stringWithString:hexString];
  1027. }
  1028. - (NSString *)derToPemPrivateKey:(NSString *)input
  1029. {
  1030. NSInteger substringLength = 65;
  1031. NSMutableString *result = [NSMutableString stringWithString: input];
  1032. for(long i=substringLength;i<=input.length;i++) {
  1033. [result insertString: @"\n" atIndex: i];
  1034. i+=substringLength;
  1035. }
  1036. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  1037. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  1038. return result;
  1039. }
  1040. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  1041. {
  1042. char *buf[256];
  1043. FILE *pFile;
  1044. NSString *pkey_string;
  1045. pFile = fmemopen(buf, sizeof(buf), "w");
  1046. PEM_write_PUBKEY(pFile,pubkey);
  1047. fputc('\0', pFile);
  1048. fclose(pFile);
  1049. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  1050. return pkey_string;
  1051. }
  1052. @end