您的位置:首页 > 其它

使用AES加密的时候(encryptString:(NSString*)string withKey:(NSString*)key) 出现结果是nil

2016-12-15 11:57 351 查看
//问题代码

+(NSString*)encryptString:(NSString*)string withKey:(NSString*)key{
    NSString *result =
nil;
    NSData *data = [string
dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",[data AES256EncryptWithKey:key]);
    result = [[NSString
alloc] initWithData:[data
AES256EncryptWithKey:key]
encoding:NSUTF8StringEncoding];
    return result;
}

//解决方式

+(NSString*)encryptString:(NSString*)string withKey:(NSString*)key{
    NSString *result =
nil;
    NSData *data = [string
dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",[data
AES256EncryptWithKey:key]);
    result = [[NSString
alloc] initWithData:[GTMBase64
encodeData:[data AES256EncryptWithKey:key]]
encoding:NSUTF8StringEncoding];
    return result;
}

解决方案来自:http://stackoverflow.com/questions/29503546/initwithdata-returns-null


initWithData
returns (null)

up
vote0down
votefavorite

Well, I have a code that selects a text, and converts it to NSData then encrypts it with AES-256 and then converts this NSData to a NSString to be displayed the message encrypted, I'm doing this as follows:
NSString *text = @"This is a simple text";

NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];

NSData *dataEnc = [data AES256EncryptWithKey:@"12556"];

NSString *stringCrypt = [[NSString alloc] initWithData:dataEnc encoding:NSUTF8StringEncoding];

NSData *dataDesc = [dataEnc AES256DecryptWithKey:@"12556"];

NSString *string = [[NSString alloc] initWithData:dataDesc encoding:NSUTF8StringEncoding];

NSLog(@"Text normal -> %@",text);

NSLog(@"Text with AES -> %@",stringCrypt);

NSLog(@"Text with AES decrypted -> %@",string);


The output of my NSLog is:
Text normal -> this is a simple text
Text with AES -> (null)
Text With AES decrypted -> this is a simple text


So the problem is with the code:
NSString *stringCrypt = [[NSString alloc] initWithData:dataEnc encoding:NSUTF8StringEncoding];


That return a null string, and in this case I need that string that will be inserted into a text file, how to solve this problem? why this returning a null value?

EDIT

The function to convert it to AES256 is:
- (NSData *)AES256EncryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}

free(buffer); //free the buffer;
return nil;
}


Solved

As the user Zaph says, I need to use the 
-base64EncodedDataWithOptions
,
in my case I do as follows:
NSString *text = @"This is a simple text";

NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];

NSData *dataEnc = [data AES256EncryptWithKey:@"12556"];

NSData *daes = [dataEnc base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];

NSString *stringCrypt = [[NSString alloc] initWithData:daes encoding:NSUTF8StringEncoding];

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:stringCrypt options:0];

NSData *dataDesc = [decodedData AES256DecryptWithKey:@"12556"];

NSString *string = [[NSString alloc] initWithData:dataDesc encoding:NSUTF8StringEncoding];

NSLog(@"Text Normal -> %@",text);

NSLog(@"Text with AES (BASE64) -> %@",stringCrypt);

NSLog(@"Text with AES decrypted -> %@",string);


In this case I only need to convert it to a base64 string, and now I can store this values inside a text value, and other device can get this text and decrypt. Thanks for all.

ios objective-c nsstring nsdata
shareimprove
this question
edited Apr
8 '15 at 11:26

asked Apr 8 '15 at 0:00





LettersBa
277116

 
 
The point of AES-256 is to have a long key, 32-bytes and the key being used is 6-bytes? – zaph Apr
8 '15 at 1:56
 
Why would you expect encrypted data to be printable? – Hot
Licks Apr
8 '15 at 3:00
 
@HotLicks, Lets go... I have an app that will send some information to my server (this information is special like name,
country, telephone, city and others) my app will send in a XML format, and I need to convert this strings to AES256 and get the encrypted strings and put inside my xml file and send it to my server. Thats what I need data to be printable. – LettersBa Apr
8 '15 at 11:30
 
@HotLicks, I can convert my information to NSData and send to my server with NSKeyUnarchive? Yes I can, but I think
in the future, and other devices like android and windows phone will need access this files, and if I do in this way, IOS is the only device that will read this files. then I need to send in a way in which everyone can read and decrypt, I do not believe the
android or windows phone system can read a NSData file, no? – LettersBa Apr
8 '15 at 11:33
 
Why would you expect encrypted data to be printable? This has nothing to do with whether the data can be stored in a
file, etc. If it needs to be transmitted as "text" then you should use Base64 encoding, as suggested.– Hot
Licks Apr
8 '15 at 12:19
add
a comment


2 Answers

activeoldestvotes

up vote1down
voteaccepted
Random bytes, and that is what encrypted looks like and can not be distinguished from, rarely is convertible to a string. This is why encrypted data is often Base64 encoded to produce printable characters.

Use 
-
base64EncodedStringWithOptions:
 to encode the encrypted data to a character string.

shareimprove
this answer
answered Apr 8 '15 at 1:45





zaph
78.8k14115160

 
 
Problem solved, thanks man. I will edit my question for future persons... – LettersBa Apr
8 '15 at 11:20
add
a comment
up vote2down
vote
I expect your 
initWithData
 is
failing because 
dataEnc
 most
certainly does not contain UTF8 bytes. Assuming your AES256 encryption code is working correctly, it is going to return binary data that looks essentially random. It will not be realistically convertible to a string unless you do something like go through
it byte by byte and output hex values.

You can write the encrypted NSData to a file directly using one of its 
writeToFile
 methods.

shareimprove
this answer
answered Apr 8 '15 at 0:10





Tom
17610

 
 
I will update my post to you see what the AES256 do... – LettersBa Apr
8 '15 at 0:12
 
Yep, that confirms it. See my edit about writing the NSData directly. You'll see gibberish if you open the file in a
text editor, but that's kind of the idea. :) – Tom Apr
8 '15 at 0:21
 
Well If I have many strings to convert I can do I loop to convert it to AES and wirteToFile, and finally get this file
and convert it to NSString and now I will see in my NSLog the my string crypted? – LettersBa Apr
8 '15 at 0:39
 
Imagine you walk over to a person who can do AES256 encryption for you. You give them a piece of paper with a message.
They think for a while and start reading numbers to you: "50, 196, 12, 3, 100...". These numbers are all between 0 and 255. That series of numbers is your encrypted message. There is no logical way to go from a bunch of numbers to an NSString automatically.
"What letter is a 250?" So if you must have it displayed as text you need to think carefully about how it should work. – Tom Apr
8 '15 at 0:47 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