iOS下 AES128加密算法获取动态密码的实现

首先我们来看项目需求:


iOS下 AES128加密算法获取动态密码的实现_第1张图片

这是一款脱机门禁的设备,后台会给我们返回机器序列号和密钥,但是后台只会给我们返回6个字节的密钥和6个字节的机器序列号,首先我们需要将6个字节的密钥补齐为16字节

//判断秘钥长度 不够32位后面补0
这里的self.OfflineKey存储的是我获取的密钥
self.OfflineKeyStr 是要加密之前补齐16字节的密钥
    if ([self.OfflineKey length] < 32) {
        NSString *str = [self.OfflineKey stringByPaddingToLength:32 withString:@"0" startingAtIndex:0];
        self.OfflineKeyStr = str;
    }

因为是动态密码,所以这里根据的是时间的变化改变密码的值
这里的self.OfflineNum存储的是我获取的机身号
self.OfflineNumStr 是要加密之前补齐16字节的时间+机身号

NSDate *date =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    NSLog(@"currentDate = %@ ,year = %.2ld ,month=%.2ld, day=%.2ld",date,currentYear,currentMonth,currentDay);

    NSString *originalStr= [NSString stringWithFormat:@"%.2ld%.2ld%.2ld%@",currentYear,currentMonth,currentDay,self.OfflineNum];
    //判断机身号+长度 不够32位后面补0
    if ([originalStr length] < 32) {
        NSString *str = [originalStr stringByPaddingToLength:32 withString:@"0" startingAtIndex:0];
        self.OfflineNumStr = str;
    }

到目前为止 我们已经准备好了要加密的数据
下面准备进行AES 128加密
首先我们新建一个类
.h

//
//  AES128Util.h
//
//

#import 

@interface AES128Util : NSObject


+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key;


+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key;


+ (NSData*)dataForHexString:(NSString*)hexString;
@end

.m

//
//  AES128Util.m
//  
//


#import "AES128Util.h"
#import 

@implementation AES128Util


+(NSString *)AES128Encrypt:(NSString *)hexStringData key:(NSString *)hexStringKey
{
    NSData *keyData = [self dataForHexString:hexStringKey];
    char *keyPtr = (char *)[keyData bytes];
    
    NSData* data = [self dataForHexString:hexStringData];
    NSUInteger dataLength = [data length];
    char *dataPtr=(char *)[data bytes];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          dataPtr,
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytes:buffer length:numBytesEncrypted];
        free(buffer);
        return [self hexStringFromData:resultData];
    }
    
    free(buffer);
    return nil;
}




+(NSString *)AES128Decrypt:(NSString *)hexStringData key:(NSString *)hexStringKey
{
    NSData *keyData = [self dataForHexString:hexStringKey];
    char *keyPtr = (char *)[keyData bytes];
    
    NSData* data = [self dataForHexString:hexStringData];
    NSUInteger dataLength = [data length];
    char *dataPtr=(char *)[data bytes];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesCrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          dataPtr,
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytes:buffer length:numBytesCrypted];
        free(buffer);
        return [self hexStringFromData:resultData];
    }
    free(buffer);
    return nil;
}


// 普通字符串转换为十六进
+ (NSString *)hexStringFromData:(NSData *)data {
    Byte *bytes = (Byte *)[data bytes];
    // 下面是Byte 转换为16进制。
    NSString *hexStr = @"";
    for(int i=0; i<[data length]; i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i] & 0xff]; //16进制数
        newHexStr = [newHexStr uppercaseString];
        
        if([newHexStr length] == 1) {
            newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];
        }
        
        hexStr = [hexStr stringByAppendingString:newHexStr];
        
    }
    return hexStr;
}


//参考:http://blog.csdn.net/linux_zkf/article/details/17124577
//十六进制转Data
+ (NSData*)dataForHexString:(NSString*)hexString
{
    if (hexString == nil) {
        
        return nil;
    }
    
    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
    NSMutableData* data = [NSMutableData data];
    while (*ch) {
        if (*ch == ' ') {
            continue;
        }
        char byte = 0;
        if ('0' <= *ch && *ch <= '9') {
            
            byte = *ch - '0';
        }else if ('a' <= *ch && *ch <= 'f') {
            
            byte = *ch - 'a' + 10;
        }else if ('A' <= *ch && *ch <= 'F') {
            
            byte = *ch - 'A' + 10;
            
        }
        
        ch++;
        
        byte = byte << 4;
        
        if (*ch) {
            
            if ('0' <= *ch && *ch <= '9') {
                
                byte += *ch - '0';
                
            } else if ('a' <= *ch && *ch <= 'f') {
                
                byte += *ch - 'a' + 10;
                
            }else if('A' <= *ch && *ch <= 'F'){
                
                byte += *ch - 'A' + 10;
                
            }
            
            ch++;
            
        }
        
        [data appendBytes:&byte length:1];
        
    }
    
    return data;
}


@end

加密

//加密
    NSString *encryStr = [AES128Util AES128Encrypt:self.OfflineNumStr key:self.OfflineKeyStr];
    //转为16字节
    NSData *data = [AES128Util dataForHexString:encryStr];
    //截取后三个字节
    NSData *last3data = [data subdataWithRange:NSMakeRange(data.length-3, 3)];
    //变为int整形
    Byte *bytes = (Byte *)[last3data bytes];
    int i = ((bytes[0] & 0x000000ff) << 16) | ((bytes[1] & 0x000000ff) << 8) | (bytes[2] & 0x000000ff);
    
    NSString *result = [NSString stringWithFormat:@"%04d",i];
    if (result.length>4) {
        result = [result substringFromIndex:result.length-4];
    }
    NSLog(@"动态码==%@",result);

这里拿到的动态码就是最终我们需要的动态密码,因为我们加密只到天,所以密码是一天一变.

特别感谢-iOS开发交流群 群号:361736344 中深圳-标哥 的帮助(这里就不泄露QQ了 感兴趣的可以加群找他)

你可能感兴趣的:(iOS下 AES128加密算法获取动态密码的实现)