NCEndToEndEncryption.m 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  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[streamBuffer];
  651. NSInteger totalNumberOfBytesWritten = 0;
  652. int cCipherLen = 0;
  653. NSMutableData *cipher;
  654. unsigned char *cCipher;
  655. while ([inStream hasBytesAvailable])
  656. {
  657. NSInteger bytesRead = [inStream read:buffer maxLength:streamBuffer];
  658. NSData *inData = [NSData dataWithBytes:buffer length:bytesRead];
  659. if (bytesRead > 0) {
  660. cipher = [NSMutableData dataWithLength:bytesRead];
  661. cCipher = [cipher mutableBytes];
  662. status = EVP_EncryptUpdate(ctx, cCipher, &cCipherLen, [inData bytes], (int)bytesRead);
  663. if ([outStream hasSpaceAvailable]) {
  664. totalNumberOfBytesWritten = [outStream write:cCipher maxLength:cCipherLen];
  665. if (totalNumberOfBytesWritten != cCipherLen) {
  666. [inStream close];
  667. [outStream close];
  668. // Free
  669. EVP_CIPHER_CTX_free(ctx);
  670. return -1;
  671. }
  672. }
  673. }
  674. }
  675. status = EVP_EncryptFinal_ex(ctx, cCipher, &cCipherLen);
  676. if (status <= 0)
  677. return NO;
  678. // Get the tag
  679. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, (int)sizeof(cTag), cTag);
  680. *authenticationTag = [NSData dataWithBytes:cTag length:sizeof(cTag)];
  681. // Append TAG
  682. if ([outStream hasSpaceAvailable]) {
  683. totalNumberOfBytesWritten = [outStream write:cTag maxLength:sizeof(cTag)];
  684. if (totalNumberOfBytesWritten != sizeof(cTag)) {
  685. status = -1;
  686. }
  687. } else {
  688. status = -1;
  689. }
  690. [inStream close];
  691. [outStream close];
  692. // Free
  693. EVP_CIPHER_CTX_free(ctx);
  694. return status; // OpenSSL uses 1 for success
  695. }
  696. // Decryption using GCM mode
  697. - (BOOL)decryptData:(NSData *)cipher plain:(NSMutableData **)plain key:(NSData *)key keyLen:(int)keyLen initializationVector:(NSData *)initializationVector authenticationTag:(NSData *)authenticationTag
  698. {
  699. int status = 0;
  700. int len = 0;
  701. // set up key
  702. len = keyLen;
  703. unsigned char cKey[len];
  704. bzero(cKey, sizeof(cKey));
  705. [key getBytes:cKey length:len];
  706. // set up ivec
  707. len = (int)[initializationVector length];
  708. unsigned char cIV[len];
  709. bzero(cIV, sizeof(cIV));
  710. [initializationVector getBytes:cIV length:len];
  711. // set up tag
  712. len = (int)[authenticationTag length];;
  713. unsigned char cTag[len];
  714. bzero(cTag, sizeof(cTag));
  715. [authenticationTag getBytes:cTag length:len];
  716. // Create and initialise the context
  717. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  718. if (!ctx)
  719. return NO;
  720. // Initialise the decryption operation
  721. if (keyLen == AES_KEY_128_LENGTH)
  722. status = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  723. else if (keyLen == AES_KEY_256_LENGTH)
  724. status = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
  725. if (status <= 0)
  726. return NO;
  727. // Set IV length. Not necessary if this is 12 bytes (96 bits)
  728. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)sizeof(cIV), NULL);
  729. if (status <= 0)
  730. return NO;
  731. // Initialise key and IV
  732. status = EVP_DecryptInit_ex(ctx, NULL, NULL, cKey, cIV);
  733. if (status <= 0)
  734. return NO;
  735. // Provide the message to be decrypted, and obtain the plaintext output
  736. *plain = [NSMutableData dataWithLength:([cipher length])];
  737. int cPlainLen = 0;
  738. unsigned char * cPlain = [*plain mutableBytes];
  739. status = EVP_DecryptUpdate(ctx, cPlain, &cPlainLen, [cipher bytes], (int)([cipher length]));
  740. if (status <= 0)
  741. return NO;
  742. // Tag is the last 16 bytes
  743. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)sizeof(cTag), cTag);
  744. if (status <= 0)
  745. return NO;
  746. // Finalise the encryption
  747. EVP_DecryptFinal_ex(ctx,NULL, &cPlainLen);
  748. // Free
  749. EVP_CIPHER_CTX_free(ctx);
  750. return status; // OpenSSL uses 1 for success
  751. }
  752. #
  753. #pragma mark - Utility
  754. #
  755. - (void)Encodedkey:(NSString **)key initializationVector:(NSString **)initializationVector
  756. {
  757. NSData *keyData = [self generateKey:AES_KEY_128_LENGTH];
  758. NSData *ivData = [self generateIV:AES_IVEC_LENGTH];
  759. *key = [keyData base64EncodedStringWithOptions:0];
  760. *initializationVector = [ivData base64EncodedStringWithOptions:0];
  761. }
  762. - (NSString *)createSHA256:(NSString *)string
  763. {
  764. const char *cstr = [string cStringUsingEncoding:NSASCIIStringEncoding];
  765. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  766. uint8_t digest[CC_SHA256_DIGEST_LENGTH];
  767. CC_SHA256(data.bytes, (unsigned int)data.length, digest);
  768. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
  769. for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
  770. [output appendFormat:@"%02x", digest[i]];
  771. return output;
  772. }
  773. - (NSString *)createSHA512:(NSString *)string
  774. {
  775. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  776. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  777. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  778. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  779. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  780. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  781. [output appendFormat:@"%02x", digest[i]];
  782. return output;
  783. }
  784. - (NSData *)generateIV:(int)length
  785. {
  786. NSMutableData *ivData = [NSMutableData dataWithLength:length];
  787. (void)SecRandomCopyBytes(kSecRandomDefault, length, ivData.mutableBytes);
  788. return ivData;
  789. }
  790. - (NSData *)generateSalt:(int)length
  791. {
  792. NSMutableData *saltData = [NSMutableData dataWithLength:length];
  793. (void)SecRandomCopyBytes(kSecRandomDefault, length, saltData.mutableBytes);
  794. return saltData;
  795. }
  796. - (NSData *)generateKey:(int)length
  797. {
  798. NSMutableData *keyData = [NSMutableData dataWithLength:length];
  799. unsigned char *pKeyData = [keyData mutableBytes];
  800. RAND_bytes(pKeyData, length);
  801. return keyData;
  802. }
  803. - (NSData *)generateKey
  804. {
  805. NSMutableData *keyData = [NSMutableData dataWithLength:AES_KEY_128_LENGTH];
  806. unsigned char *pKeyData = [keyData mutableBytes];
  807. RAND_bytes(pKeyData, AES_KEY_128_LENGTH);
  808. return keyData;
  809. }
  810. - (NSString *)getSHA1:(NSString *)input
  811. {
  812. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  813. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  814. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  815. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  816. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  817. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  818. [output appendFormat:@"%02x", digest[i]];
  819. return output;
  820. }
  821. - (NSData *)hashValueMD5OfData:(NSData *)data
  822. {
  823. MD5_CTX md5Ctx;
  824. unsigned char hashValue[MD5_DIGEST_LENGTH];
  825. if(!MD5_Init(&md5Ctx)) {
  826. return nil;
  827. }
  828. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  829. return nil;
  830. }
  831. if (!MD5_Final(hashValue, &md5Ctx)) {
  832. return nil;
  833. }
  834. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  835. }
  836. - (NSString *)hexadecimalString:(NSData *)input
  837. {
  838. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  839. if (!dataBuffer) {
  840. return [NSString string];
  841. }
  842. NSUInteger dataLength = [input length];
  843. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  844. for (int i = 0; i < dataLength; ++i) {
  845. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  846. }
  847. return [NSString stringWithString:hexString];
  848. }
  849. - (NSString *)derToPemPrivateKey:(NSString *)input
  850. {
  851. NSInteger substringLength = 65;
  852. NSMutableString *result = [NSMutableString stringWithString: input];
  853. for(long i=substringLength;i<=input.length;i++) {
  854. [result insertString: @"\n" atIndex: i];
  855. i+=substringLength;
  856. }
  857. [result insertString: @"-----BEGIN PRIVATE KEY-----\n" atIndex: 0];
  858. [result appendString:@"\n-----END PRIVATE KEY-----\n"];
  859. return result;
  860. }
  861. - (NSString *)pubKeyToString:(EVP_PKEY *)pubkey
  862. {
  863. char *buf[256];
  864. FILE *pFile;
  865. NSString *pkey_string;
  866. pFile = fmemopen(buf, sizeof(buf), "w");
  867. PEM_write_PUBKEY(pFile,pubkey);
  868. fputc('\0', pFile);
  869. fclose(pFile);
  870. pkey_string = [NSString stringWithUTF8String:(char *)buf];
  871. return pkey_string;
  872. }
  873. @end