NSDateFormatter 用于解密字符串
我正在尝试从网络服务器获取加密日期并将其转换为 NSDate 对象。但日期格式化程序总是返回零日期。解密的字符串不适用于日期格式化程序,但输入直接的日期字符串可以。
如何调试这个问题并让日期格式化程序来解析我的日期?
// 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]]];
I'm trying to get a encrypted date from a web server and convert it into NSDate object. But the date formatter always returns nil date. The decrypted string does not work with the date formatter, but typing a straight date string works.
How do I debug this problem and get date formatter to parse my date?
// 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]]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果当您硬编码“2011-04-02”时它有效,而当您认为已解密“2011-04-02”时它不起作用,那么显然这两个字符串之间存在一些差异。
如何解析和比较代码中的两个字符串,尝试找出差异所在。
例如:
运行代码并查看控制台输出。希望问题会更清楚一点。
Well, if it works when you hardcode "2011-04-02" and it doesn't work when you think you've decrypted "2011-04-02" then obviously there's some difference between those two strings.
How about parsing and comparing both strings in code, to try and find what the difference is.
For example:
Run the code and look at the console output. Hopefully the problem will be a little clearer.
不知道为什么解密后的字符串长度为 16,而正常字符串的长度为 10。
我设法通过删除控制字符来修复它。
decryptedString = [decryptedString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
Don't know why the decrypted string have length of 16, whereas the good string have length of 10.
I managed to fix it by removing the control characters.
decryptedString = [decryptedString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];