aes128加解密 ios
2017-04-19 15:43:15 TechAlleyBoy 阅读数 8144

最近有个项目用过AES128 的加解密,搜了不少资料,最后封装了一个公共方法,分享一下。代码如下

一:.h文件

#import <Foundation/Foundation.h>

@interface FSAES128 : NSObject

/**
 *  加密
 *
 *  @param string 需要加密的string
 *
 *  @return 加密后的字符串
 */
+ (NSString *)AES128EncryptStrig:(NSString *)string;

/**
 *  解密
 *
 *  @param string 加密的字符串
 *
 *  @return 解密后的内容
 */
+ (NSString *)AES128DecryptString:(NSString *)string;
@end

二:.m文件

#import "FSAES128.h"
#import "NSData+AES128.h"

#define IV  @"偏移量 16位长度的字符串"
#define  KEY  @"key值 16位长度的字符串"

@implementation FSAES128

/**
 *  加密
 *
 *  @param string 需要加密的string
 *
 *  @return 加密后的字符串
 */
+ (NSString *)AES128EncryptStrig:(NSString *)string{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSData *aesData = [data AES128EncryptWithKey:KEY iv:IV];
    return [FSAES128 convertDataToHexStr:aesData];
}

/**
 *  解密
 *
 *  @param string 加密的字符串
 *
 *  @return 解密后的内容
 */
+ (NSString *)AES128DecryptString:(NSString *)string{
    NSData *data  = [FSAES128 convertHexStrToData:string];
    NSData *aesData = [data AES128DecryptWithKey:KEY iv:IV];
    return [[NSString alloc] initWithData:aesData encoding:NSUTF8StringEncoding];
}

//16进制转换为NSData
+ (NSData*)convertHexStrToData:(NSString*)str {
    if (!str || [str length] ==0) {
        return nil;
    }

    NSMutableData *hexData = [[NSMutableData alloc]initWithCapacity:[str length]*2];
    NSRange range;
    if ([str length] %2==0) {
        range = NSMakeRange(0,2);
    } else {
        range = NSMakeRange(0,1);
    }
    for (NSInteger i = range.location; i < [str length]; i +=2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc]initWithString:hexCharStr];

        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc]initWithBytes:&anInt length:1];
        [hexData appendData:entity];

        range.location+= range.length;
        range.length=2;
    }
//    NSLog(@"hexdata: %@", hexData);
    return hexData;
}

//NSData转换为16进制
+ (NSString*)convertDataToHexStr:(NSData*)data {
    if (!data || [data length] ==0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc]initWithCapacity:[data length]/2];

    [data enumerateByteRangesUsingBlock:^(const void*bytes,NSRange byteRange,BOOL*stop) {
        unsigned char *dataBytes = (unsigned  char*)bytes;
        for (NSInteger i =0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] ==2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];

    return string;
}

@end

三:NSData+AES128文件

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
@interface NSData (AES128)
/**
 *  加密
 *
 *  @param key 公钥
 *  @param iv  偏移量
 *
 *  @return 加密之后的NSData
 */
- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv;
/**
 *  解密
 *
 *  @param key 公钥
 *  @param iv  偏移量
 *
 *  @return 解密之后的NSData
 */
- (NSData *)AES128DecryptWithKey:(NSString *)key iv:(NSString *)iv;

@end
#import "NSData+AES128.h"

@implementation NSData (AES128)
/**
 *  根据CCOperation,确定加密还是解密
 *
 *  @param operation kCCEncrypt -> 加密  kCCDecrypt->解密
 *  @param key       公钥
 *  @param iv        偏移量
 *
 *  @return 加密或者解密的NSData
 */
- (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;

}


- (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];

}

@end

四:使用方法

//加密的字段
NSString *str = @"75677F53D5688E1FE9AC073E324B76BC6CCD8CCC05509FBF74375B40BDE50DA0B6A153355D82567B1E2FAAC96600C61064E9820AEA58E72C1DA3D3108F6DABE81E1766200F7183B0AB1F093B368F03321CB0D14EDDD57E3E64C2549FEC04C25187F8008AB90E4B7D0B69256A0467A923C56F004F721207C3A69E30D3470C08601523D79BE3F4907FC69A7CB02C747782ABC4A7F6D52CACB72DAE92984FFD73CA";

