iOS13 sha256加密

#pragma mark ====== SHA256加密小写

```

- (NSString *)SHA256With:(NSString *)str{

    const char*s  = [str cStringUsingEncoding:NSASCIIStringEncoding];

    NSData*keyData = [NSData dataWithBytes:s length:strlen(s)];

    uint8_t digest[CC_SHA256_DIGEST_LENGTH] = {0};

    CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);

    NSData *out = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];

    NSString*hash = [selfhex:out];

    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];

    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];

    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];

    returnhash;

}

#pragma mark - String Conversion

-(NSString*)hex:(NSData*)data{

     NSMutableData*result = [NSMutableData dataWithLength:2*data.length];

     unsignedconstchar* src = data.bytes;

     unsignedchar* dst = result.mutableBytes;

     unsignedchart0, t1;

     for(inti =0; i < data.length; i ++ ) {

          t0 = src[i] >>4;

          t1 = src[i] &0x0F;

          dst[i*2] =48+ t0 + (t0 /10) *39;

          dst[i*2+1] =48+ t1 + (t1 /10) *39;

     }

     return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];

}

或者用一下方法

-(NSString*)sha256Message:(NSString*)body_content{

    const char *s = [body_content cStringUsingEncoding:NSUTF8StringEncoding];

      NSData*keyData = [NSData dataWithBytes:s length:strlen(s)];

      uint8_t digest[CC_SHA256_DIGEST_LENGTH] = {0};

      CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);

       NSData*outStr = [NSDatadataWithBytes:digestlength:CC_SHA256_DIGEST_LENGTH];

          //=======xcode编译ios13之后 格式变掉=======

      //    NSString *hash = [outStr description];

      //    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];

      //    //        hash = [hash stringByReplacingOccurrencesOfString:@"\n" withString:@""];

      //    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];

      //    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];

      //    return hash;

          //=========新的方式====

  constunsigned*tokenBytes = (constunsigned*)[outStrbytes];

          NSString *hexHash = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",                                 ntohl(tokenBytes[0]),ntohl(tokenBytes[1]),ntohl(tokenBytes[2]),                                 ntohl(tokenBytes[3]),ntohl(tokenBytes[4]),ntohl(tokenBytes[5]),                                 ntohl(tokenBytes[6]),ntohl(tokenBytes[7])];

    returnhexHash;

}

你可能感兴趣的:(iOS13 sha256加密)