美文网首页
iOS NSString类别的常用加密+验证方法

iOS NSString类别的常用加密+验证方法

作者: huangxiongbiao | 来源:发表于2017-04-19 19:50 被阅读89次

    使用背景:

    app开发过程中,经常需要对输入提交的内容进行验证格式(如:电话号码,身份证等)可以使用类别的方法简单搞定。另外常用加密也可以进行封装,方方便正常开发使用

    代码如下:
    .h文件

    #import <Foundation/Foundation.h>
    #import <CommonCrypto/CommonCryptor.h>
    #import <CommonCrypto/CommonDigest.h>
    #import "GTMBase64.h"
    
    #define iOSLess8_0 [[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0
    
    @interface NSString (Category)
    
    + (const char *)UnicodeToISO88591:(NSString *)src;
    
    + (NSString *)_859ToUTF8:(NSString *)oldStr;
    
    + (NSString *)stringFromHexString:(NSString *)hexString;
    
    + (NSString *)hexStringFromString:(NSString *)string;
    
    + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key;
    
    + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key;
    
    +(NSData *)TripleDES:(NSString *)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt encryptOrDecryptKey:(NSString *)encryptOrDecryptKey;
    
    + (NSString *)md5:(NSString *)str;
    //验证
    + (BOOL) validateEmail:(NSString *)email;
    + (BOOL) validateMobile:(NSString *)mobile;
    + (BOOL) validateCarNo:(NSString *)carNo;
    + (BOOL) validateCarType:(NSString *)CarType;
    + (BOOL) validateUserName:(NSString *)name;
    + (BOOL) validateNickname:(NSString *)nickname;
    + (BOOL) validateIdentityCard: (NSString *)identityCard;
    
    #ifdef  iOSLess8_0
    -(BOOL)containsString:(NSString *)str;
    #endif
    
    @end
    

    .m文件

    #import "NSString+Category.h"
    #import <CommonCrypto/CommonDigest.h>
    
    //threeKey=====57566778E82E07A12017042283723415==
    //keyId====F3EFC2F26C66006D===
    //pinkdata ==<47dff4b5 dad06c1e>==(null)+
    //pinkey====<47dff4b5 dad06c1e>==
    //randomstr+pid==4634313234454142==7a9860eca85a1e56==
    //key+data===<47dff4b5 dad06c1e>+<46343132 34454142>
    //=0
    //key+data===<47dff4b5 dad06c1e>+<7a9860ec a85a1e56>
    //data1+data2==<821da271 e37b4b0b>+<3cf9d4f1 0c03d3cd>
    //key+data===<821da271 e37b4b0b>+<3cf9d4f1 0c03d3cd>
    //keyData====<57488727 1c7dcdfc>
    
    @implementation NSString (Category)
    
    + (const char *)UnicodeToISO88591:(NSString *)src
    {
        NSStringEncoding enc =      CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
        return [src cStringUsingEncoding:enc];
    }
    + (NSString *)_859ToUTF8:(NSString *)oldStr
    {
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
        
        return [NSString stringWithUTF8String:[oldStr cStringUsingEncoding:enc]];
    }
    // 十六进制转换为普通字符串的。
    + (NSString *)stringFromHexString:(NSString *)hexString { //
        
        char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
        bzero(myBuffer, [hexString length] / 2 + 1);
        for (int i = 0; i < [hexString length] - 1; i += 2) {
            unsigned int anInt;
            NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
            NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
            [scanner scanHexInt:&anInt];
            myBuffer[i / 2] = (char)anInt;
        }
        NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    //    NSLog(@"------字符串=======%@",unicodeString);
        return unicodeString;
        
        
    }
    
    //普通字符串转换为十六进制的。
    + (NSString *)hexStringFromString:(NSString *)string{
        NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
        Byte *bytes = (Byte *)[myD bytes];
        //下面是Byte 转换为16进制。
        NSString *hexStr=@"";
        for(int i=0;i<[myD length];i++)
            
        {
            NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
            
            if([newHexStr length]==1)
                
                hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
            
            else 
                
                hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr]; 
        } 
        return hexStr; 
    }
    
    /******************************************************************************
     函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
     函数描述 : 文本数据进行DES加密
     输入参数 : (NSData *)data
     (NSString *)key
     输出参数 : N/A
     返回参数 : (NSData *)
     备注信息 : 此函数不可用于过长文本
     ******************************************************************************/
    + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
    {
    //    char keyPtr[kCCKeySizeAES256+1];
    //    bzero(keyPtr, sizeof(keyPtr));
    //    
    //    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
        const void *vkey ;//= (const void *)[encryptOrDecryptKey UTF8String];
        DDLog(@"key+data===%@+%@",[NSData dataWithHexString:key],data);
        
        vkey = [[NSData dataWithHexString:key] bytes];
        
        NSUInteger dataLength = [data length];
        
    //    CCCryptorStatus ccStatus;
    //    uint8_t *bufferPtr = NULL;
    //    size_t bufferPtrSize = 0;
    //    size_t movedBytes = 0;
    //    ccStatus = CCCrypt(encryptOrDecrypt,
    //                       kCCAlgorithm3DES,
    //                       kCCOptionPKCS7Padding | kCCOptionECBMode,
    //                       vkey,
    //                       kCCKeySize3DES,
    //                       nil,
    //                       vplainText,
    //                       plainTextBufferSize,
    //                       (void *)bufferPtr,
    //                       bufferPtrSize,
    //                       &movedBytes);
        
        size_t bufferSize = dataLength + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
    //    uint8_t *buffer = malloc(8);
    //    size_t bufferSize = 8;
        size_t numBytesEncrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                              kCCOptionPKCS7Padding | kCCOptionECBMode,
                                              vkey, 8,
                                              nil,
                                              [data bytes], 8,
                                              (void*)buffer, bufferSize
                                              ,&numBytesEncrypted);
        NSLog(@"=%d",cryptStatus);
        if (cryptStatus == kCCSuccess) {
            return [NSData dataWithBytesNoCopy:buffer length:8];
        }
        
        free(buffer);
        return nil;
    }
    
    /******************************************************************************
     函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
     函数描述 : 文本数据进行DES解密
     输入参数 : (NSData *)data
     (NSString *)key
     输出参数 : N/A
     返回参数 : (NSData *)
     备注信息 : 此函数不可用于过长文本
     ******************************************************************************/
    + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key
    {
        char keyPtr[kCCKeySizeAES256+1];
        bzero(keyPtr, sizeof(keyPtr));
        
        [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
        
        NSUInteger dataLength = [data length];
        
        size_t bufferSize = dataLength + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
        
        size_t numBytesDecrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                                              kCCOptionPKCS7Padding | kCCOptionECBMode,
                                              keyPtr, kCCBlockSizeDES,
                                              NULL,
                                              [data bytes], dataLength,
                                              buffer, bufferSize,
                                              &numBytesDecrypted);
        
        if (cryptStatus == kCCSuccess) {
            return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        }
        
        free(buffer);
        return nil;
    }
    
    +(NSData *)TripleDES:(NSString *)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt encryptOrDecryptKey:(NSString *)encryptOrDecryptKey
    {
        
        const void *vplainText;
        size_t plainTextBufferSize;
        
        if (encryptOrDecrypt == kCCDecrypt)//解密
        {
    //        NSData *EncryptData = [GTMBase64 decodeData:[plainText dataUsingEncoding:NSUTF8StringEncoding]];
    //        NSData *EncryptData = [GTMBase64 decodeData:[NSData dataWithHexString:plainText]];
            NSData *EncryptData = [NSData dataWithHexString:plainText];
            plainTextBufferSize = [EncryptData length];
            vplainText = [EncryptData bytes];
        }
        else //加密
        {
            NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
            plainTextBufferSize = [data length];
            vplainText = (const void *)[data bytes];
        }
        
        CCCryptorStatus ccStatus;
        uint8_t *bufferPtr = NULL;
        size_t bufferPtrSize = 0;
        size_t movedBytes = 0;
        
        bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
        bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
        memset((void *)bufferPtr, 0x0, bufferPtrSize);
        // memset((void *) iv, 0x0, (size_t) sizeof(iv));
    //    NSNEXTSTEPStringEncoding
        
        const void *vkey ;//= (const void *)[encryptOrDecryptKey UTF8String];
        
        vkey = [[NSData dataWithHexString:encryptOrDecryptKey] bytes];
        
        // NSString *initVec = @"init Vec";
        //const void *vinitVec = (const void *) [initVec UTF8String];
        //  Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
        ccStatus = CCCrypt(encryptOrDecrypt,
                           kCCAlgorithm3DES,
                           kCCOptionPKCS7Padding | kCCOptionECBMode,
                           vkey,
                           16,
                           nil,
                           vplainText,
                           8,
                           (void *)bufferPtr,
                           bufferPtrSize,
                           &movedBytes);
        //if (ccStatus == kCCSuccess) NSLog(@"SUCCESS");
        /*else if (ccStatus == kCC ParamError) return @"PARAM ERROR";
         else if (ccStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
         else if (ccStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
         else if (ccStatus == kCCAlignmentError) return @"ALIGNMENT";
         else if (ccStatus == kCCDecodeError) return @"DECODE ERROR";
         else if (ccStatus == kCCUnimplemented) return @"UNIMPLEMENTED"; */
        
        NSString *result;
        NSData *resultData;
        if (encryptOrDecrypt == kCCDecrypt)
        {
            result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                                    length:(NSUInteger)movedBytes]
                                            encoding:NSUTF8StringEncoding];
            resultData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
            NSLog(@"pinkdata ==%@==%@+%d",resultData,result,ccStatus);
        }
        else
        {
            resultData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
            result = [GTMBase64 stringByEncodingData:resultData];
        }
        
        return resultData;
    }
    
    + (NSString *)md5:(NSString *)str
    {
        const char *cStr = [str UTF8String];
        unsigned char result[16];
        CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
        return [NSString stringWithFormat:
                @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                result[0], result[1], result[2], result[3],
                result[4], result[5], result[6], result[7],
                result[8], result[9], result[10], result[11],
                result[12], result[13], result[14], result[15]
                ];
    }
    
    #ifdef  iOSLess8_0
    -(BOOL)containsString:(NSString *)str
    {
        NSRange range = [self rangeOfString:str];
        if(range.location != NSNotFound) return YES;
        return NO;
    }
    #endif
    
    //邮箱
    + (BOOL) validateEmail:(NSString *)email
    {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        return [emailTest evaluateWithObject:email];
    }
    
    
    //手机号码验证
    + (BOOL) validateMobile:(NSString *)mobile
    {
        //手机号以13, 15,18开头,八个 \d 数字字符
        NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
        return [phoneTest evaluateWithObject:mobile];
    }
    
    
    //车牌号验证
    + (BOOL) validateCarNo:(NSString *)carNo
    {
        NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
        NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
        NSLog(@"carTest is %@",carTest);
        return [carTest evaluateWithObject:carNo];
    }
    
    
    //车型
    + (BOOL) validateCarType:(NSString *)CarType
    {
        NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
        NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
        return [carTest evaluateWithObject:CarType];
    }
    
    
    //用户名
    + (BOOL) validateUserName:(NSString *)name
    {
        NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
        NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
        BOOL B = [userNamePredicate evaluateWithObject:name];
        return B;
    }
    //昵称
    + (BOOL) validateNickname:(NSString *)nickname
    {
        NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
        NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
        return [passWordPredicate evaluateWithObject:nickname];
    }
    
    
    //身份证号
    + (BOOL) validateIdentityCard: (NSString *)identityCard
    {
        BOOL flag;
        if (identityCard.length <= 0) {
            flag = NO;
            return flag;
        }
        NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
        NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
        return [identityCardPredicate evaluateWithObject:identityCard];
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:iOS NSString类别的常用加密+验证方法

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