//解密字符串
NSString *contentStr = [FSAES128 AES128DecryptString:str];
contentStr 解密值:
{
    "freezeMoney": 0,
    "ordersMoney": null,
    "roleCode": 2,
    "status": 0,
    "totalMoney": 500,
    "userCode": "116092100000006",
    "userName": "13691116842",
    "walletId": "1"
}
2014-09-06 09:12:31 u011422739 阅读数 2137



闲话不多说 直接上代码:


加密:

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

{

    //    int kCCKeySizeAES128;

    //    int kCCBlockSizeAES128;

    

    

    char keyPtr[kCCKeySizeAES128+1];

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

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

    

    char ivPtr[kCCBlockSizeAES128+1];

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

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

    

    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [data length];

    

    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);

    int newSize = 0;

    

    if(diff > 0)

    {

        newSize = dataLength + diff;

    }

    

//    char dataPtr[newSize];

    Byte dataPtr[newSize];

    memcpy(dataPtr, [data bytes], [data length]);

    for(int i = 0; i < diff; i++)

    {

        dataPtr[i + dataLength] = 0x00;

    }

    

    size_t bufferSize = newSize + kCCBlockSizeAES128;

    void *buffer = malloc(bufferSize);

    memset(buffer, 0, bufferSize);

    

    size_t numBytesCrypted = 0;

    

  NSString *key = SERVICE_key;

    

    NSData *testData = [[key md5HexDigest] dataUsingEncoding: NSUTF8StringEncoding];


    Byte *testByte = (Byte *)[testData bytes];



    

    Byte keyByte[16];

    

    for(int i=8;i<[testData length];i++){

        

        if (i==24) {

            break;

        }

//        NSLog(@"testByte = %d\n",testByte[i]);

        keyByte[i-8]=testByte[i];

        

    }

    


    

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,

                                          kCCAlgorithmAES128,

                                          0X0000,               //No padding

                                          keyByte,

                                          kCCKeySizeAES128,

                                          ivPtr,

                                          dataPtr ,

                                          sizeof(dataPtr),

                                          buffer,

                                          bufferSize,

                                          &numBytesCrypted);

    


        if (cryptStatus == kCCSuccess) {

        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];

        return [GTMBase64New stringByEncodingData:resultData];

    }

    free(buffer);

    return nil;

}


解密

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

{

    char keyPtr[kCCKeySizeAES128 + 1];

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

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

    

    char ivPtr[kCCBlockSizeAES128 + 1];

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

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

    

    NSData *data = [GTMBase64New decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];

    NSUInteger dataLength = [data length];

    size_t bufferSize = dataLength + kCCBlockSizeAES128;

    void *buffer = malloc(bufferSize);

    

    size_t numBytesCrypted = 0;

//    NSData *testData = [gkey dataUsingEncoding: NSUTF8StringEncoding];


  NSString *key = SERVICE_key;


    NSData *testData = [[key md5HexDigest] dataUsingEncoding: NSUTF8StringEncoding];

    

    Byte *testByte = (Byte *)[testData bytes];


    

    Byte keyByte[16];

    

    for(int i=8;i<[testData length];i++){

        

        if (i==24) {

            break;

        }

        keyByte[i-8]=testByte[i];

        

    }

    

    

    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,

                                          kCCAlgorithmAES128,

                                          0X0000,

                                          keyByte,

                                          kCCKeySizeAES128,

                                          ivPtr,

                                          [data bytes],

                                          dataLength,

                                          buffer,

                                          bufferSize,

                                          &numBytesCrypted);

    

    

    if (cryptStatus == kCCSuccess) {

        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];

        return [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];

    }

    free(buffer);

    return nil;

}



将key就是一次md5加密 获得标准的固定16位字符,  ;

所有key 以及加密算法都要和后台一致 才能成功;


2018-02-08 12:04:00 weixin_34416649 阅读数 5

