1
votes

My task is to encrypt a file(.png, .txt, any..)

In order to achieve it what I doing is

Encryption:

  1. Read a file and store it into NSData.
  2. Convert NSData to NSString.
  3. Encrypt the NSString with help of AESCrypt
  4. Store the NSString in a file

Decryption

  1. Read the encrypted string
  2. Decrypt it with the help of AESCrypt
  3. Convert it back to NSData
  4. Save it back to some location

Below is the code that I am doing in order convert a file to NSString:

NSString* sourceFile = @"/Users/Vikas/Desktop/theHulk.png";

NSData *data = [[NSFileManager defaultManager] contentsAtPat
h:sourceFile];

NSString *dataAsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Problem:

The above code is able to read and store the file to NSData however when I am converting the NSData to NSString, the value I am getting is nil

Research

StackOver Flow 1

StackOver Flow 2

S.P: If you have better suggestion for file encryption then please let me know as I am newbie.

1
Can you encrypt the data without converting to string? Generally, encryption works on bytes, not just stringsCarl Veazey
Actually, the library(AESCrypt) I am using is able to encrypt strings so I thought the if I want to encrypt a file then I need to convert it to NSString. It would be great if you could give me a hit about how to en/de-crypt NSData @CarlVeazeyVikas Bansal
Dont use that library then. Use common crypto directly or a diff abstraction of itCarl Veazey
stackoverflow.com/questions/2579453/… got that from searching encrypt nsdata, I believe you may be able to make similar searches to learn more ;)Carl Veazey
Not all data can be converted to any particular string encoding, in particular UTF-8. For tat reason if a string representation is needed the general solution is either to use Base64 or hexadecimal encoding.zaph

1 Answers

0
votes

According to this blog the string to data conversion forces a trailing \0 byte, which you might have to remove. This can be done as follows:

data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];

Try see if that works for you.