· 7 years ago · May 31, 2018, 04:08 PM
1Encryption:
2
3
4
5NSString * _secret = @"This the sample text has to be encrypted"; // this is the text that you want to encrypt.
6
7
8
9NSString * _key = @"shared secret"; //secret key for encryption. To make encryption stronger, we will not use this key directly. We'll first hash the key next step and then use it.
10
11
12
13key = [[StringEncryption alloc] sha256:key length:32]; //this is very important, 32 bytes = 256 bit
14
15
16
17NSString * iv = [[[[StringEncryption alloc] generateRandomIV:11] base64EncodingWithLineLength:0] substringToIndex:16]; //Here we are generating random initialization vector (iv). Length of this vector = 16 bytes = 128 bits
18
19
20
21NSData * encryptedData = [[StringEncryption alloc] encrypt:[secret dataUsingEncoding:NSUTF8StringEncoding] key:key iv:iv];
22
23
24
25NSLog(@"encrypted data:: %@", [encryptedData base64EncodingWithLineLength:0]); //print the encrypted text
26
27Encryption = [plainText + secretKey + randomIV] = Cyphertext
28
29
30
31Decryption:
32
33
34
35
36
37encryptedData = [[StringEncryption alloc] decrypt:encryptedData key:key iv:iv];
38
39NSString * decryptedText = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding];
40
41NSLog(@"decrypted data:: %@", decryptedText); //print the decrypted text