android上调用代码:mcrypt = new MCrypt();/* 加密*/String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("需加密的字符") );/* 解密*/String decrypted = new String( mcrypt.decrypt( encrypted ) );PHP上调用的代码:$mcrypt = new MCrypt();#Encrypt$encrypted = $mcrypt->encrypt("需加密的字符");#Decrypt$decrypted = $mcrypt->decrypt($encrypted);IOS上调用的代码:#import "Tool.h"// 加解密字符串NSString *string1 = @"fengzihua";NSString *encString = [Tool crypt:string1];NSLog(@"%@",encString); NSString *rawString = [Tool decrypt:encString];NSLog(@"%@",rawString); android实现加解密的代码:/***********//**JAVA**/ import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MCrypt { private String iv = "fedcba9876543210";//虚拟的 iv (需更改) private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher; private String SecretKey = "0123456789abcdef";//虚拟的 密钥 (需更改) public MCrypt() { ivspec = new IvParameterSpec(iv.getBytes()); keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES"); try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public byte[] encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return encrypted; } public byte[] decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); byte[] decrypted = null; try { cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return decrypted; } public static String bytesToHex(byte[] data) { if (data==null) { return null; } int len = data.length; String str = ""; for (int i=0; ihex2bin($key); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $encrypted = mcrypt_generic($td, $str); mcrypt_generic_deinit($td); mcrypt_module_close($td); return bin2hex($encrypted); } function decrypt($code) { //$key = $this->hex2bin($key); $code = $this->hex2bin($code); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $decrypted = mdecrypt_generic($td, $code); mcrypt_generic_deinit($td); mcrypt_module_close($td); return utf8_encode(trim($decrypted)); } protected function hex2bin($hexdata) { $bindata = ''; for ($i = 0; $i < strlen($hexdata); $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } }IOS实现加解密的代码:/**********//**Tool.h**/#import#import "CommonCrypto/CommonCrypto.h"

@interface Tool : NSObject

+ (NSString*) crypt:(NSString*)recource;

+ (NSString*) decrypt:(NSString*)recource;

@end

/**Tool.m**/

#import "Tool.h"

#define kCryptingKey @"0123456789abcdef"  /// 同上

#define kCryptingIv @"fedcba9876543210"  /// 同上

@implementation Tool

+ (NSString*) crypt:(NSString*)recource

{

    NSData *data = [recource dataUsingEncoding:NSUTF8StringEncoding];

    NSData *encrypt = [self AES128EncryptWithKey:kCryptingKey withData:data iv:kCryptingIv];

    return [self stringWithHexBytes:encrypt];

}

+ (NSString*) decryptData:(NSData*)recource

{

    NSData *decrypt = [self AES128DecryptWithKey:kCryptingKey withData:recource iv:kCryptingIv];

    return [[NSString alloc] initWithData:decrypt encoding:NSUTF8StringEncoding];

}

+ (NSString*) decrypt:(NSString*)recource

{

    NSData* data=[self decodeFromHexidecimal:recource];

    NSData *decrypt = [self AES128DecryptWithKey:kCryptingKey withData:data iv:kCryptingIv];

    return [[NSString alloc] initWithData:decrypt encoding:NSUTF8StringEncoding];

}

+ (NSData *) decodeFromHexidecimal:(NSString*)str

{

    NSString *command = [NSString stringWithString:str];

    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSMutableData *commandToSend = [[NSMutableData data] init];

    unsigned char whole_byte;

    char byte_chars[3] = {'\0','\0','\0'};

    int i;

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

        byte_chars[0] = [command characterAtIndex:i*2];

        byte_chars[1] = [command characterAtIndex:i*2+1];

        whole_byte = strtol(byte_chars, NULL, 16);

        [commandToSend appendBytes:&whole_byte length:1];

    }

    return commandToSend;

}

