(更新了代码,删除padding参数,修改了IV校验)
文章里介绍了不同加密模式下参数的限制条件,源码里也包含了条件判断,以帮助大家理解CommonCrypto的使用
此加解密工具包含了:
对NSData的AES,DES,3DES,BLOWFISH加密解密方法。
以及对NSData和NSString的MD5,SHA1,SHA2的计算。
主要依赖于 CommonCrypto 库,本工具并未包含所有加密方法(如:RC4,RC2,CAST)。
BuffKit源码及Demo地址:
https://github.com/FlashHand/BuffKit/tree/master/BuffKit/CryptoBuff
https://github.com/FlashHand/BuffKit
以Blowfish加解密为例子:
NSString *sourceStr=@"12345678901234561";
NSData *source=[sourceStr dataUsingEncoding:NSUTF8StringEncoding];
[source bfCryptoBlowfishEncodeWithMode:BuffCryptoModeCFB8 iv:@"1234567812345678" key:@"1234567812345678" completion:^(NSData *cryptoData) {
[cryptoData bfCryptoBlowfishDecodeWithMode:BuffCryptoModeCFB8 iv:@"1234567812345678" key:@"1234567812345678" completion:^(NSData *cryptoData2) {
NSString *result = [[NSString alloc] initWithData: cryptoData2 encoding: NSUTF8StringEncoding];
NSLog(@"%@",result);
}];
上面包含了encode和decode过程。
打印结果为:12345678901234561
参数详细说明:
BuffCryptoMode 为加密模式,支持的加密模式有
typedef NS_ENUM(NSInteger, BuffCryptoMode) {
BuffCryptoModeECB = 1,//kCCModeECB
BuffCryptoModeCBC = 2,//kCCModeCBC
BuffCryptoModeCFB = 3,//kCCModeCFB
BuffCryptoModeCTR = 4,//kCCModeCTR
BuffCryptoModeOFB = 7,//kCCModeOFB
BuffCryptoModeCFB8 = 10,//kCCModeCFB8
};
并不推荐使用ECB,因为安全性较差。下图表明了,如果对一个位图进行AES-ECB加密甚至会保留原图的一些特征。
iv 为初始化偏移量(initialization vector)ECB下填写会被忽略,
注意iv的length在AES加密时下是16,否则是8,iv的size必须和cypher block size 一致,iv官方注释:
/*
iv Initialization vector, optional. Used for
Cipher Block Chaining (CBC) mode. If present,
must be the same length as the selected
algorithm's block size. If CBC mode is
selected (by the absence of any mode bits in
the options flags) and no IV is present, a
NULL (all zeroes) IV will be used. This is
ignored if ECB mode is used or if a stream
cipher algorithm is selected.
*/
/*!
@enum Block sizes
@discussion Block sizes, in bytes, for supported algorithms.
@constant kCCBlockSizeAES128 AES block size (currently, only 128-bit
blocks are supported).
@constant kCCBlockSizeDES DES block size.
@constant kCCBlockSize3DES Triple DES block size.
@constant kCCBlockSizeCAST CAST block size.
*/
enum {
/* AES */
kCCBlockSizeAES128 = 16,
/* DES */
kCCBlockSizeDES = 8,
/* 3DES */
kCCBlockSize3DES = 8,
/* CAST */
kCCBlockSizeCAST = 8,
kCCBlockSizeRC2 = 8,
kCCBlockSizeBlowfish = 8,
};
key 是密钥,AES加密时key的长度必须是16,24,32其中一个,
DES加密时是8,3DES加密时是24,
blowfish加密时key的长度可以是整数区间[8,56]中的任意一个.
加密过程是在GLOBAL_QUEUE里执行的,completion block是异步回调,
block传入一个NSData类的参数cryptoData,加密或解密失败时cryptoData=nil.
<h3 id="1">关于padding</h3>
注意:在ECB或CBC情况下,当原文长度无法被key.length整除时,会对原内容进行补位(padding),默认用PKCS7Padding,否则加密就会失败,补位方法如下:
while (sourceM.length % key.length != 0) {
int pad = 0x07;
NSData *padData = [[NSData alloc] initWithBytes:&pad length:1];
[sourceM appendData:padData];
}
在CFB,CTR,OFB,CFB8下无需padding,因为密文和原文大小是一样的,具体参考可参考http://www.di-mgt.com.au/cryptopad.html
若需要自定义实现或了解实现方式可以看源码
https://github.com/FlashHand/BuffKit
如果你有任何问题,欢迎通过简书留言:)