aes256 ios 加密向量
2017-05-18 09:43:00 weixin_33788244 阅读数 35

import"NSData+AES256.h"

#import 《Foundation/Foundation.h》

#import 《CommonCrypto/CommonDigest.h》

#import 《CommonCrypto/CommonCryptor.h》

@interfaceNSData (AES256)

- (NSData*)aes256_encrypt:(NSString*)key;

- (NSData*)aes256_decrypt:(NSString*)key;

@end

import"NSData+AES256.m"

#import"NSData+AES256.h"

@implementationNSData (AES256)

- (NSData*)aes256_encrypt:(NSString*)key//加密

{

    charkeyPtr[kCCKeySizeAES256+1];

    bzero(keyPtr,sizeof(keyPtr));

    [keygetCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];

    NSUIntegerdataLength = [selflength];

    size_tbufferSize = dataLength +kCCBlockSizeAES128;

    void*buffer =malloc(bufferSize);

    size_tnumBytesEncrypted =0;

    CCCryptorStatuscryptStatus =CCCrypt(kCCEncrypt,kCCAlgorithmAES128,

    kCCOptionPKCS7Padding|kCCOptionECBMode,

    keyPtr,kCCBlockSizeAES128,NULL,[selfbytes], dataLength,buffer, bufferSize,&numBytesEncrypted);

    if(cryptStatus ==kCCSuccess)

    {

    return[NSDatadataWithBytesNoCopy:bufferlength:numBytesEncrypted];

    }

    free(buffer);

    returnnil;

    }

- (NSData*)aes256_decrypt:(NSString*)key//解密

{

    charkeyPtr[kCCKeySizeAES256+1];

    bzero(keyPtr,sizeof(keyPtr));

    [keygetCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];

    NSUIntegerdataLength = [selflength];

    size_tbufferSize = dataLength +kCCBlockSizeAES128;

    void*buffer =malloc(bufferSize);

    size_tnumBytesDecrypted =0;

    CCCryptorStatuscryptStatus =CCCrypt(kCCDecrypt,kCCAlgorithmAES128,

    kCCOptionPKCS7Padding|kCCOptionECBMode,keyPtr,kCCBlockSizeAES128,NULL,[selfbytes], dataLength,buffer, bufferSize,&numBytesDecrypted);

    if(cryptStatus ==kCCSuccess)

    {

    return[NSDatadataWithBytesNoCopy:bufferlength:numBytesDecrypted];

    }

    free(buffer);

    returnnil;

    }

@end

import"NSString+AES256.h"


#import 《Foundation/Foundation.h》

#import"NSData+AES256.h"

@interfaceNSString (AES256)

- (NSData*)aes256_encrypt:(NSString*)key;

- (NSData*)aes256_decrypt:(NSString*)key;

@end

import"NSString+AES256.m"

#import"NSString+AES256.h"

#import 《Security/Security.h》

@implementationNSString (AES256)

-(NSString*) aes256_encrypt:(NSString*)key

{

constchar*cstr = [selfcStringUsingEncoding:NSUTF8StringEncoding];

NSData*data = [NSDatadataWithBytes:cstrlength:self.length];

//对数据进行加密

NSData*result = [dataaes256_encrypt:key];

//转换为2进制字符串

if(result && result.length>0) {

Byte*datas = (Byte*)[resultbytes];

NSMutableString*output = [NSMutableStringstringWithCapacity:result.length*2];

for(inti =0; i < result.length; i++){

[outputappendFormat:@"%02x", datas[i]];

}

returnoutput;

}

returnnil;

}

-(NSString*) aes256_decrypt:(NSString*)key

{

//转换为2进制Data

NSMutableData*data = [NSMutableDatadataWithCapacity:self.length/2];

unsignedcharwhole_byte;

charbyte_chars[3] = {'\0','\0','\0'};

inti;

for(i=0; i < [selflength] /2; i++) {

byte_chars[0] = [selfcharacterAtIndex:i*2];

byte_chars[1] = [selfcharacterAtIndex:i*2+1];

whole_byte =strtol(byte_chars,NULL,16);

[dataappendBytes:&whole_bytelength:1];

}

//对数据进行解密

NSData* result = [dataaes256_decrypt:key];

if(result && result.length>0) {

return[[NSStringalloc]initWithData:resultencoding:NSUTF8StringEncoding];

}

    returnnil;

}