+ (NSData *)AES128EncryptWithKey:(NSString *)key withData:(NSData*)_data 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 = [_data length];


    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);

    unsigned long int newSize = 0;


    if(diff > 0)

    {

        newSize = dataLength + diff;

    }


    char dataPtr[newSize];

    memcpy(dataPtr, [_data bytes], [_data length]);

    for(int i = 0; i < diff; i++)

    {

        dataPtr[i + dataLength] = 0x00;

    }


    size_t bufferSize = newSize + kCCBlockSizeAES128;


    void *buffer = malloc( bufferSize );

    memset(buffer, 0, bufferSize);


    size_t numBytesEncrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, 0x0000,

                                          keyPtr, kCCKeySizeAES128,

                                          ivPtr,

                                          dataPtr,

                                          sizeof(dataPtr),

                                          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 *)AES128DecryptWithKey:(NSString *)key withData:(NSData*)data 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 = [data length];


    size_t bufferSize = dataLength + kCCBlockSizeAES128;

    void *buffer = malloc(bufferSize);


    size_t numBytesDecrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,  0x0000,

                                          keyPtr, kCCBlockSizeAES128,

                                          ivPtr,

                                          [data bytes],

                                          dataLength,

                                          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;

}

+ (NSString*) stringWithHexBytes:(NSData*)_data {

    NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([_data length] * 2)];

    const unsigned char *dataBuffer = [_data bytes];

    int i;

    for (i = 0; i < [_data length]; ++i) {

        [stringBuffer appendFormat:@"%02lX", (unsigned long)dataBuffer[i]];

    }

    return [stringBuffer copy];

}

@end

2015-04-16 17:29:00 weixin_34315485 阅读数 2

有个项目用过AES128 (CBC)的加密,当时搜索了很久的资料,基本不能使用。这里我自己写了一个可以用的  代码如下:

(PS:这个方法写的还有些瑕疵 不过已经足够正常使用了,有机会的话 会写的好看一点。。。转发要标注出处哦)

这是.h 

 1 //
 2 //  AES128CBC_No_Padding_Unit.h
 3 // 
 4 //
 5 //  Created by apple on 14-5-13.
 6 //  Copyright (c) 2014年 akforsure. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 @interface AES128CBC_No_Padding_Unit : NSObject
12 /**
13  *  AES128加密
14  *
15  *  @param plainText 原文
16  *
17  *  @return 加密好的字符串
18  */
19 + (NSString *)AES128Encrypt:(NSString *)plainText;
20 /**
21  *  AES128解密
22  *
23  *  @param encryptText 密文
24  *
25  *  @return 明文
26  */
27 + (NSString *)AES128Decrypt:(NSString *)encryptText;
28 @end

