NCEndToEndEncryption.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. //
  2. // NCEndToEndEncryption.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/09/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  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/x509.h>
  29. #import <openssl/bio.h>
  30. #import <openssl/err.h>
  31. #import <openssl/pem.h>
  32. #import <openssl/rsa.h>
  33. #import <openssl/pkcs12.h>
  34. #import <openssl/ssl.h>
  35. #import <openssl/err.h>
  36. #import <openssl/bn.h>
  37. #import <openssl/md5.h>
  38. #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);
  39. #define AES_KEY_LENGTH 16
  40. #define AES_IVEC_LENGTH 16
  41. #define AES_GCM_TAG_LENGTH 16
  42. #define IV_DELIMITER_ENCODED @"fA==" // "|" base64 encoded
  43. #define PBKDF2_INTERACTION_COUNT 1024
  44. #define PBKDF2_KEY_LENGTH 256
  45. #define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  46. #define TEST_KEY @"ciao"
  47. #define fileNameCertificate @"cert.pem"
  48. #define fileNameCSR @"csr.pem"
  49. #define fileNamePrivateKey @"privateKey.pem"
  50. #define fileNamePubliceKey @"publicKey.pem"
  51. @interface NCEndToEndEncryption ()
  52. {
  53. NSData *_privateKeyData;
  54. NSData *_publicKeyData;
  55. NSData *_csrData;
  56. }
  57. @end
  58. @implementation NCEndToEndEncryption
  59. //Singleton
  60. + (instancetype)sharedManager {
  61. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  62. static dispatch_once_t onceToken;
  63. dispatch_once(&onceToken, ^{
  64. NCEndToEndEncryption = [self new];
  65. });
  66. return NCEndToEndEncryption;
  67. }
  68. #
  69. #pragma mark - Generate Certificate X509 - CSR - Private Key
  70. #
  71. - (BOOL)generateCertificateX509WithUserID:(NSString *)userID directoryUser:(NSString *)directoryUser
  72. {
  73. OPENSSL_init_ssl(0, NULL);
  74. OPENSSL_init_crypto(0, NULL);
  75. X509 *x509;
  76. x509 = X509_new();
  77. EVP_PKEY *pkey;
  78. NSError *keyError;
  79. pkey = [self generateRSAKey:&keyError];
  80. if (keyError) {
  81. return NO;
  82. }
  83. X509_set_pubkey(x509, pkey);
  84. EVP_PKEY_free(pkey);
  85. // Set Serial Number
  86. ASN1_INTEGER_set(X509_get_serialNumber(x509), 123);
  87. // Set Valididity Date Range
  88. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  89. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  90. X509_gmtime_adj((ASN1_TIME *)X509_get0_notBefore(x509), notBefore);
  91. X509_gmtime_adj((ASN1_TIME *)X509_get0_notAfter(x509), notAfter);
  92. X509_NAME *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(@"\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. NSLog(@"\n%@", [[NSString alloc] initWithData:_publicKeyData encoding:NSUTF8StringEncoding]);
  150. // PrivateKey
  151. BIO *privateKeyBIO = BIO_new(BIO_s_mem());
  152. PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
  153. len = BIO_pending(privateKeyBIO);
  154. keyBytes = malloc(len);
  155. BIO_read(privateKeyBIO, keyBytes, len);
  156. _privateKeyData = [NSData dataWithBytes:keyBytes length:len];
  157. NSLog(@"\n%@", [[NSString alloc] initWithData:_privateKeyData encoding:NSUTF8StringEncoding]);
  158. if(keyBytes)
  159. free(keyBytes);
  160. #ifdef DEBUG
  161. // Save to disk [DEBUG MODE]
  162. [self saveToDiskPEMWithCert:x509 key:pkey directoryUser:directoryUser];
  163. #endif
  164. return YES;
  165. }
  166. - (EVP_PKEY *)generateRSAKey:(NSError **)error
  167. {
  168. EVP_PKEY *pkey = EVP_PKEY_new();
  169. if (!pkey) {
  170. return NULL;
  171. }
  172. BIGNUM *bigNumber = BN_new();
  173. int exponent = RSA_F4;
  174. RSA *rsa = RSA_new();
  175. if (BN_set_word(bigNumber, exponent) < 0) {
  176. goto cleanup;
  177. }
  178. if (RSA_generate_key_ex(rsa, 2048, bigNumber, NULL) < 0) {
  179. goto cleanup;
  180. }
  181. if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
  182. goto cleanup;
  183. }
  184. cleanup:
  185. RSA_free(rsa);
  186. BN_free(bigNumber);
  187. return pkey;
  188. }
  189. - (BOOL)saveToDiskPEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser
  190. {
  191. FILE *f;
  192. // Certificate
  193. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCertificate];
  194. f = fopen([certificatePath fileSystemRepresentation], "wb");
  195. if (PEM_write_X509(f, x509) < 0) {
  196. // Error writing to disk.
  197. fclose(f);
  198. return NO;
  199. }
  200. NSLog(@"Saved cert to %@", certificatePath);
  201. fclose(f);
  202. // PublicKey
  203. NSString *publicKeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePubliceKey];
  204. f = fopen([publicKeyPath fileSystemRepresentation], "wb");
  205. if (PEM_write_PUBKEY(f, pkey) < 0) {
  206. // Error
  207. fclose(f);
  208. return NO;
  209. }
  210. NSLog(@"Saved publicKey to %@", publicKeyPath);
  211. fclose(f);
  212. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  213. // file using the password and cipher you provide.
  214. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  215. // PrivateKey
  216. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey];
  217. f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  218. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  219. // Error
  220. fclose(f);
  221. return NO;
  222. }
  223. NSLog(@"Saved privatekey to %@", privatekeyPath);
  224. fclose(f);
  225. // CSR Request sha256
  226. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR];
  227. f = fopen([csrPath fileSystemRepresentation], "wb");
  228. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  229. if (PEM_write_X509_REQ(f, certreq) < 0) {
  230. // Error
  231. fclose(f);
  232. return NO;
  233. }
  234. NSLog(@"Saved csr to %@", csrPath);
  235. fclose(f);
  236. return YES;
  237. }
  238. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  239. {
  240. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  241. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  242. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directoryUser];
  243. FILE *f = fopen([path fileSystemRepresentation], "wb");
  244. if (i2d_PKCS12_fp(f, p12) != 1) {
  245. fclose(f);
  246. return NO;
  247. }
  248. NSLog(@"Saved p12 to %@", path);
  249. fclose(f);
  250. return YES;
  251. }
  252. #
  253. #pragma mark - Register client for Server with exists Key pair
  254. #
  255. - (NSString *)createCSR:(NSString *)userID directoryUser:(NSString *)directoryUser
  256. {
  257. // Create Certificate, if do not exists
  258. if (!_csrData) {
  259. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  260. return nil;
  261. }
  262. NSString *csr = [[NSString alloc] initWithData:_csrData encoding:NSUTF8StringEncoding];
  263. return csr;
  264. }
  265. - (NSString *)encryptPrivateKey:(NSString *)userID directoryUser: (NSString *)directoryUser passphrase:(NSString *)passphrase
  266. {
  267. NSMutableData *privateKeyCipherData = [NSMutableData new];
  268. if (!_privateKeyData) {
  269. if (![self generateCertificateX509WithUserID:userID directoryUser:directoryUser])
  270. return nil;
  271. }
  272. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  273. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  274. // Remove all whitespaces from passphrase
  275. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  276. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  277. NSData *initVectorData = [self generateIV:AES_IVEC_LENGTH];
  278. BOOL result = [self encryptData:_privateKeyData cipherData:&privateKeyCipherData keyData:keyData initVectorData:initVectorData tagData:nil];
  279. if (result && privateKeyCipherData) {
  280. NSString *privateKeyCipherBase64;
  281. NSString *initVectorBase64;
  282. NSString *privateKeyCipherWithInitVectorBase64;
  283. privateKeyCipherBase64 = [privateKeyCipherData base64EncodedStringWithOptions:0];
  284. initVectorBase64 = [initVectorData base64EncodedStringWithOptions:0];
  285. privateKeyCipherWithInitVectorBase64 = [NSString stringWithFormat:@"%@%@%@", privateKeyCipherBase64, IV_DELIMITER_ENCODED, initVectorBase64];
  286. return privateKeyCipherWithInitVectorBase64;
  287. } else {
  288. return nil;
  289. }
  290. }
  291. #
  292. #pragma mark - No key pair exists on the server
  293. #
  294. - (NSString *)decryptPrivateKey:(NSString *)privateKeyCipher passphrase:(NSString *)passphrase publicKey:(NSString *)publicKey
  295. {
  296. NSMutableData *privateKeyData = [NSMutableData new];
  297. // Key (data)
  298. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  299. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  300. // Remove all whitespaces from passphrase
  301. passphrase = [passphrase stringByReplacingOccurrencesOfString:@" " withString:@""];
  302. CCKeyDerivationPBKDF(kCCPBKDF2, passphrase.UTF8String, passphrase.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  303. // Split
  304. NSRange range = [privateKeyCipher rangeOfString:IV_DELIMITER_ENCODED];
  305. NSInteger idx = range.location + range.length;
  306. // PrivateKey
  307. NSString *privateKeyCipherBase64 = [privateKeyCipher substringToIndex:range.location];
  308. NSData *privateKeyCipherData = [[NSData alloc] initWithBase64EncodedString:privateKeyCipherBase64 options:0];
  309. // Init Vector
  310. NSString *initVectorBase64 = [privateKeyCipher substringFromIndex:idx];
  311. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:initVectorBase64 options:0];
  312. BOOL result = [self decryptData:privateKeyCipherData plainData:&privateKeyData keyData:keyData initVectorData:initVectorData tag:nil];
  313. if (result && privateKeyData) {
  314. NSString *privateKey = [[NSString alloc] initWithData:privateKeyData encoding:NSUTF8StringEncoding];
  315. NSData *encryptData = [self encryptAsymmetricString:TEST_KEY publicKey:publicKey];
  316. NSString *decryptString = [self decryptAsymmetricData:encryptData privateKey:privateKey];
  317. //unsigned char cPrivateKey[privateKeyData.length];
  318. //bzero(cPrivateKey, sizeof(cPrivateKey));
  319. //[privateKeyData getBytes:cPrivateKey length:privateKeyData.length];
  320. //BIO *priv_bio = BIO_new_mem_buf(cPrivateKey, privateKeyData.length);
  321. //RSA *rsaPrivKey = PEM_read_bio_RSAPrivateKey(priv_bio, NULL, NULL, NULL);
  322. // Temp test REMOVE !!
  323. if ([privateKey containsString:@"-----BEGIN PRIVATE KEY-----"] && [privateKey containsString:@"-----END PRIVATE KEY-----"])
  324. return privateKey;
  325. else
  326. return nil;
  327. } else {
  328. return nil;
  329. }
  330. }
  331. #
  332. #pragma mark - Asymmetric Encrypt/Decrypt String
  333. #
  334. - (NSData *)encryptAsymmetricString:(NSString *)plain publicKey:(NSString *)publicKey
  335. {
  336. //unsigned char *pKey = (unsigned char *)[publicKey UTF8String];
  337. char *pKey = "-----BEGIN PUBLIC KEY-----\n"
  338. "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwMu7BZF451FjUXYNr323\n"
  339. "aeeaCW2a7s6eHHs8Gz5qgQ/zDegub6is3jwdTZJyGcRcN1DxKQsLcOa3F18KSiCk\n"
  340. "yzIWjNV4YH7GdV7Ke2qLjcQUs7wktGUKyPYJmDWGYv/QN0Sbbol9IbeLjSBHUt16\n"
  341. "xBex5IIpQqDtBy0RZvAMdUUB1rezKka0bC+b5CmE4ysIRFyFiweSlGsSdkaS9q1l\n"
  342. "d+c/V4LMxljNbhdpfpiniWAD3lm9+mDJzToOiqz+nH9SHs4ClEThBAScI00xJH36\n"
  343. "3mDvY0x6HVDyCsueC9jtfZKnI2uwM2tbUU4iDkCaIYm6VE6h1qs5AkrxH1o6K2lC\n"
  344. "kQIDAQAB\n"
  345. "-----END PUBLIC KEY-----\n";
  346. BIO *bio = BIO_new_mem_buf(pKey, -1);
  347. RSA *rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, 0, NULL);
  348. BIO_free(bio);
  349. NSData *plainData = [plain dataUsingEncoding:NSUTF8StringEncoding];
  350. NSMutableData *cipherData = [NSMutableData dataWithLength:[plainData length]];
  351. unsigned char *pCipherData = [cipherData mutableBytes];
  352. int encrypted_length = RSA_public_encrypt((int)[plainData length], [plainData bytes], pCipherData, rsa, RSA_PKCS1_PADDING);
  353. if(encrypted_length == -1) {
  354. char buffer[500];
  355. ERR_error_string(ERR_get_error(), buffer);
  356. NSLog(@"%@",[NSString stringWithUTF8String:buffer]);
  357. return nil;
  358. }
  359. return [NSData dataWithBytes:pCipherData length:[plainData length]];
  360. }
  361. - (NSString *)decryptAsymmetricData:(NSData *)chiperData privateKey:(NSString *)privateKey
  362. {
  363. //unsigned char *pKey = (unsigned char *)[privateKey UTF8String];
  364. char *pKey = "-----BEGIN RSA PRIVATE KEY-----\n"
  365. "MIIEowIBAAKCAQEAwMu7BZF451FjUXYNr323aeeaCW2a7s6eHHs8Gz5qgQ/zDegu\n"
  366. "b6is3jwdTZJyGcRcN1DxKQsLcOa3F18KSiCkyzIWjNV4YH7GdV7Ke2qLjcQUs7wk\n"
  367. "tGUKyPYJmDWGYv/QN0Sbbol9IbeLjSBHUt16xBex5IIpQqDtBy0RZvAMdUUB1rez\n"
  368. "Kka0bC+b5CmE4ysIRFyFiweSlGsSdkaS9q1ld+c/V4LMxljNbhdpfpiniWAD3lm9\n"
  369. "+mDJzToOiqz+nH9SHs4ClEThBAScI00xJH363mDvY0x6HVDyCsueC9jtfZKnI2uw\n"
  370. "M2tbUU4iDkCaIYm6VE6h1qs5AkrxH1o6K2lCkQIDAQABAoIBAChqzWNGcu0zb7nF\n"
  371. "IOtYVJocFnvBgYhswlLANwKTHCrAWDjjItD/sHXKbm4ztD3Yn2htTJFJInXhuCJr\n"
  372. "JzIRE9sRPg76NYktKpeybope9LCcmaZwW9WBlTg59Br3pZude14KwPb0Vco6u0Oz\n"
  373. "r6AclD8FpKJ98v5n1Cj79rj4u/PdTXZP+Fmz8y0KAgM1s39rtiaAHKGCcyfb1awf\n"
  374. "pCsYL0IvmU1Z00sPe5dzSqLY4HcIyT2kIMqnC0c0HTPtU6A5GI7dPMQsJy+ZEsWo\n"
  375. "kR4YdymmN3C11gdd8kTpExdm1Ick5GfgUfc5hYYTBUO4n8bWJFJLxY6MtjdRfWHc\n"
  376. "SBg4hw0CgYEA3vYaOzk8gUgUVkhnAsyoRNPkMKOH+EbOWuAssK3lQ2U8gvryJngz\n"
  377. "KaQEGnluHvwK69BkJQQ5+PTMKhvhDZ4Ur9t6K7iZ3io3XLafH+jZk8alxYtZen00\n"
  378. "Z38z2VQ8gjYHjfXGKNs1YGcfb+uJ5a8YMGbNjYTdGkIeWL0DLdrYH78CgYEA3V1R\n"
  379. "fTPCY93kxOfYEnRvsO7HY6/4aESAMthROABd9IbYzmsA2Jkcs9Cns3MvWoLpbUY5\n"
  380. "c36WDn9pZOg8vF0dday9Gr/ZrisEv7MgFl0FloyNsnGviHHFfoLPbOjEPUGXcRy2\n"
  381. "1350nFJ2L0e9XcHgvPSjkmwcLbGgkrtWgjJoMa8CgYB0URPSPcPw9jeV4+PJtBc9\n"
  382. "AQYU0duHjPjus/Dco3vtswzkkCJwK1kVqjlxzlPC2l6gM3FrVk8gMCWq+ixovEWy\n"
  383. "kN+lm4K6Qm/rcGKHdSS9UW7+JfqiSltiexwDj0yZ6bH7P3MHsYShLGtcKhcguj32\n"
  384. "Ukt+PwhSQJgwVzsnWvpRZQKBgQCDFrIdLLufHFZPbOR9+UnzQ1P8asb2KCqq8YMX\n"
  385. "YNBC8GAPzToRCor+yT+mez29oezN81ouVPZT24v0X7sn6RR7DTJnVtl31K3ZQCBu\n"
  386. "XePjRZTb6YsDiCxmQNzJKAaeJ+ug5lo4vwAbWpH2actwbFHEVDNRkIgXXysx+ZK/\n"
  387. "Q06ErQKBgHzXwrSRWppsQGdxSrU1Ynwg0bIirfi2N8zyHgFutQzdkDXY5N0gRG7a\n"
  388. "Xz8GFJecE8Goz8Mw2NigtBC4EystXievCwR3EztDyU5PgvEQV7d+0GLKtCG6QFqC\n"
  389. "gZKlwzSf9rLhfXYCrWgqg7ZXsiaADQePw+fU2dudERxmg3gokBFL\n"
  390. "-----END RSA PRIVATE KEY-----\n";
  391. BIO *bio = BIO_new_mem_buf(pKey, -1);
  392. RSA *rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, 0, NULL);
  393. BIO_free(bio);
  394. NSMutableData *plainData = [NSMutableData dataWithLength:[chiperData length]];
  395. unsigned char *pPlainData = [plainData mutableBytes];
  396. int decrypted_length = RSA_private_decrypt((int)[chiperData length], [chiperData bytes], pPlainData, rsa, RSA_PKCS1_PADDING);
  397. if(decrypted_length == -1) {
  398. char buffer[500];
  399. ERR_error_string(ERR_get_error(), buffer);
  400. NSLog(@"%@",[NSString stringWithUTF8String:buffer]);
  401. return nil;
  402. }
  403. NSString *plain = [[NSString alloc] initWithBytes:pPlainData length:sizeof(pPlainData) encoding:NSUTF8StringEncoding];
  404. return plain;
  405. }
  406. #
  407. #pragma mark - Encrypt/Decrypt Files AES/GCM/NoPadding as cipher (128 bit key size)
  408. #
  409. - (void)encryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  410. {
  411. NSMutableData *cipherData;
  412. NSData *tagData;
  413. NSString* authenticationTag;
  414. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  415. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  416. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  417. BOOL result = [self encryptData:plainData cipherData:&cipherData keyData:keyData initVectorData:initVectorData tagData:&tagData];
  418. if (cipherData != nil && result) {
  419. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"encrypted.dms"] atomically:YES];
  420. authenticationTag = [tagData base64EncodedStringWithOptions:0];
  421. }
  422. }
  423. - (void)decryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  424. {
  425. NSMutableData *plainData;
  426. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  427. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  428. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  429. NSString *tag = @"PboI9tqHHX3QeAA22PIu4w==";
  430. BOOL result = [self decryptData:cipherData plainData:&plainData keyData:keyData initVectorData:initVectorData tag:tag];
  431. if (plainData != nil && result) {
  432. [plainData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"decrypted"] atomically:YES];
  433. }
  434. }
  435. // encrypt data AES 256 GCM NOPADING
  436. - (BOOL)encryptData:(NSData *)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tagData:(NSData **)tagData
  437. {
  438. int status = 0;
  439. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  440. // set up key
  441. unsigned char cKey[AES_KEY_LENGTH];
  442. bzero(cKey, sizeof(cKey));
  443. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  444. // set up ivec
  445. unsigned char cIv[AES_IVEC_LENGTH];
  446. bzero(cIv, AES_IVEC_LENGTH);
  447. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  448. // set up to Encrypt AES 128 GCM
  449. int numberOfBytes = 0;
  450. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  451. EVP_EncryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  452. // set the key and ivec
  453. EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  454. EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  455. unsigned char * ctBytes = [*cipherData mutableBytes];
  456. EVP_EncryptUpdate (ctx, ctBytes, &numberOfBytes, [plainData bytes], (int)[plainData length]);
  457. status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  458. if (status && tagData) {
  459. unsigned char cTag[AES_GCM_TAG_LENGTH];
  460. bzero(cTag, AES_GCM_TAG_LENGTH);
  461. status = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_LENGTH, cTag);
  462. *tagData = [NSData dataWithBytes:cTag length:AES_GCM_TAG_LENGTH];
  463. }
  464. EVP_CIPHER_CTX_free(ctx);
  465. return (status != 0); // OpenSSL uses 1 for success
  466. }
  467. // decrypt data AES 256 GCM NOPADING
  468. - (BOOL)decryptData:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tag:(NSString *)tag
  469. {
  470. int status = 0;
  471. int numberOfBytes = 0;
  472. *plainData = [NSMutableData dataWithLength:[cipherData length]];
  473. // set up key
  474. unsigned char cKey[AES_KEY_LENGTH];
  475. bzero(cKey, sizeof(cKey));
  476. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  477. // set up ivec
  478. unsigned char cIv[AES_IVEC_LENGTH];
  479. bzero(cIv, AES_IVEC_LENGTH);
  480. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  481. // set up tag
  482. //unsigned char cTag[AES_GCM_TAG_LENGTH];
  483. //bzero(cTag, AES_GCM_TAG_LENGTH);
  484. //[tagData getBytes:cTag length:AES_GCM_TAG_LENGTH];
  485. /* verify tag if exists*/
  486. if (tag) {
  487. NSData *authenticationTagData = [cipherData subdataWithRange:NSMakeRange([cipherData length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  488. NSString *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  489. if (![authenticationTag isEqualToString:tag])
  490. return NO;
  491. }
  492. /* Create and initialise the context */
  493. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  494. /* Initialise the decryption operation. */
  495. status = EVP_DecryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  496. if (! status)
  497. return NO;
  498. /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
  499. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  500. if (! status)
  501. return NO;
  502. /* Initialise key and IV */
  503. status = EVP_DecryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  504. if (! status)
  505. return NO;
  506. /* Provide the message to be decrypted, and obtain the plaintext output. */
  507. unsigned char * ctBytes = [*plainData mutableBytes];
  508. status = EVP_DecryptUpdate (ctx, ctBytes, &numberOfBytes, [cipherData bytes], (int)[cipherData length]);
  509. if (! status)
  510. return NO;
  511. /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
  512. //status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_LENGTH, cTag);
  513. //if (!status)
  514. // return NO;
  515. /* Finalise the decryption. A positive return value indicates success, anything else is a failure - the plaintext is n trustworthy. */
  516. //status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  517. //if (!status)
  518. // return NO;
  519. // Without test Final
  520. EVP_DecryptFinal_ex (ctx, NULL, &numberOfBytes);
  521. EVP_CIPHER_CTX_free(ctx);
  522. return status; // OpenSSL uses 1 for success
  523. }
  524. #
  525. #pragma mark - Utility
  526. #
  527. - (NSString *)createSHA512:(NSString *)string
  528. {
  529. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  530. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  531. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  532. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  533. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  534. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  535. [output appendFormat:@"%02x", digest[i]];
  536. return output;
  537. }
  538. - (NSData *)generateIV:(int)ivLength
  539. {
  540. NSMutableData *ivData = [NSMutableData dataWithLength:ivLength];
  541. (void)SecRandomCopyBytes(kSecRandomDefault, ivLength, ivData.mutableBytes);
  542. return ivData;
  543. }
  544. - (NSString *)getMD5:(NSString *)input
  545. {
  546. // Create pointer to the string as UTF8
  547. const char *ptr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  548. // Create byte array of unsigned chars
  549. unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  550. // Create 16 byte MD5 hash value, store in buffer
  551. CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
  552. // Convert MD5 value in the buffer to NSString of hex values
  553. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  554. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  555. [output appendFormat:@"%02x",md5Buffer[i]];
  556. return output;
  557. }
  558. - (NSString *)getSHA1:(NSString *)input
  559. {
  560. const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
  561. NSData *data = [NSData dataWithBytes:cstr length:input.length];
  562. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  563. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  564. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  565. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  566. [output appendFormat:@"%02x", digest[i]];
  567. return output;
  568. }
  569. - (NSData *)hashValueMD5OfData:(NSData *)data
  570. {
  571. MD5_CTX md5Ctx;
  572. unsigned char hashValue[MD5_DIGEST_LENGTH];
  573. if(!MD5_Init(&md5Ctx)) {
  574. return nil;
  575. }
  576. if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
  577. return nil;
  578. }
  579. if (!MD5_Final(hashValue, &md5Ctx)) {
  580. return nil;
  581. }
  582. return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
  583. }
  584. - (NSString *)hexadecimalString:(NSData *)input
  585. {
  586. const unsigned char *dataBuffer = (const unsigned char *) [input bytes];
  587. if (!dataBuffer) {
  588. return [NSString string];
  589. }
  590. NSUInteger dataLength = [input length];
  591. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  592. for (int i = 0; i < dataLength; ++i) {
  593. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) dataBuffer[i]]];
  594. }
  595. return [NSString stringWithString:hexString];
  596. }
  597. - (NSString *)stringRemoveBeginEnd:(NSString *)input
  598. {
  599. input = [input stringByReplacingOccurrencesOfString:@"-----BEGIN CERTIFICATE-----\n" withString:@""];
  600. input = [input stringByReplacingOccurrencesOfString:@"\n-----END CERTIFICATE-----" withString:@""];
  601. input = [input stringByReplacingOccurrencesOfString:@"-----BEGIN PRIVATE KEY-----\n" withString:@""];
  602. input = [input stringByReplacingOccurrencesOfString:@"\n-----END PRIVATE KEY-----" withString:@""];
  603. return input;
  604. }
  605. @end