NCEndToEndEncryption.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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_INTERACTION_COUNT 1024
  33. #define PBKDF2_KEY_LENGTH 256
  34. //#define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  35. #define ASYMMETRIC_STRING_TEST @"Nextcloud a safe home for all your data"
  36. #define fileNameCertificate @"cert.pem"
  37. #define fileNameCSR @"csr.pem"
  38. #define fileNamePrivateKey @"privateKey.pem"
  39. #define fileNamePubliceKey @"publicKey.pem"
  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
  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, PBKDF2_INTERACTION_COUNT, 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
  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, PBKDF2_INTERACTION_COUNT, 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:(NSString *)encrypted key:(NSString *)key
  324. {
  325. NSMutableData *cipher;
  326. NSData *authenticationTag = [NSData new];
  327. NSData *encryptedData = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  328. encryptedData = [[encryptedData base64EncodedStringWithOptions:0] dataUsingEncoding:NSUTF8StringEncoding];
  329. // Key
  330. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  331. // Initialization Vector
  332. NSData *initializationVector = [self generateIV:AES_IVEC_LENGTH];
  333. BOOL result = [self encryptData:encryptedData cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVector authenticationTag:&authenticationTag];
  334. if (cipher != nil && result) {
  335. NSString *cipherString = [cipher base64EncodedStringWithOptions:0];
  336. NSString *initializationVectorString = [initializationVector base64EncodedStringWithOptions:0];
  337. NSString *payload = [NSString stringWithFormat:@"%@%@%@", cipherString, IV_DELIMITER_ENCODED, initializationVectorString];
  338. return payload;
  339. }
  340. return nil;
  341. }
  342. - (NSString *)encryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  343. {
  344. NSMutableData *cipher;
  345. NSData *authenticationTagData = [NSData new];
  346. NSData *encryptedData = [encrypted dataUsingEncoding:NSUTF8StringEncoding];
  347. encryptedData = [[encryptedData base64EncodedStringWithOptions:0] dataUsingEncoding:NSUTF8StringEncoding];
  348. // Key
  349. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  350. // Initialization Vector
  351. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  352. BOOL result = [self encryptData:encryptedData cipher:&cipher key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  353. if (cipher != nil && result) {
  354. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  355. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  356. NSString *payload = [cipher base64EncodedStringWithOptions:0];
  357. return payload;
  358. }
  359. return nil;
  360. }
  361. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key
  362. {
  363. NSMutableData *plain;
  364. NSRange range = [encrypted rangeOfString:IV_DELIMITER_ENCODED];
  365. if (range.location == NSNotFound) {
  366. range = [encrypted rangeOfString:IV_DELIMITER_ENCODED_OLD];
  367. if (range.location == NSNotFound) {
  368. return nil;
  369. }
  370. }
  371. // Cipher
  372. NSString *cipher = [encrypted substringToIndex:(range.location)];
  373. NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:cipher options:0];
  374. // Key
  375. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  376. // Initialization Vector
  377. NSString *initializationVector = [encrypted substringWithRange:NSMakeRange(range.location + range.length, encrypted.length - (range.location + range.length))];
  378. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  379. // Authentication Tag
  380. NSString *authenticationTag = [cipher substringWithRange:NSMakeRange(cipher.length - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  381. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  382. // Remove Authentication Tag
  383. cipherData = [cipherData subdataWithRange:NSMakeRange(0, cipherData.length - AES_GCM_TAG_LENGTH)];
  384. BOOL result = [self decryptData:cipherData plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  385. if (plain != nil && result) {
  386. return plain;
  387. }
  388. return nil;
  389. }
  390. - (NSData *)decryptPayloadFile:(NSString *)encrypted key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  391. {
  392. NSMutableData *plain;
  393. NSData *cipher = [[NSData alloc] initWithBase64EncodedString:encrypted options:0];
  394. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  395. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  396. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  397. // Remove Authentication Tag
  398. cipher = [cipher subdataWithRange:NSMakeRange(0, cipher.length - AES_GCM_TAG_LENGTH)];
  399. BOOL result = [self decryptData:cipher plain:&plain key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  400. if (plain != nil && result) {
  401. return plain;
  402. }
  403. return nil;
  404. }
  405. #
  406. #pragma mark - Encrypt / Decrypt file
  407. #
  408. - (BOOL)encryptFile:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag
  409. {
  410. NSData *authenticationTagData;
  411. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directory, fileName]];
  412. if (plainData == nil)
  413. return false;
  414. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  415. NSData *initializationVectorData = [self generateIV:AES_IVEC_LENGTH];
  416. BOOL result = [self encryptFile:[NSString stringWithFormat:@"%@/%@", directory, fileName] fileNameCipher:[NSString stringWithFormat:@"%@/%@", directory, fileNameIdentifier] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:&authenticationTagData];
  417. if (result) {
  418. *key = [keyData base64EncodedStringWithOptions:0];
  419. *initializationVector = [initializationVectorData base64EncodedStringWithOptions:0];
  420. *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  421. if (key == nil || initializationVector == nil || authenticationTag == nil) {
  422. return false;
  423. } else {
  424. return true;
  425. }
  426. }
  427. return false;
  428. }
  429. - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView ocId:(NSString *)ocId key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag
  430. {
  431. NSMutableData *plainData;
  432. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  433. if (cipherData == nil)
  434. return false;
  435. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
  436. NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0];
  437. NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0];
  438. BOOL result = [self decryptData:cipherData plain:&plainData key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData];
  439. if (plainData != nil && result) {
  440. [plainData writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] atomically:YES];
  441. return true;
  442. }
  443. return false;
  444. }
  445. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  446. // -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  447. #
  448. #pragma mark - OPENSSL ENCRYPT/DECRYPT
  449. #
  450. #
  451. #pragma mark - Encrypt/Decrypt asymmetric
  452. #
  453. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey privateKey:(NSString *)privateKey
  454. {
  455. EVP_PKEY *key = NULL;
  456. int status = 0;
  457. if (publicKey != nil) {
  458. unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  459. // Extract real publicKey
  460. BIO *bio = BIO_new_mem_buf(pKey, -1);
  461. if (!bio)
  462. return nil;
  463. X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
  464. if (!x509)
  465. return nil;
  466. key = X509_get_pubkey(x509);
  467. if (!key)
  468. return nil;
  469. }
  470. if (privateKey != nil) {
  471. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  472. BIO *bio = BIO_new_mem_buf(pKey, -1);
  473. if (!bio)
  474. return nil;
  475. key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  476. if (!key)
  477. return nil;
  478. }
  479. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  480. if (!ctx)
  481. return nil;
  482. status = EVP_PKEY_encrypt_init(ctx);
  483. if (status <= 0)
  484. return nil;
  485. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  486. if (status <= 0)
  487. return nil;
  488. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  489. if (status <= 0)
  490. return nil;
  491. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  492. if (status <= 0)
  493. return nil;
  494. unsigned long outLen = 0;
  495. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  496. status = EVP_PKEY_encrypt(ctx, NULL, &outLen, [plainData bytes], (int)[plainData length]);
  497. if (status <= 0 || outLen == 0)
  498. return nil;
  499. unsigned char *out = (unsigned char *) malloc(outLen);
  500. status = EVP_PKEY_encrypt(ctx, out, &outLen, [plainData bytes], (int)[plainData length]);
  501. if (status <= 0)
  502. return nil;
  503. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  504. if (out)
  505. free(out);
  506. return outData;
  507. }
  508. - (NSData *)decryptAsymmetricData:(NSData *)cipherData privateKey:(NSString *)privateKey
  509. {
  510. unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  511. int status = 0;
  512. BIO *bio = BIO_new_mem_buf(pKey, -1);
  513. if (!bio)
  514. return nil;
  515. EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
  516. if (!key)
  517. return nil;
  518. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(key, NULL);
  519. if (!ctx)
  520. return nil;
  521. status = EVP_PKEY_decrypt_init(ctx);
  522. if (status <= 0)
  523. return nil;
  524. status = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
  525. if (status <= 0)
  526. return nil;
  527. status = EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
  528. if (status <= 0)
  529. return nil;
  530. status = EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256());
  531. if (status <= 0)
  532. return nil;
  533. unsigned long outLen = 0;
  534. status = EVP_PKEY_decrypt(ctx, NULL, &outLen, [cipherData bytes], (int)[cipherData length]);
  535. if (status <= 0 || outLen == 0)
  536. return nil;
  537. unsigned char *out = (unsigned char *) malloc(outLen);
  538. status = EVP_PKEY_decrypt(ctx, out, &outLen, [cipherData bytes], (int)[cipherData length]);
  539. if (status <= 0)
  540. return nil;
  541. NSData *outData = [[NSData alloc] initWithBytes:out length:outLen];
  542. if (out)
  543. free(out);
  544. return outData;
  545. }
  546. #
  547. #pragma mark - AES/GCM/NoPadding
  548. #
  549. // Encryption NSData using GCM mode
  550. - (BOOL)encryptData:(NSData *)plain cipher:(NSMutableData **)cipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  551. {
  552. int status = 0;
  553. int len = 0;
  554. // set up key
  555. len = keyLen;
  556. unsigned char cKey[len];
  557. bzero(cKey, sizeof(cKey));
  558. [key getBytes:cKey length:len];
  559. // set up ivec
  560. len = AES_IVEC_LENGTH;
  561. unsigned char cIV[len];
  562. bzero(cIV, sizeof(cIV));
  563. [initializationVector getBytes:cIV length:len];
  564. // set up tag
  565. len = AES_GCM_TAG_LENGTH;
  566. unsigned char cTag[len];
  567. bzero(cTag, sizeof(cTag));
  568. // Create and initialise the context
  569. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  570. if (!ctx)
  571. return NO;
  572. // Initialise the encryption operation
  573. if (keyLen == AES_KEY_128_LENGTH)
  574. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  575. else if (keyLen == AES_KEY_256_LENGTH)
  576. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  577. if (status <= 0)
  578. return NO;
  579. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  580. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  581. if (status <= 0)
  582. return NO;
  583. // Initialise key and IV
  584. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  585. if (status <= 0)
  586. return NO;
  587. // Provide the message to be encrypted, and obtain the encrypted output
  588. *cipher = [NSMutableData dataWithLength:[plain length]];
  589. unsigned char * cCipher = [*cipher mutableBytes];
  590. int cCipherLen = 0;
  591. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  592. if (status <= 0)
  593. return NO;
  594. // Finalise the encryption
  595. len = cCipherLen;
  596. status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  597. if (status <= 0)
  598. return NO;
  599. // Get the tag
  600. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  601. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  602. // Append TAG
  603. [*cipher appendData:*authenticationTag];
  604. // Free
  605. EVP_CIPHER_CTX_free(ctx);
  606. return status; // OpenSSL uses 1 for success
  607. }
  608. // Encryption file using GCM mode
  609. - (BOOL)encryptFile:(NSString *)fileName fileNameCipher:(NSString *)fileNameCipher key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData **)authenticationTag
  610. {
  611. int status = 0;
  612. int len = 0;
  613. // set up key
  614. len = keyLen;
  615. unsigned char cKey[len];
  616. bzero(cKey, sizeof(cKey));
  617. [key getBytes:cKey length:len];
  618. // set up ivec
  619. len = AES_IVEC_LENGTH;
  620. unsigned char cIV[len];
  621. bzero(cIV, sizeof(cIV));
  622. [initializationVector getBytes:cIV length:len];
  623. // set up tag
  624. len = AES_GCM_TAG_LENGTH;
  625. unsigned char cTag[len];
  626. bzero(cTag, sizeof(cTag));
  627. // Create and initialise the context
  628. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  629. if (!ctx)
  630. return NO;
  631. // Initialise the encryption operation
  632. if (keyLen == AES_KEY_128_LENGTH)
  633. status = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  634. else if (keyLen == AES_KEY_256_LENGTH)
  635. status = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  636. if (status <= 0)
  637. return NO;
  638. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  639. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  640. if (status <= 0)
  641. return NO;
  642. // Initialise key and IV
  643. status = EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIV);
  644. if (status <= 0)
  645. return NO;
  646. NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:fileName];
  647. NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:fileNameCipher append:false];
  648. [inStream open];
  649. [outStream open];
  650. Byte buffer[1024];
  651. while ([inStream hasBytesAvailable])
  652. {
  653. int bytesRead = [inStream read:buffer maxLength:1024];
  654. NSData *inData = [NSData dataWithBytes:buffer length:bytesRead];
  655. NSMutableData *cipher;
  656. unsigned char *cCipher = [cipher mutableBytes];
  657. int cCipherLen = 0;
  658. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [inData bytes], bytesRead);
  659. [outStream write:cCipher maxLength:cCipherLen];
  660. }
  661. // Finalise the encryption
  662. //status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  663. [inStream close];
  664. [outStream close];
  665. /*
  666. // Provide the message to be encrypted, and obtain the encrypted output
  667. *cipher = [NSMutableData dataWithLength:[plain length]];
  668. unsigned char * cCipher = [*cipher mutableBytes];
  669. int cCipherLen = 0;
  670. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [plain bytes], (int)[plain length]);
  671. if (status <= 0)
  672. return NO;
  673. // Finalise the encryption
  674. len = cCipherLen;
  675. status = EVP_EncryptFinal_ex(ctx, cCipher+cCipherLen, &len);
  676. if (status <= 0)
  677. return NO;
  678. */
  679. // Get the tag
  680. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  681. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  682. // Append TAG
  683. // [*cipher appendData:*authenticationTag];
  684. // Free
  685. EVP_CIPHER_CTX_free(ctx);
  686. return status; // OpenSSL uses 1 for success
  687. }
  688. // Decryption using GCM mode
  689. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  690. {
  691. int status = 0;
  692. int len = 0;
  693. // set up key
  694. len = keyLen;
  695. unsigned char cKey[len];
  696. bzero(cKey, sizeof(cKey));
  697. [key getBytes:cKey length:len];
  698. // set up ivec
  699. len = (int)[initializationVector length];
  700. unsigned char cIV[len];
  701. bzero(cIV, sizeof(cIV));
  702. [initializationVector getBytes:cIV length:len];
  703. // set up tag
  704. len = (int)[authenticationTag length];;
  705. unsigned char cTag[len];
  706. bzero(cTag, sizeof(cTag));
  707. [authenticationTag getBytes:cTag length:len];
  708. // Create and initialise the context
  709. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  710. if (!ctx)
  711. return NO;
  712. // Initialise the decryption operation
  713. if (keyLen == AES_KEY_128_LENGTH)
  714. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  715. else if (keyLen == AES_KEY_256_LENGTH)
  716. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  717. if (status <= 0)
  718. return NO;
  719. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  720. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  721. if (status <= 0)
  722. return NO;
  723. // Initialise key and IV
  724. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  725. if (status <= 0)
  726. return NO;
  727. // Provide the message to be decrypted, and obtain the plaintext output
  728. *plain = [NSMutableData dataWithLength:([cipher length])];
  729. int cPlainLen = 0;
  730. unsigned char * cPlain = [*plain mutableBytes];
  731. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  732. if (status <= 0)
  733. return NO;
  734. // Tag is the last 16 bytes
  735. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  736. if (status <= 0)
  737. return NO;
  738. // Finalise the encryption
  739. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  740. // Free
  741. EVP_CIPHER_CTX_free(ctx);
  742. return status; // OpenSSL uses 1 for success
  743. }
  744. #
  745. #pragma mark - Utility
  746. #
  747. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  748. {
  749. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  750. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  751. *key = [keyData base64EncodedStringWithOptions:0];
  752. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  753. }
  754. - (NSString *)createSHA256:(NSString *)string
  755. {
  756. const char *cstr = [string cStringUsingEncoding:NSASCIIStringEncoding];
  757. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  758. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  759. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  760. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  761. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  762. [output appendFormat:@"%02x", digest[i]];
  763. return output;
  764. }
  765. - (NSString *)createSHA512:(NSString *)string
  766. {
  767. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  768. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  769. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  770. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  771. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  772. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  773. [output appendFormat:@"%02x", digest[i]];
  774. return output;
  775. }
  776. - (NSData *)generateIV:(int)length
  777. {
  778. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  779. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  780. return ivData;
  781. }
  782. - (NSData *)generateSalt:(int)length
  783. {
  784. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  785. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  786. return saltData;
  787. }
  788. - (NSData *)generateKey:(int)length
  789. {
  790. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  791. unsigned char *pKeyData = [keyData mutableBytes];
  792. RAND_bytes(pKeyData, length);
  793. return keyData;
  794. }
  795. - (NSData *)generateKey
  796. {
  797. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  798. unsigned char *pKeyData = [keyData mutableBytes];
  799. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  800. return keyData;
  801. }
  802. - (NSString *)getSHA1:(NSString *)input
  803. {
  804. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  805. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  806. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  807. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  808. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  809. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  810. [output appendFormat:@"%02x", digest[i]];
  811. return output;
  812. }
  813. - (NSData *)hashValueMD5OfData:(NSData *)data
  814. {
  815. MD5_CTX md5Ctx;
  816. unsigned char hashValue[MD5_DIGEST_LENGTH];
  817. if(!MD5_Init(&md5Ctx)) {
  818. return nil;
  819. }
  820. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  821. return nil;
  822. }
  823. if (!MD5_Final(hashValue, &md5Ctx)) {
  824. return nil;
  825. }
  826. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  827. }
  828. - (NSString *)hexadecimalString:(NSData *)input
  829. {
  830. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  831. if (!dataBuffer) {
  832. return [NSString string];
  833. }
  834. NSUInteger dataLength = [input length];
  835. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  836. for (int i = 0; i < dataLength; ++i) {
  837. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  838. }
  839. return [NSString stringWithString:hexString];
  840. }
  841. - (NSString *)derToPemPrivateKey:(NSString *)input
  842. {
  843. NSInteger substringLength = 65;
  844. NSMutableString *result = [NSMutableString stringWithString: input];
  845. for(long i=substringLength;i<=input.length;i++) {
  846. [result insertString: @"\n" atIndex: i];
  847. i+=substringLength;
  848. }
  849. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  850. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  851. return result;
  852. }
  853. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  854. {
  855. char *buf[256];
  856. FILE *pFile;
  857. NSString *pkey_string;
  858. pFile = fmemopen(buf, sizeof(buf), "w");
  859. PEM_write_PUBKEY(pFile,pubkey);
  860. fputc('\0', pFile);
  861. fclose(pFile);
  862. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  863. return pkey_string;
  864. }
  865. @end