ios网络参数加密工具方法

传入字符串,输出它的base64编码结果

- (NSString *)getEncryption:(NSString *)data secret:(NSString *)secret{ 
 //传入 需要编码的数据
    
    NSString* key = secret;  //key固定
    
    const char *cKey = [key   cStringUsingEncoding:NSASCIIStringEncoding];  //转换为二进制数据
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
    
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *hash = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];   //得到一个hash二进制数
    
//调用类方法,参数为hash,进行数据编码,返回编码结果
    NSString *result = [PDEncryptionTools base64forData:hash];   

    return [result stringByReplacingOccurrencesOfString:@"+" withString:@"_"];
}

进行base64编码

+ (NSString*)base64forData:(NSData*)theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];   //数据 字节 类型转换为 8位2进制
    NSInteger length = [theData length];   //数据的长度
    
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;
            
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] = table[(value >> 18) & 0x3F];
        output[theIndex + 1] = table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];  //返回加密的数据
}

密钥
#define SECRET @"8b11c62e-2dfe-4921-b108-d9fd621ce7e5"

需要引入:
<Foundation/Foundation.h>、<CommonCrypto/CommonHMAC.h>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • /**ios常见的几种加密方法: 普通的加密方法是讲密码进行加密后保存到用户偏好设置( [NSUserDefaul...
    彬至睢阳阅读 8,196评论 0 7
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,833评论 19 139
  • 0x01 目录 常见编码: ASCII编码 Base64/32/16编码 shellcode编码 Quoted-p...
    H0f_9阅读 14,516评论 2 17
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 9,711评论 0 13
  • 北京的某个角落里有我的成长,快乐和悲伤一无所知的年纪里看不到花开,等不到未来似乎,所有的旅途从故乡的灵魂,到脚下的...
    立黄昏阅读 3,926评论 45 45

友情链接更多精彩内容