iOS sha1 encryption method (hash algorithm, used to verify data integrity) and encryption method when the string contains Chinese characters

 

 The first case: when there are no Chinese characters to be encrypted

首先需要添加头文件
#import<CommonCrypto/CommonDigest.h>
//需要加密的字符串中无汉字)然后直接使用下面的方法就可以了
//sha1加密方式
- (NSString *) sha1:(NSString *)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)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;
}

  The second case: when there are Chinese characters to be encrypted

首先需要添加头文件
#import<CommonCrypto/CommonDigest.h>
然后直接使用下面的方法就可以了
//sha1加密方式
- (NSString *) sha1:(NSString *)input
{
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
     NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)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;
}

Guess you like

Origin blog.csdn.net/ximiaoweilai/article/details/102747842