美文网首页
iOS字符串NSString加密SHA/MD5(Objectiv

iOS字符串NSString加密SHA/MD5(Objectiv

作者: Raywf | 来源:发表于2018-03-20 14:38 被阅读0次

    2018.3.20

    字符串在线加密
    在线加密1

    iOS 简单应用
    创建一个NSString分类

    //  NSString+RFCategory.h
    #import <Foundation/Foundation.h>
    
    @interface NSString (RFCategory)
    
    ///SHA-1加密
    - (NSString *)rf_EncryptSHA1;
    
    ///SHA-256加密
    - (NSString *)rf_EncryptSHA256;
    
    ///MD5加密
    - (NSString *)rf_EncryptMD5;
    
    @end
    
    
    //  NSString+RFCategory.m
    #import "NSString+RFCategory.h"
    #import <CommonCrypto/CommonDigest.h>
    
    @implementation NSString (RFCategory)
    
    - (NSString *)rf_EncryptSHA1 {
        if (self.length<=0) return nil;
    
        const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
        NSData *keyData = [NSData dataWithBytes:cstr length:self.length];
    
        return [NSString RF_EncryptSHA1:keyData];
    }
    + (NSString *)RF_EncryptSHA1:(NSData *)keyData {
        if (keyData.length<=0) return nil;
    
        uint8_t digest[CC_SHA1_DIGEST_LENGTH];
        CC_SHA1(keyData.bytes, (unsigned int)keyData.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 *)rf_EncryptSHA256 {
        if (self.length<=0) return nil;
    
        const char *s = [self cStringUsingEncoding:NSASCIIStringEncoding];
        NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
    
        return [NSString RF_EncryptSHA256:keyData];
    }
    + (NSString *)RF_EncryptSHA256:(NSData *)keyData {
        if (keyData.length<=0) return nil;
    
        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 = [out description];
        hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
    
        return hash;
    }
    
    - (NSString *)rf_EncryptMD5 {
        if (self.length<=0) return nil;
    
        const char *cStr = [self UTF8String];
        unsigned char digest[16];
        CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
    
        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;
    }
    
    @end
    

    参考链接:
    1.iOS sha256加密

    相关文章

      网友评论

          本文标题:iOS字符串NSString加密SHA/MD5(Objectiv

          本文链接:https://www.haomeiwen.com/subject/ilxbqftx.html