NSDateFormatter用于解密的字符串

时间:2011-04-03 05:16:56

标签: iphone cocoa-touch aes encryption nsdateformatter

我正在尝试从Web服务器获取加密日期并将其转换为NSDate对象。但日期格式化程序始终返回nil日期。解密的字符串不适用于日期格式化程序,但键入直接日期字符串有效。

如何调试此问题并获取日期格式化程序来解析我的日期?

// Decrypt the message
NSData *encrypted = [NSData dataFromBase64String:dataReturned];
NSData *decrypted = [encrypted AES128DecryptWithKey:key];
NSString *decryptedString = [[NSString alloc] initWithData:decrypted encoding:NSASCIIStringEncoding]; 
// decryptedString is @"2011-04-02" according to GDB

//  NSString *decryptedString = @"2011-04-02"; //This works
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[formatter setLocale:enUSPOSIXLocale];
[formatter setDateFormat:@"yyyy-MM-dd"];

NSDate *expiryDate = [formatter dateFromString:[decryptedString stringByTrimmingCharactersInSet:
                                                [NSCharacterSet whitespaceAndNewlineCharacterSet]]];

2 个答案:

答案 0 :(得分:3)

好吧,如果你在硬编码“2011-04-02”时有效并且当你认为你已经解密“2011-04-02”时它不起作用那么显然这两个字符串之间存在一些差异。

如何在代码中解析和比较两个字符串,以尝试找出差异。

例如:

decryptedString = [decryptedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSString* goodString = @"2011-04-02";

NSLog(@"Decrypted String: %@", decryptedString);
NSLog(@"Good String: %@", goodString);
NSLog(@"Compare: %d" [goodString compare:decryptedString]);  // 0 means they're identical.

NSDate* expiryDate = [formatter dateFromString:decryptedString];
NSDate* goodDate = [formatter dateFromString:goodString];

NSLog(@"Decrypted Date: %@", expiryDate);
NSLog(@"Good Date: %@", goodDate);

运行代码并查看控制台输出。希望问题会更清楚一点。

答案 1 :(得分:0)

不知道为什么解密后的字符串长度为16,而好字符串的长度为10。

我设法通过删除控制字符来修复它。

decryptedString = [decryptedString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];

相关问题