@end
2016-04-19 17:55:00 weixin_34220834 阅读数 11

NSData+AES.h 文件

#import <Foundation/Foundation.h>

@interface NSData (AES)

/**
 * Encrypt NSData using AES256 with a given symmetric encryption key.
 * @param key The symmetric encryption key
 */
- (NSData *)AES256EncryptWithKey:(NSString *)key;

/**
 * Decrypt NSData using AES256 with a given symmetric encryption key.
 * @param key The symmetric encryption key
 */
- (NSData *)AES256DecryptWithKey:(NSString *)key;

NSData+AES.m 文件

#import "NSData+AES.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSData (AES)

- (NSData *)AES256EncryptWithKey:(NSString *)key
{
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
    
    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [self length];
    
    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          keyPtr, kCCKeySizeAES256,
                                          NULL /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    
    free(buffer); //free the buffer;
    return nil;
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
    
    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [self length];
    
    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          keyPtr, kCCKeySizeAES256,
                                          NULL /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    
    free(buffer); //free the buffer;
    return nil;
}

@end

加密解密

    NSString *key = @"key";
    NSString *secret = @"text to encrypt";
    //加密
    NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *cipher = [plain AES256EncryptWithKey:key];
    
    printf("%s\n", [[cipher description] UTF8String]);
    NSLog(@"%@", [[NSString alloc] initWithData:cipher encoding:NSUTF8StringEncoding]);//打印出null,这是因为没有解密。
    
    //解密
    plain = [cipher AES256DecryptWithKey:key];
    printf("%s\n", [[plain description] UTF8String]);
    NSLog(@"%@", [[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding]);
2017-12-02 11:23:00 weixin_34232363 阅读数 43
- (NSString *)AES256Encrypt:(NSString *)dataString WithKey:(NSString *)key iv:(NSString *)iv {
    
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *dataToEncrypt = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [dataToEncrypt length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          keyData.bytes, kCCKeySizeAES256,
                                          ivData.bytes, // initialisation vector
                                          dataToEncrypt.bytes,
                                          dataToEncrypt.length, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        return [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
    }
    
    free(buffer); //free the buffer;
    return nil;
}
- (NSString *)AES256Decrypt:(NSString *)originString WithKey:(NSString *)key iv:(NSString *)iv {
    NSData *originData = [originString dataUsingEncoding:NSUTF8StringEncoding];
    NSData *cipherData = [GTMBase64 decodeData:originData];
    
    NSData *keydata = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *dataToEncrypt = cipherData;
    NSUInteger dataLength = [dataToEncrypt length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keydata.bytes,
                                          kCCKeySizeAES256,
                                          ivData.bytes,
                                          [dataToEncrypt bytes],
                                          [dataToEncrypt length],
                                          buffer,
                                          1024,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    free(buffer); //free the buffer;
    return nil;
}
2014-08-12 16:13:47 u014131398 阅读数 6553

     算法具体实现没有研究,使用关键是要保证加密和解密能够匹配上,而且要app和后台匹配上,才能够使用加密后的数据通信。

   1、AES128:

      AES128是需要一个初始化向量iv的,和256不一样。

//加密

- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv

{

    return [self AES128Operation:kCCEncrypt key:key iv:iv];

}

//解密

- (NSData *)AES128DecryptWithKey:(NSString *)key iv:(NSString *)iv

{

    return [self AES128Operation:kCCDecrypt key:key iv:iv];

}


//调用方法

- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv

{

    char keyPtr[kCCKeySizeAES128 + 1];

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

    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    

    char ivPtr[kCCBlockSizeAES128 + 1];

    memset(ivPtr, 0, sizeof(ivPtr));

    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

    

    NSUInteger dataLength = [self length];

    size_t bufferSize = dataLength + kCCBlockSizeAES128;

    void *buffer = malloc(bufferSize);

    

    size_t numBytesCrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(operation,

                                          kCCAlgorithmAES128,

                                          kCCOptionPKCS7Padding,

                                          keyPtr,

                                          kCCBlockSizeAES128,

                                          ivPtr,

                                          [self bytes],

                                          dataLength,

                                          buffer,

                                          bufferSize,

                                          &numBytesCrypted);

    if (cryptStatus == kCCSuccess) {

        return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];

    }

    free(buffer);

    return nil;

}

   

   2、AES256:

     

- (NSData *)AES256EncryptWithKey:(NSString *)key   //加密

{

    char keyPtr[kCCKeySizeAES256+1];

    bzero(keyPtr, sizeof(keyPtr));

    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    size_t bufferSize = dataLength + kCCBlockSizeAES128;

    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,

                                          kCCOptionPKCS7Padding | kCCOptionECBMode,

                                          keyPtr, kCCBlockSizeAES128,

                                          NULL,

                                          [self bytes], dataLength,

                                          buffer, bufferSize,

                                          &numBytesEncrypted);

    if (cryptStatus == kCCSuccess) {

        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];

    }

    free(buffer);

    return nil;

}


