美文网首页iOSiOS Developer
iOS下 AES128加密算法

iOS下 AES128加密算法

作者: 弗雷德里希大王 | 来源:发表于2017-04-12 10:50 被阅读0次

    因为蓝牙4.0芯片自带AES128加密算法所以 只要涉及到蓝牙开发都会使用

    加密方法

    +(NSMutableData*)AES_NEW_AESEn:(NSMutableData*)plain pass:(NSMutableData*)key

    {

    // NSLog(@"key是%@",key);

    charkeyPtr[kCCKeySizeAES128+1];

    memset(keyPtr,0,sizeof(keyPtr));

    [keygetBytes:keyPtrlength:sizeof(keyPtr)];

    //NSLog(@"加密的KEY是%s",keyPtr);

    NSData* data = [[NSDataalloc]initWithData:plain];

    NSUIntegerdataLength = [datalength];

    size_tbufferSize = dataLength +kCCBlockSizeAES128;

    void*buffer =malloc(bufferSize);

    size_tnumBytesEncrypted =0;

    CCCryptorStatuscryptStatus =CCCrypt(kCCEncrypt,

    kCCAlgorithmAES128,

    kCCOptionPKCS7Padding|kCCOptionECBMode,

    keyPtr,

    kCCBlockSizeAES128,

    NULL,

    [databytes],

    dataLength,

    buffer,

    bufferSize,

    &numBytesEncrypted);

    if(cryptStatus ==kCCSuccess) {

    NSMutableData*resultData = [NSMutableDatadataWithBytes:bufferlength:numBytesEncrypted];

    returnresultData;

    }

    free(buffer);

    returnnil;

    }

    解密方法

    +(NSMutableData*)AES_NEW_AESDecrypt:(NSMutableData*)encryptText password:(NSMutableData*)key

    {

    charkeyPtr[kCCKeySizeAES128+1];

    memset(keyPtr,0,sizeof(keyPtr));

    [keygetBytes:keyPtrlength:sizeof(keyPtr)];

    NSData*data=[[NSDataalloc]initWithData:encryptText];

    NSUIntegerdataLength = [datalength];

    size_tbufferSize = dataLength +kCCBlockSizeAES128;

    void*buffer =malloc(bufferSize);

    size_tnumBytesCrypted =0;

    CCCryptorStatuscryptStatus =CCCrypt(kCCDecrypt,

    kCCAlgorithmAES128,

    kCCOptionECBMode,

    keyPtr,

    kCCBlockSizeAES128,

    NULL,

    [databytes],

    dataLength,

    buffer,

    bufferSize,

    &numBytesCrypted);

    if(cryptStatus ==kCCSuccess) {

    NSMutableData*resultData = [NSMutableDatadataWithBytesNoCopy:bufferlength:numBytesCrypted];

    returnresultData;

    }

    free(buffer);

    returnnil;

    }

    解密的时候没带  kCCOptionPKCS7Padding 如果发现需要就加上

    相关文章

      网友评论

        本文标题:iOS下 AES128加密算法

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