NCEndToEndEncryption.m 37 KB

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