aes ios php 加密
2017-08-02 14:25:00 weixin_33766168 阅读数 26

首先 需和后台约定 偏移量, 和 key 的值 (必须的一致 切记)

#define IV          @"20170101" //偏移量,可自行修改
#define KEY         @"wangyuceshi" //key,可自行修改 只要和后台约定好即可

*加密

#pragma mark - AES加密
//将string转成带密码的data
+(NSString*)encryptAESData:(NSString*)string
{
if (string.length==0) {
return @"";
}
//将nsstring转化为nsdata
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//使用密码对nsdata进行加密
NSData *encryptedData = [data AES128EncryptWithKey:KEY gIv:IV];
//返回进行base64进行转码的加密字符串
return [self convertStringToHexStr:[CustomBase64 encode:encryptedData]];
}

*解密

#pragma mark - AES解密
//将带密码的data转成string
+(NSString*)decryptAESData:(NSString *)string
{
if (string.length==0) {
return @"";
}
//base64解密
NSData *decodeBase64Data=[CustomBase64 decode:[self stringFromHexString:string]];
//使用密码对data进行解密
NSData *decryData = [decodeBase64Data AES128DecryptWithKey:KEY gIv:IV];
//将解了密码的nsdata转化为nsstring
NSString *str = [[NSString alloc] initWithData:decryData encoding:NSUTF8StringEncoding];
return str;
}

使用用法

1.导入 #import "AESCommonCrypto.h"
*加密

NSString *encryptoStr           = [AESCommonCrypto encryptAESData:self.textFIeld.text];

*解密

NSString *decryptStr            = [AESCommonCrypto decryptAESData:self.encryptoLbl.text];

效果图


5345406-501b6b835dd487ee.png
Simulator Screen Shot 2017年8月2日 上午11.51.20.png

详情请见 Githud 地址 https://github.com/wyxlh/AESEncryption

2017-12-29 16:50:47 linlinyin1991 阅读数 211

AES:对称加密算法

AES是一种对称加密算法,加密和解密密钥为同一个,密钥的长度最少支持为128、192、256,分组长度128位。

我们项目中是AES加密完成之后再用Base64加密一下,所以解密的时候就需要先解密Base64,再进行AES解密,Base64这步并不是必须的。

关键代码

//定义加密密钥长度类型
typedef NS_ENUM(NSInteger, AESType) {
    AES128 = 0,
    AES192,
    AES256
};