- (NSData *)AES256DecryptWithKey:(NSString *)key   //解密

{

    char keyPtr[kCCKeySizeAES256+1];

    bzero(keyPtr, sizeof(keyPtr));

    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    size_t bufferSize = dataLength + kCCBlockSizeAES128;

    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,

                                          kCCOptionPKCS7Padding | kCCOptionECBMode,

                                          keyPtr, kCCBlockSizeAES128,

                                          NULL,

                                          [self bytes], dataLength,

                                          buffer, bufferSize,

                                          &numBytesDecrypted);

    if (cryptStatus == kCCSuccess) {

        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];

    }

    free(buffer);

    return nil;

}

  

2016-10-24 23:18:33 u011154007 阅读数 1435

前言:加密算法在IOS中是很普遍的,很多地方都可能用的到,其中AES256和MD5加密是比较常用的。

一、MD5加密

#import <Foundation/Foundation.h>

@interface NSString (MD5Encrypt)

- (NSString *)md5Encrypt;

@end

#import "NSString+MD5Encrypt.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (MD5Encrypt)

- (NSString *)md5Encrypt {
    const char *original_str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (unsigned int)strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [hash appendFormat:@"%02x", result[i]];
    }
    return [hash uppercaseString];
}

+ (NSString *)md5:(NSString *)input
{
    const char *cStr = [input 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


二、AES256加密及解密

1、对NSData加密解密

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

@interface NSData(AES256)

- (NSData *)aes256_encrypt:(NSString *)key;
- (NSData *)aes256_decrypt:(NSString *)key;

@end

#import "NSData+AES256.h"

@implementation NSData(AES256)

- (NSData *)aes256_encrypt:(NSString *)key   //加密
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}


- (NSData *)aes256_decrypt:(NSString *)key   //解密
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        
    }
    free(buffer);
    return nil;
}
@end

2、对NSString加密解密

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

#import "NSData+AES256.h"

@interface NSString(AES256)

- (NSString *)aes256_encrypt:(NSString *)key;
- (NSString *)aes256_decrypt:(NSString *)key;

@end
#import "NSString +AES256.h"

@implementation NSString(AES256)

- (NSString *)aes256_encrypt:(NSString *)key
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    //对数据进行加密
    NSData *result = [data aes256_encrypt:key];
    //转换为2进制字符串
    if (result && result.length > 0) {
        
        Byte *datas = (Byte*)[result bytes];
        NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
        
        for(int i = 0; i < result.length; i++){
            [output appendFormat:@"%02x", datas[i]];
        }
        return output;
    }
    return nil;
}

- (NSString *)aes256_decrypt:(NSString *)key
{
    //转换为2进制Data
    NSMutableData *data = [NSMutableData dataWithCapacity:self.length / 2];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [self length] / 2; i++) {
        byte_chars[0] = [self characterAtIndex:i*2];
        byte_chars[1] = [self characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    
    //对数据进行解密
    NSData* result = [data aes256_decrypt:key];
    if (result && result.length > 0) {
        return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    }
    return nil;
}

@end




为什么80%的码农都做不了架构师?>>>...

博文 来自: weixin_33929309
没有更多推荐了,返回首页