【问题标题】:Getting MD5 and SHA-1获取 MD5 和 SHA-1
【发布时间】:2023-03-12 09:10:01
【问题描述】:

我正在寻求在我的 iPhone 应用程序中获取 MD5 和 SHA-1 的帮助。 谁能给我一个关于如何获得这些的想法?

【问题讨论】:

标签: ios objective-c md5 sha


【解决方案1】:
#include <CommonCrypto/CommonDigest.h>

-(NSString*) sha1:(NSString*)input
{

 NSData *data = [input dataUsingEncoding: NSUTF8StringEncoding]; 

 uint8_t digest[CC_SHA1_DIGEST_LENGTH];

 CC_SHA1(data.bytes, data.length, digest);

 NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

 for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
 [output appendFormat:@"%02x", digest[i]];

 return output;

}

- (NSString *) md5:(NSString *) input
{
 const char *cStr = [input UTF8String];
 unsigned char digest[CC_MD5_DIGEST_LENGTH];
 CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call

 NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

 for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
 [output appendFormat:@"%02x", digest[i]];

 return  output;

}

还可以在这里查看我的博客文章 - http://www.makebetterthings.com/blogs/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/

【讨论】:

  • 不要忘记在您的实现代码顶部添加#import &lt;CommonCrypto/CommonDigest.h&gt;。无需链接libcommonCrypto.dylib
  • 你为什么用 CC_SHA1_DIGEST_LENGTH*2 初始化 mutableString 而不仅仅是 [NSMutableString string] ?
  • NSData *data = [NSData dataWithBytes:cstr length:input.length]; 行将中断非 ASCII 字符串。我建议使用 strlen(cstr) 而不是 input.length。
  • 是的,sha1 方法的前两行确实在 unicode 字符(例如大引号)上中断。我通过将这两行替换为: NSData *data = [input dataUsingEncoding: NSUTF8StringEncoding];
  • @lifjoy - 感谢您指出这一点。我刚刚更新了答案。再次感谢!
猜你喜欢
  • 2017-12-03
  • 2013-04-29
  • 2013-09-08
  • 1970-01-01
  • 2011-09-12
  • 2021-09-05
  • 2019-08-24
  • 1970-01-01
  • 2019-04-26
相关资源
最近更新 更多