//AES加密实现
+ (NSString *)aesEncrypt:(NSString *)string key:(NSString *)key {
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSData * result = [self aes:data key:key mode:kCCEncrypt type:AES128];
    if (result.length == 0) {return @"";}
    NSString *resultStr = nil;
    NSData * aesData = [NSData dataWithBytes:(const void *)result.bytes length:result.length];
    NSData *tmpData = [aesData base64EncodedDataWithOptions:0];
    resultStr = [[NSString alloc] initWithData:tmpData encoding:NSUTF8StringEncoding];;
    if (resultStr.length == 0) {return @"";}
    return resultStr;
}
//AES解密
+ (NSString *)aesDecrypt:(NSString *)string key:(NSString *)key {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSData* result = [self aes:data key:key mode:kCCDecrypt type:AES128];
    NSString * resultStr = nil;
    if (result.length == 0) {return @"";}
    resultStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    if (resultStr.length == 0) {return @"";}
    return resultStr;
}
//加解密算法实现
+ (NSData *)aes:(NSData *)data key:(NSString *)key mode:(CCOperation)operation type:(AESType)type {
    NSInteger size;
    switch (type) {
        case AES128:
            size = kCCKeySizeAES128;
            break;
        case AES192: {
            size = kCCKeySizeAES192;
        }
            break;
        case AES256: {
            size = kCCKeySizeAES256;
        }
            break;
        default:
            size = kCCKeySizeAES128;
            break;
    }
    char keyPtr[size + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = data.length;
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void * buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    NSString * initIv = [self iv];
    char ivPtr[size + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [initIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    NSData * result;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          size,
                                          ivPtr,
                                          data.bytes,
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        result = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        return result;

    } else {
        free(buffer);
        return nil;
    }
}

//偏移量
+ (NSString *)iv {
    if (self.aesType == AES128) {
        return @"8841054029634287";
    }
    if (self.aesType == AES192) {
        return @"884105402963428788410540";
    }
    if (self.aesType == AES256) {
        return @"88410540296342878841054029634287";
    }
    return @"";
}

源码下载链接

2016-02-24 13:40:49 Leemin_ios 阅读数 562


NSData+AES.h

//
//  NSData+AES.h
//  Smile
//
//  Created by 李 敏 on 14-11-24.
//  Copyright (c) 2014年 BOX. All rights reserved.
//

#import <Foundation/Foundation.h>

@class NSString;

@interface NSData (Encryption)


- (NSData *)AES256EncryptWithStrKey:(NSString *)key;
- (NSData *)AES256EncryptWithKey:(NSData *)data;   //加密
- (NSData *)AES256DecryptWithKey:(NSString *)key;   //解密

- (NSString *)newStringInBase64FromData;            //追加64编码

+ (NSString*)base64encode:(NSString*)str;           //同上64编码



//加密
- (NSData *)AES128EncryptWithStrKey:(NSString *)key iv:(NSString *)iv;
//解密
- (NSData *)AES128DecryptWithStrKey:(NSString *)key iv:(NSString *)iv;
@end
NSData+AES.m
//
//  NSData+AES.m
//  Smile
//
//  Created by 李 敏 on 14-11-24.
//  Copyright (c) 2014年 BOX. All rights reserved.
//

#import "NSData+AES.h"
#import <CommonCrypto/CommonCryptor.h>
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@implementation NSData (Encryption)

- (NSData *)AES256EncryptWithKey:(NSData *)data {//加密
    //    char keyPtr[kCCKeySizeAES256+1];
    //    bzero(keyPtr, sizeof(keyPtr));
    //    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    memcpy(&keyPtr, [data bytes], 16);
    
    
    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 *)AES256EncryptWithStrKey:(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;
}

- (NSString *)newStringInBase64FromData            //追加64编码
{
    
    NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
    
    unsigned char * working = (unsigned char *)[self bytes];
    
    int srcLen = [self length];
    
    for (int i=0; i<srcLen; i += 3) {
        
        for (int nib=0; nib<4; nib++) {
            
            int byt = (nib == 0)?0:nib-1;
            
            int ix = (nib+1)*2;
            
            if (i+byt >= srcLen) break;
            
            unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
            
            if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
            
            [dest appendFormat:@"%c", base64[curr]];
            
        }
        
    }
    
    return dest;
    
}

+ (NSString*)base64encode:(NSString*)str
{
    
    if ([str length] == 0)
        
        return @"";
    
    const char *source = [str UTF8String];
    
    int strlength  = strlen(source);
    
    char *characters = malloc(((strlength + 2) / 3) * 4);
    
    if (characters == NULL)
        
        return nil;
    
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    
    while (i < strlength) {
        
        char buffer[3] = {0,0,0};
        
        short bufferLength = 0;
        
        while (bufferLength < 3 && i < strlength)
            
            buffer[bufferLength++] = source[i++];
        
        characters[length++] = base64[(buffer[0] & 0xFC) >> 2];
        
        characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        
        if (bufferLength > 1)
            
            characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        
        else characters[length++] = '=';
        
        if (bufferLength > 2)
            
            characters[length++] = base64[buffer[2] & 0x3F];
        
        else characters[length++] = '=';
        
    }
    
    NSString *g = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
    
    return g;
    
}

//加密
- (NSData *)AES128EncryptWithStrKey:(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(kCCEncrypt,
                                          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 *)AES128DecryptWithStrKey:(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(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
    }
    free(buffer);
    return nil;
}
@end

使用:

#define DecodeOrEncode_Key 	@"www.limin.haoren" //加密解密用的Key
#define gIv             @"www.baidulou.com" //自行修改16位

需要加密的二进制数据comData。

//AES加密
    NSData *resultData = [comData AES128EncryptWithStrKey:DecodeOrEncode_Key iv:gIv];



2018-03-29 17:35:00 weixin_33802505 阅读数 4

心急的童鞋直接看这里Demo
运行之后可以去在线加密网站验证

AES(Advanced Encryption Standard)高级加密标准,又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES

AES的五种加密模式

AES有五种加密模式(CBC、ECB、CTR、OCF、CFB)
1.电码本模式(Electronic Codebook Book (ECB)
2.密码分组链接模式(Cipher Block Chaining (CBC))
3.计算器模式(Counter (CTR))
4.密码反馈模式(Cipher FeedBack (CFB))
5.输出反馈模式(Output FeedBack (OFB))

在iOS用到的一般就是ECB和CBC两种。

ECB-电码本模式

ECB是最简单的块密码加密模式,加密前根据加密块大小(AES加密块固定为128位)分成若干块,之后将每块使用相同的密钥单独加密,所以加密块相同的明文会生成相同的密文。

CBC-密码分组链接模式

CBC模式对于每个待加密的密码块在加密前会先与前一个密码块的密文异或然后再用加密器加密。第一个明文块与一个叫初始化向量的数据块异或。

OK,最简单的理论理解了,就来看iOS最重要的干货:加解密函数CCCrypt

CCCrypt - 加解密函数

CCCryptorStatus CCCrypt(
    CCOperation op,         /* kCCEncrypt, etc. */
    CCAlgorithm alg,        /* kCCAlgorithmAES128, etc. */
    CCOptions options,      /* kCCOptionPKCS7Padding, etc. */
    const void *key,
    size_t keyLength,
    const void *iv,         /* optional initialization vector */
    const void *dataIn,     /* optional per op and alg */
    size_t dataInLength,
    void *dataOut,          /* data RETURNED here */
    size_t dataOutAvailable,
    size_t *dataOutMoved)

重要的参数说明:

  1. CCOperation op:加密kCCEncrypt,解密kCCDecrypt
  2. CCAlgorithm alg:加密算法,这里kCCAlgorithmAES128和kCCAlgorithmAES是一样的,AES加密块固定是128位,咱们常说的AES128、192、256加密只是加密秘钥的长度不同(当然加密处理轮数也不同,这里就不做说明了)
  3. CCOptions options:
    kCCOptionPKCS7Padding:填充模式
    kCCOptionECBMode:ECB模式
  4. size_t keyLength:参数是下面这些,看到很多博客不管是128还是256,这里都写kCCBlockSizeAES128,这是不对的,这样加密出来的其实还是128加密
enum {
    kCCKeySizeAES128          = 16,
    kCCKeySizeAES192          = 24,
    kCCKeySizeAES256          = 32,
    kCCKeySizeDES             = 8,
    kCCKeySize3DES            = 24,
    kCCKeySizeMinCAST         = 5,
    kCCKeySizeMaxCAST         = 16,
    kCCKeySizeMinRC4          = 1,
    kCCKeySizeMaxRC4          = 512,
    kCCKeySizeMinRC2          = 1,
    kCCKeySizeMaxRC2          = 128,
    kCCKeySizeMinBlowfish     = 8,
    kCCKeySizeMaxBlowfish     = 56,
};
  1. iv:偏移向量,CBC模式下需要,不传默认16位0,ECB不需要
关于CCCrypt中的key和keyLength

AES数据块长度为128位,所以IV长度需要为16个字符(ECB模式不用IV),密钥根据指定密钥位数分别为16、24、32个字符,IV与密钥超过长度则截取,不足则在末尾填充'\0'补足

key和keyLength之间的关系,现在算是搞明白了,key就是咱们传入的密钥,keyLength是决定密钥长度的,也就是aes128,192,256的真正区别了,如果传入的key是32位,也就是256要求的位数,但是keyLength选择了kCCKeySizeAES128,那么真正的key其实是截取前面的16位,如果key传入16位,但是keyLength选择了kCCKeySizeAES256,那就是密钥位数不够,会自动补全到32位
虽然密钥长度不够的话会自动补齐或者截取,不过感觉还是传入正确的密钥比较好,128的keysize=16,192keysize=24,256keysize=32

好了,直接上代码

翠花,上酸菜~

Demo
需要引入 #import <CommonCrypto/CommonCrypto.h>

AES256 ECB模式加密

+(NSData *)dataByAes256ECB:(NSData *)data key:(NSString *)key mode:(CCOperation)operation {
    char keyPtr[kCCKeySizeAES256 + 1];//选择aes256加密,所以key长度应该是kCCKeySizeAES256,32位
    bzero(keyPtr, sizeof(keyPtr));//清零
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];//秘钥key转成cString
    
    NSUInteger dataLength = data.length;
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    
    void * buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,//ECB模式
                                          keyPtr,
                                          kCCKeySizeAES256,
                                          NULL,//选择ECB模式,不需要向量
                                          data.bytes,
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData * result = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        return result;
    }
    free(buffer);
    return nil;
}

AES128 CBC模式加解密

+(NSData *)dataByAes128CBC:(NSData *)data key:(NSString *)key mode:(CCOperation)operation iv:(NSString *)iv {
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = data.length;
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void * buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    
    NSString * initIv = iv;
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [initIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCKeySizeAES128,
                                          ivPtr,
                                          data.bytes,
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData * result = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        return result;
    }
    free(buffer);
    return nil;
}

在线验证

2015-04-06 17:48:41 yangchen9931 阅读数 376

AES   GitHub 下载地址  https://github.com/Gurpartap/AESCrypt-ObjC


官方文档


Add this line to your class:

#import "AESCrypt.h"

Usage

NSString *message = @"top secret message";  // message 为加密字符串 与密码混合加密
    NSString *password = @"p4ssw0rd";           // passwprd 为用户输入的密码

Encrypting

NSString *encryptedData = [AESCrypt encrypt:message password:password];  //加密

Decrypting

NSString *message = [AESCrypt decrypt:encryptedData password:password];   解密

之后我么可以通过  

NSUserDefaults * saveUserMessageDefaults = [NSUserDefaults standardUserDefaults]


iOS AES 256加密

阅读数 401

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