这是.m

  1 //
  2 //  AES128CBC_No_Padding_Unit.m
  3 // 
  4 //
  5 //  Created by apple on 14-5-13.
  6 //  Copyright (c) 2014年 akforsure. All rights reserved.
  7 //
  8 
  9 #import "AES128CBC_No_Padding_Unit.h"
 10 #import <CommonCrypto/CommonCryptor.h>
 11 #import "GTMBase64.h"
 12 @implementation AES128CBC_No_Padding_Unit
 13 + (NSString *)AES128Encrypt:(NSString *)plainText
 14 {
 15     char keyPtr[kCCKeySizeAES128+1];
 16     memset(keyPtr, 0, sizeof(keyPtr));
 17     [AESKEY getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
 18     
 19     char ivPtr[kCCBlockSizeAES128+1];
 20     memset(ivPtr, 0, sizeof(ivPtr));
 21     [AESIV getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
 22     
 23     NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
 24     NSUInteger dataLength = [data length];
 25     
 26     int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
 27     int newSize = 0;
 28     
 29     if(diff > 0)
 30     {
 31         newSize = dataLength + diff;
 32     }
 33     
 34     char dataPtr[newSize];
 35     memcpy(dataPtr, [data bytes], [data length]);
 36     for(int i = 0; i < diff; i++)
 37     {
 38         dataPtr[i + dataLength] = 0x00;
 39     }
 40     
 41     size_t bufferSize = newSize + kCCBlockSizeAES128;
 42     void *buffer = malloc(bufferSize);
 43     memset(buffer, 0, bufferSize);
 44     
 45     size_t numBytesCrypted = 0;
 46     
 47     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
 48                                           kCCAlgorithmAES128,
 49                                           0x0000,   //这里用的 NoPadding的填充方式
 50                                                     //除此以外还有 kCCOptionPKCS7Padding 和 kCCOptionECBMode
 51                                           keyPtr,
 52                                           kCCKeySizeAES128,
 53                                           ivPtr,
 54                                           dataPtr,
 55                                           sizeof(dataPtr),
 56                                           buffer,
 57                                           bufferSize,
 58                                           &numBytesCrypted);
 59     
 60     if (cryptStatus == kCCSuccess) {
 61         NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
 62         return [GTMBase64 stringByEncodingData:resultData];
 63     }
 64     free(buffer);
 65     return nil;
 66 }
 67 
 68 + (NSString *)AES128Decrypt:(NSString *)encryptText
 69 {
 70     char keyPtr[kCCKeySizeAES128 + 1];
 71     memset(keyPtr, 0, sizeof(keyPtr));
 72     [AESKEY getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
 73     
 74     char ivPtr[kCCBlockSizeAES128 + 1];
 75     memset(ivPtr, 0, sizeof(ivPtr));
 76     [AESIV getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
 77     
 78     NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
 79     NSUInteger dataLength = [data length];
 80     size_t bufferSize = dataLength + kCCBlockSizeAES128;
 81     void *buffer = malloc(bufferSize);
 82     
 83     size_t numBytesCrypted = 0;
 84     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
 85                                           kCCAlgorithmAES128,
 86                                           0x0000,
 87                                           keyPtr,
 88                                           kCCBlockSizeAES128,
 89                                           ivPtr,
 90                                           [data bytes],
 91                                           dataLength,
 92                                           buffer,
 93                                           bufferSize,
 94                                           &numBytesCrypted);
 95     if (cryptStatus == kCCSuccess) {
 96         NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
 97         return [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];
 98     }
 99     free(buffer);
100     return nil;
101 }
102 
103 @end

转载于:https://www.cnblogs.com/akforsure/p/4432730.html

2018-04-25 17:27:00 weixin_34392906 阅读数 32

在线加解密网址
http://www.seacha.com/tools/aes.html?src=wenhan123455678888050i33i206279278&mode=ECB&keylen=128&key=9ab7b2d96c018e7a&iv=9ab7b2d96c018e7a&bpkcs=pkcs7padding&session=SWkqdRzCEJoOtWBTKl6R&aes=1f074e036cd2b7d995649a1175a5d6f5&encoding=hex&type=0

本篇只讲(AES-128-ECB)的实现

//加密
+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key  
{  
    char keyPtr[kCCKeySizeAES128+1];  
    memset(keyPtr, 0, sizeof(keyPtr));  
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
      
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];  
    NSUInteger dataLength = [data length];  
      
    size_t bufferSize = dataLength + kCCBlockSizeAES128;  
    void *buffer = malloc(bufferSize);  
    size_t numBytesEncrypted = 0;  
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,  
                                          kCCAlgorithmAES128,  
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,  
                                          keyPtr,  
                                          kCCBlockSizeAES128,  
                                          NULL,  
                                          [data bytes],  
                                          dataLength,  
                                          buffer,  
                                          bufferSize,  
                                          &numBytesEncrypted);  
    if (cryptStatus == kCCSuccess) {  
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];  
        //return [GTMBase64 stringByEncodingData:resultData];  
        return [self hexStringFromData:resultData];  
  
    }  
    free(buffer);  
    return nil;  
}  
//解密
+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key  
{  
    char keyPtr[kCCKeySizeAES128 + 1];  
    memset(keyPtr, 0, sizeof(keyPtr));  
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
      
    //NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];  
      
    NSData *data=[self dataForHexString:encryptText];  
      
    NSUInteger dataLength = [data length];  
    size_t bufferSize = dataLength + kCCBlockSizeAES128;  
    void *buffer = malloc(bufferSize);  
      
    size_t numBytesCrypted = 0;  
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,  
                                          kCCAlgorithmAES128,  
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,  
                                          keyPtr,  
                                          kCCBlockSizeAES128,  
                                          NULL,  
                                          [data bytes],  
                                          dataLength,  
                                          buffer,  
                                          bufferSize,  
                                          &numBytesCrypted);  
    if (cryptStatus == kCCSuccess) {  
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];  
        return [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];  
    }  
    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;  
} 
//十六进制转Data  
//十六进制转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;
}

IOS加解密

阅读数 8

http://clement.blog.51cto.com/2235236/948107

博文 来自: weixin_34405354

ios加解密

阅读数 594

IOS加解密

阅读数 1

没有更多推荐了,返回首页