NCEndToEndEncryption.m 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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. // Key
  328. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  329. // Initialization Vector
  330. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  331. BOOL result = [self encryptData:encrypted cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  332. if (cipher != nil && result) {
  333. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  334. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  335. NSString *payload = [NSString stringWithFormat:@"%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString];
  336. return payload;
  337. }
  338. return nil;
  339. }
  340. - (NSString *)encryptPayloadFile:(NSData *)encrypted key:(NSString *)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  341. {
  342. NSMutableData *cipher;
  343. NSData *authenticationTagData = [NSData new];
  344. // Key
  345. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  346. // Initialization Vector
  347. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  348. BOOL result = [self encryptData:encrypted cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  349. if (cipher != nil && result) {
  350. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  351. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  352. NSString *payload = [cipher base64EncodedStringWithOptions:0];
  353. return payload;
  354. }
  355. return nil;
  356. }
  357. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  358. {
  359. NSMutableData *plain;
  360. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  361. if (range.location == NSNotFound) {
  362. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  363. if (range.location == NSNotFound) {
  364. return nil;
  365. }
  366. }
  367. // Cipher
  368. NSString *cipher = [encrypted substringToIndex:(range.location)];
  369. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  370. // Key
  371. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  372. // Initialization Vector
  373. NSString *initializationVector = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  374. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  375. // Authentication Tag
  376. NSString *authenticationTag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  377. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  378. // Remove Authentication Tag
  379. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  380. BOOL result = [self decryptData:cipherData plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  381. if (plain != nil && result) {
  382. return plain;
  383. }
  384. return nil;
  385. }
  386. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  387. {
  388. NSMutableData *plain;
  389. // Remove initializationVector Tag if exists [ANDROID]
  390. NSString *android = [@"|" stringByAppendingString: initializationVector];
  391. encrypted = [encrypted stringByReplacingOccurrencesOfString:android withString:@""];
  392. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:encrypted options:0];
  393. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  394. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  395. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  396. // Remove Authentication Tag
  397. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  398. BOOL result = [self decryptData:cipher plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  399. if (plain != nil && result && plain.length > 0) {
  400. return plain;
  401. }
  402. return nil;
  403. }
  404. #
  405. #pragma mark - Encrypt / Decrypt file
  406. #
  407. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  408. {
  409. NSData *authenticationTagData;
  410. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  411. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  412. BOOL result = [self encryptFile:[NSString stringWithFormat:@"%@/%@", directory, fileName] fileNameCipher:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  413. if (result) {
  414. *key = [keyData base64EncodedStringWithOptions:0];
  415. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  416. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  417. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  418. return false;
  419. } else {
  420. return true;
  421. }
  422. }
  423. return false;
  424. }
  425. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  426. {
  427. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  428. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  429. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  430. 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];
  431. }
  432. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  433. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  434. #
  435. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  436. #
  437. #
  438. #pragma mark - Encrypt/Decrypt asymmetric
  439. #
  440. - (NSData *)encryptAsymmetricData:(NSData *)plainData privateKey:(NSString *)privateKey
  441. {
  442. EVP_PKEY *key = NULL;
  443. int status = 0;
  444. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  445. BIO *bio = BIO_new_mem_buf(pKey, -1);
  446. if (!bio)
  447. return nil;
  448. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  449. if (!key)
  450. return nil;
  451. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  452. if (!ctx)
  453. return nil;
  454. status = EVP_PKEY_encrypt_init(ctx);
  455. if (status <= 0)
  456. return nil;
  457. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  458. if (status <= 0)
  459. return nil;
  460. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  461. if (status <= 0)
  462. return nil;
  463. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  464. if (status <= 0)
  465. return nil;
  466. unsigned long outLen = 0;
  467. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  468. if (status <= 0 || outLen == 0)
  469. return nil;
  470. unsigned char *out = (unsigned char *) malloc(outLen);
  471. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  472. if (status <= 0)
  473. return nil;
  474. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  475. if (out)
  476. free(out);
  477. return outData;
  478. }
  479. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  480. {
  481. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  482. int status = 0;
  483. BIO *bio = BIO_new_mem_buf(pKey, -1);
  484. if (!bio)
  485. return nil;
  486. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  487. if (!key)
  488. return nil;
  489. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  490. if (!ctx)
  491. return nil;
  492. status = EVP_PKEY_decrypt_init(ctx);
  493. if (status <= 0)
  494. return nil;
  495. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  496. if (status <= 0)
  497. return nil;
  498. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  499. if (status <= 0)
  500. return nil;
  501. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  502. if (status <= 0)
  503. return nil;
  504. unsigned long outLen = 0;
  505. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  506. if (status <= 0 || outLen == 0)
  507. return nil;
  508. unsigned char *out = (unsigned char *) malloc(outLen);
  509. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  510. if (status <= 0)
  511. return nil;
  512. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  513. if (out)
  514. free(out);
  515. return outData;
  516. }
  517. #
  518. #pragma mark - AES/GCM/NoPadding
  519. #
  520. // Encryption data using GCM mode
  521. - (BOOL)encryptData:(NSData *)plain cipher:(NSMutableData **)cipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  522. {
  523. int status = 0;
  524. int len = 0;
  525. // set up key
  526. len = keyLen;
  527. unsigned char cKey[len];
  528. bzero(cKey, sizeof(cKey));
  529. [key getBytes:cKey length:len];
  530. // set up ivec
  531. len = AES_IVEC_LENGTH;
  532. unsigned char cIV[len];
  533. bzero(cIV, sizeof(cIV));
  534. [initializationVector getBytes:cIV length:len];
  535. // set up tag
  536. len = AES_GCM_TAG_LENGTH;
  537. unsigned char cTag[len];
  538. bzero(cTag, sizeof(cTag));
  539. // Create and initialise the context
  540. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  541. if (!ctx)
  542. return NO;
  543. // Initialise the encryption operation
  544. if (keyLen == AES_KEY_128_LENGTH)
  545. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  546. else if (keyLen == AES_KEY_256_LENGTH)
  547. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  548. if (status <= 0) {
  549. EVP_CIPHER_CTX_free(ctx);
  550. return NO;
  551. }
  552. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  553. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  554. if (status <= 0) {
  555. EVP_CIPHER_CTX_free(ctx);
  556. return NO;
  557. }
  558. // Initialise key and IV
  559. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  560. if (status <= 0) {
  561. EVP_CIPHER_CTX_free(ctx);
  562. return NO;
  563. }
  564. // Provide the message to be encrypted, and obtain the encrypted output
  565. *cipher = [NSMutableData dataWithLength:[plain length]];
  566. unsigned char * cCipher = [*cipher mutableBytes];
  567. int cCipherLen = 0;
  568. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  569. if (status <= 0) {
  570. EVP_CIPHER_CTX_free(ctx);
  571. return NO;
  572. }
  573. // Finalise the encryption
  574. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  575. if (status <= 0) {
  576. EVP_CIPHER_CTX_free(ctx);
  577. return NO;
  578. }
  579. // Get the tag
  580. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  581. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  582. // Append TAG
  583. [*cipher appendData:*authenticationTag];
  584. EVP_CIPHER_CTX_free(ctx);
  585. return status; // OpenSSL uses 1 for success
  586. }
  587. // Encryption file using GCM mode
  588. - (BOOL)encryptFile:(NSString *)fileName fileNameCipher:(NSString *)fileNameCipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  589. {
  590. int status = 0;
  591. int len = 0;
  592. // set up key
  593. len = keyLen;
  594. unsigned char cKey[len];
  595. bzero(cKey, sizeof(cKey));
  596. [key getBytes:cKey length:len];
  597. // set up ivec
  598. len = AES_IVEC_LENGTH;
  599. unsigned char cIV[len];
  600. bzero(cIV, sizeof(cIV));
  601. [initializationVector getBytes:cIV length:len];
  602. // set up tag
  603. len = AES_GCM_TAG_LENGTH;
  604. unsigned char cTag[len];
  605. bzero(cTag, sizeof(cTag));
  606. // Create and initialise the context
  607. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  608. if (!ctx) {
  609. return NO;
  610. }
  611. // Initialise the encryption operation
  612. if (keyLen == AES_KEY_128_LENGTH)
  613. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  614. else if (keyLen == AES_KEY_256_LENGTH)
  615. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  616. if (status <= 0) {
  617. EVP_CIPHER_CTX_free(ctx);
  618. return NO;
  619. }
  620. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  621. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  622. if (status <= 0) {
  623. EVP_CIPHER_CTX_free(ctx);
  624. return NO;
  625. }
  626. // Initialise key and IV
  627. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  628. if (status <= 0) {
  629. EVP_CIPHER_CTX_free(ctx);
  630. return NO;
  631. }
  632. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  633. [inStream open];
  634. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNameCipher append:false];
  635. [outStream open];
  636. Byte buffer[streamBuffer];
  637. NSInteger totalNumberOfBytesWritten = 0;
  638. int cCipherLen = 0;
  639. unsigned char *cCipher;
  640. while ([inStream hasBytesAvailable]) {
  641. @autoreleasepool {
  642. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  643. if (bytesRead > 0) {
  644. cCipher = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  645. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  646. if (status <= 0) {
  647. [inStream close];
  648. [outStream close];
  649. EVP_CIPHER_CTX_free(ctx);
  650. return NO;
  651. }
  652. if ([outStream hasSpaceAvailable]) {
  653. totalNumberOfBytesWritten = [outStream write:cCipher maxLength:cCipherLen];
  654. if (totalNumberOfBytesWritten != cCipherLen) {
  655. [inStream close];
  656. [outStream close];
  657. EVP_CIPHER_CTX_free(ctx);
  658. return NO;
  659. }
  660. }
  661. }
  662. }
  663. }
  664. [inStream close];
  665. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  666. if (status <= 0) {
  667. [outStream close];
  668. EVP_CIPHER_CTX_free(ctx);
  669. return NO;
  670. }
  671. // Get the tag
  672. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  673. if (status <= 0) {
  674. [outStream close];
  675. EVP_CIPHER_CTX_free(ctx);
  676. return NO;
  677. }
  678. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  679. // Append TAG
  680. if ([outStream hasSpaceAvailable]) {
  681. totalNumberOfBytesWritten = [outStream write:cTag maxLength:sizeof(cTag)];
  682. if (totalNumberOfBytesWritten != sizeof(cTag)) {
  683. status = NO;
  684. }
  685. } else {
  686. status = NO;
  687. }
  688. [outStream close];
  689. EVP_CIPHER_CTX_free(ctx);
  690. return status; // OpenSSL uses 1 for success
  691. }
  692. // Decryption data using GCM mode
  693. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  694. {
  695. int status = 0;
  696. int len = 0;
  697. // set up key
  698. len = keyLen;
  699. unsigned char cKey[len];
  700. bzero(cKey, sizeof(cKey));
  701. [key getBytes:cKey length:len];
  702. // set up ivec
  703. len = (int)[initializationVector length];
  704. unsigned char cIV[len];
  705. bzero(cIV, sizeof(cIV));
  706. [initializationVector getBytes:cIV length:len];
  707. // set up tag
  708. len = (int)[authenticationTag length];;
  709. unsigned char cTag[len];
  710. bzero(cTag, sizeof(cTag));
  711. [authenticationTag getBytes:cTag length:len];
  712. // Create and initialise the context
  713. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  714. if (!ctx)
  715. return NO;
  716. // Initialise the decryption operation
  717. if (keyLen == AES_KEY_128_LENGTH)
  718. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  719. else if (keyLen == AES_KEY_256_LENGTH)
  720. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  721. if (status <= 0) {
  722. EVP_CIPHER_CTX_free(ctx);
  723. return NO;
  724. }
  725. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  726. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  727. if (status <= 0) {
  728. EVP_CIPHER_CTX_free(ctx);
  729. return NO;
  730. }
  731. // Initialise key and IV
  732. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  733. if (status <= 0) {
  734. EVP_CIPHER_CTX_free(ctx);
  735. return NO;
  736. }
  737. // Provide the message to be decrypted, and obtain the plaintext output
  738. *plain = [NSMutableData dataWithLength:([cipher length])];
  739. int cPlainLen = 0;
  740. unsigned char * cPlain = [*plain mutableBytes];
  741. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  742. if (status <= 0) {
  743. EVP_CIPHER_CTX_free(ctx);
  744. return NO;
  745. }
  746. // Tag is the last 16 bytes
  747. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  748. if (status <= 0) {
  749. EVP_CIPHER_CTX_free(ctx);
  750. return NO;
  751. }
  752. // Finalise the encryption
  753. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  754. // Free
  755. EVP_CIPHER_CTX_free(ctx);
  756. return status; // OpenSSL uses 1 for success
  757. }
  758. // Decryption file using GCM mode
  759. - (BOOL)decryptFile:(NSString *)fileName fileNamePlain:(NSString *)fileNamePlain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  760. {
  761. int status = 0;
  762. int len = 0;
  763. // set up key
  764. len = keyLen;
  765. unsigned char cKey[len];
  766. bzero(cKey, sizeof(cKey));
  767. [key getBytes:cKey length:len];
  768. // set up ivec
  769. len = (int)[initializationVector length];
  770. unsigned char cIV[len];
  771. bzero(cIV, sizeof(cIV));
  772. [initializationVector getBytes:cIV length:len];
  773. // set up tag
  774. len = (int)[authenticationTag length];;
  775. unsigned char cTag[len];
  776. bzero(cTag, sizeof(cTag));
  777. [authenticationTag getBytes:cTag length:len];
  778. // Create and initialise the context
  779. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  780. if (!ctx)
  781. return NO;
  782. // Initialise the decryption operation
  783. if (keyLen == AES_KEY_128_LENGTH)
  784. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  785. else if (keyLen == AES_KEY_256_LENGTH)
  786. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  787. if (status <= 0) {
  788. EVP_CIPHER_CTX_free(ctx);
  789. return NO;
  790. }
  791. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  792. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  793. if (status <= 0) {
  794. EVP_CIPHER_CTX_free(ctx);
  795. return NO;
  796. }
  797. // Initialise key and IV
  798. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  799. if (status <= 0) {
  800. EVP_CIPHER_CTX_free(ctx);
  801. return NO;
  802. }
  803. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  804. [inStream open];
  805. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNamePlain append:false];
  806. [outStream open];
  807. Byte buffer[streamBuffer];
  808. NSInteger totalNumberOfBytesWritten = 0;
  809. int cPlainLen = 0;
  810. unsigned char *cPlain;
  811. while ([inStream hasBytesAvailable]) {
  812. @autoreleasepool {
  813. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  814. if (bytesRead > 0) {
  815. cPlain = [[NSMutableData dataWithLength:bytesRead] mutableBytes];
  816. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [[NSData dataWithBytes:buffer length:bytesRead] bytes], (int)bytesRead);
  817. if (status <= 0) {
  818. [inStream close];
  819. [outStream close];
  820. EVP_CIPHER_CTX_free(ctx);
  821. return NO;
  822. }
  823. if ([outStream hasSpaceAvailable]) {
  824. totalNumberOfBytesWritten = [outStream write:cPlain maxLength:cPlainLen];
  825. if (totalNumberOfBytesWritten != cPlainLen) {
  826. [inStream close];
  827. [outStream close];
  828. EVP_CIPHER_CTX_free(ctx);
  829. return NO;
  830. }
  831. }
  832. }
  833. }
  834. }
  835. [inStream close];
  836. [outStream close];
  837. // Tag is the last 16 bytes
  838. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  839. if (status <= 0)
  840. return NO;
  841. // Finalise the encryption
  842. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  843. // Free
  844. EVP_CIPHER_CTX_free(ctx);
  845. return status; // OpenSSL uses 1 for success
  846. }
  847. #
  848. #pragma mark - CMS
  849. #
  850. - (NSData *)generateSignatureCMS:(NSData *)data certificate:(NSString *)certificate privateKey:(NSString *)privateKey publicKey:(NSString *)publicKey userId:(NSString *)userId
  851. {
  852. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  853. unsigned char *certKey = (unsigned char *)[certificate UTF8String];
  854. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  855. BIO *certKeyBIO = BIO_new_mem_buf(certKey, -1);
  856. if (!certKeyBIO)
  857. return nil;
  858. X509 *x509 = PEM_read_bio_X509(certKeyBIO, NULL, 0, NULL);
  859. if (!x509)
  860. return nil;
  861. BIO *pkeyBIO = BIO_new_mem_buf(pKey, -1);
  862. EVP_PKEY *key = PEM_read_bio_PrivateKey(pkeyBIO, NULL, NULL, NULL);
  863. if (!key)
  864. return nil;
  865. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  866. CMS_ContentInfo *contentInfo = CMS_sign(x509, key, NULL, dataBIO, CMS_DETACHED);
  867. if (contentInfo == nil)
  868. return nil;
  869. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  870. PEM_write_bio_CMS(printBIO, contentInfo);
  871. BIO *i2dCmsBioOut = BIO_new(BIO_s_mem());
  872. if (i2d_CMS_bio(i2dCmsBioOut, contentInfo) != 1)
  873. return nil;
  874. int len = BIO_pending(i2dCmsBioOut);
  875. char *keyBytes = malloc(len);
  876. BIO_read(i2dCmsBioOut, keyBytes, len);
  877. NSData *i2dCmsData = [NSData dataWithBytes:keyBytes length:len];
  878. // TEST
  879. [self verifySignatureCMS:i2dCmsData data:data publicKey:publicKey userId:userId];
  880. BIO_free(printBIO);
  881. BIO_free(certKeyBIO);
  882. BIO_free(pkeyBIO);
  883. BIO_free(dataBIO);
  884. BIO_free(i2dCmsBioOut);
  885. return i2dCmsData;
  886. }
  887. - (BOOL)verifySignatureCMS:(NSData *)cmsContent data:(NSData *)data publicKey:(NSString *)publicKey userId:(NSString *)userId
  888. {
  889. BIO *dataBIO = BIO_new_mem_buf((void*)data.bytes, (int)data.length);
  890. BIO *printBIO = BIO_new_fp(stdout, BIO_NOCLOSE);
  891. BIO *cmsBIO = BIO_new_mem_buf(cmsContent.bytes, (int)cmsContent.length);
  892. CMS_ContentInfo *contentInfo = d2i_CMS_bio(cmsBIO, NULL);
  893. unsigned char *publicKeyUTF8 = (unsigned char *)[publicKey UTF8String];
  894. BIO *publicKeyBIO = BIO_new_mem_buf(publicKeyUTF8, -1);
  895. EVP_PKEY *pkey = PEM_read_bio_PUBKEY(publicKeyBIO, NULL, NULL, NULL);
  896. CMS_ContentInfo_print_ctx(printBIO, contentInfo, 0, NULL);
  897. BOOL verifyResult = CMS_verify(contentInfo, NULL, NULL, dataBIO, NULL, CMS_DETACHED | CMS_NO_SIGNER_CERT_VERIFY);
  898. if (verifyResult) {
  899. STACK_OF(X509) *signers = CMS_get0_signers(contentInfo);
  900. int numSigners = sk_X509_num(signers);
  901. for (int i = 0; i < numSigners; ++i) {
  902. X509 *signer = sk_X509_value(signers, i);
  903. int result = X509_verify(signer, pkey);
  904. if (result <= 0) {
  905. verifyResult = false;
  906. break;
  907. }
  908. int cnDataLength = X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, 0, 0);
  909. cnDataLength += 1;
  910. NSMutableData* cnData = [NSMutableData dataWithLength:cnDataLength];
  911. X509_NAME_get_text_by_NID(X509_get_subject_name(signer), NID_commonName, [cnData mutableBytes], cnDataLength);
  912. NSString *cn = [[NSString alloc] initWithCString:[cnData mutableBytes] encoding:NSUTF8StringEncoding];
  913. if ([userId isEqualToString:cn]) {
  914. verifyResult = true;
  915. break;
  916. } else {
  917. verifyResult = false;
  918. }
  919. }
  920. if (signers) {
  921. sk_X509_free(signers);
  922. }
  923. signers = NULL;
  924. }
  925. BIO_free(dataBIO);
  926. BIO_free(printBIO);
  927. BIO_free(cmsBIO);
  928. BIO_free(publicKeyBIO);
  929. return verifyResult;
  930. }
  931. #
  932. #pragma mark - Utility
  933. #
  934. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  935. {
  936. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  937. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  938. *key = [keyData base64EncodedStringWithOptions:0];
  939. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  940. }
  941. - (NSString *)createSHA256:(NSData *)data
  942. {
  943. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  944. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  945. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  946. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  947. [output appendFormat:@"%02x", digest[i]];
  948. return output;
  949. }
  950. - (NSString *)createSHA512:(NSString *)string
  951. {
  952. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  953. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  954. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  955. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  956. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  957. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  958. [output appendFormat:@"%02x", digest[i]];
  959. return output;
  960. }
  961. - (NSData *)generateIV:(int)length
  962. {
  963. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  964. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  965. return ivData;
  966. }
  967. - (NSData *)generateSalt:(int)length
  968. {
  969. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  970. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  971. return saltData;
  972. }
  973. - (NSData *)generateKey:(int)length
  974. {
  975. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  976. unsigned char *pKeyData = [keyData mutableBytes];
  977. RAND_bytes(pKeyData, length);
  978. return keyData;
  979. }
  980. - (NSData *)generateKey
  981. {
  982. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  983. unsigned char *pKeyData = [keyData mutableBytes];
  984. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  985. return keyData;
  986. }
  987. - (NSString *)getSHA1:(NSString *)input
  988. {
  989. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  990. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  991. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  992. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  993. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  994. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  995. [output appendFormat:@"%02x", digest[i]];
  996. return output;
  997. }
  998. - (NSData *)hashValueMD5OfData:(NSData *)data
  999. {
  1000. MD5_CTX md5Ctx;
  1001. unsigned char hashValue[MD5_DIGEST_LENGTH];
  1002. if(!MD5_Init(&md5Ctx)) {
  1003. return nil;
  1004. }
  1005. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  1006. return nil;
  1007. }
  1008. if (!MD5_Final(hashValue, &md5Ctx)) {
  1009. return nil;
  1010. }
  1011. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  1012. }
  1013. - (NSString *)hexadecimalString:(NSData *)input
  1014. {
  1015. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  1016. if (!dataBuffer) {
  1017. return [NSString string];
  1018. }
  1019. NSUInteger dataLength = [input length];
  1020. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  1021. for (int i = 0; i < dataLength; ++i) {
  1022. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  1023. }
  1024. return [NSString stringWithString:hexString];
  1025. }
  1026. - (NSString *)derToPemPrivateKey:(NSString *)input
  1027. {
  1028. NSInteger substringLength = 65;
  1029. NSMutableString *result = [NSMutableString stringWithString: input];
  1030. for(long i=substringLength;i<=input.length;i++) {
  1031. [result insertString: @"\n" atIndex: i];
  1032. i+=substringLength;
  1033. }
  1034. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  1035. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  1036. return result;
  1037. }
  1038. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  1039. {
  1040. char *buf[256];
  1041. FILE *pFile;
  1042. NSString *pkey_string;
  1043. pFile = fmemopen(buf, sizeof(buf), "w");
  1044. PEM_write_PUBKEY(pFile,pubkey);
  1045. fputc('\0', pFile);
  1046. fclose(pFile);
  1047. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  1048. return pkey_string;
  1049. }
  1050. @end