WXUtil.mm 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #import <Foundation/Foundation.h>
  2. #import "WXUtil.h"
  3. /*
  4. 加密实现MD5和SHA1
  5. */
  6. @implementation WXUtil
  7. //md5 encode
  8. +(NSString *) md5:(NSString *)str
  9. {
  10. const char *cStr = [str UTF8String];
  11. unsigned char digest[CC_MD5_DIGEST_LENGTH];
  12. CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
  13. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  14. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  15. [output appendFormat:@"%02X", digest[i]];
  16. return output;
  17. }
  18. //sha1 encode
  19. +(NSString*) sha1:(NSString *)str
  20. {
  21. const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
  22. NSData *data = [NSData dataWithBytes:cstr length:str.length];
  23. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  24. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  25. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  26. for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
  27. [output appendFormat:@"%02x", digest[i]];
  28. return output;
  29. }
  30. //http 请求
  31. +(NSData *) httpSend:(NSString *)url method:(NSString *)method data:(NSString *)data
  32. {
  33. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];
  34. //设置提交方式
  35. [request setHTTPMethod:method];
  36. //设置数据类型
  37. [request addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
  38. //设置编码
  39. [request setValue:@"UTF-8" forHTTPHeaderField:@"charset"];
  40. //如果是POST
  41. [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
  42. NSError *error;
  43. //将请求的url数据放到NSData对象中
  44. NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
  45. return response;
  46. //return [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
  47. }
  48. @end