AES实现文件加密

公司需要自己课件,讲义等文件只能由自己的app打开,不能够由别的工具打开,防止盗版。主要是pdf

无论是音频,视频,文本文件,本质只不过是一堆二进制数据,之所以能够被播放和阅读,是因为这些二进制数据都按照有自己特定的格式组合了数据,相应的软件可以根据约定好的格式去解析里面的数据然后呈现出相应的结果。

pdf结构格式介绍参考:
http://blog.csdn.net/pdfmaker/article/details/573990
同时可以使用工具PDFStreamDumper查看对应的结构。根据里面的结构依次读取二进制文件信息结合pdf协议就可以制作pdf阅读器,但是这应该不是一个简单的事情。pdf文件是支持设定密码的,但是这里的需求不是用pdf自带的密码机制,而是希望对文件进行加密。可以参考http://blog.csdn.net/pdfMaker/article/details/576210 在pdf格式的基础上增加字段自定义自己的格式,但是有点复杂,而且文中所介绍的pdf加密主要是对于普通用户设置密码和这里需求也不太一样,如果这样需要实现用户口令验证算法和pdf加密算法。这两个算法需要自己设计,而且不能太简单,因为pdf文件格式不像视频那样复杂,所有的密码信息都再文本中,过于简单容易破解。而且课件还可能是ppt,如果用这样的办法加密ppt文件是不可行的。所有考虑到应该对整个文件进行加密。使用AES加密算法,下面的是AES算法是aes/ecb/pck5padding+base64

php 端

案例

header("Content-type: text/html; charset=utf-8");
require_once 'aes.php';
$content = file_get_contents('group.pdf');
$aes = new Security('1234567812345678', '');//密码长度16位
$res = $aes->encrypt($content);
file_put_contents('encrypt_pdf.pdf', $res);

php 加密类

class Security {

    private $key = null;
    private $signKey = null;
    /**
     *
     * @param $key      密钥
     * @return String
     */
    public function __construct($key = null, $signKey = null) {

        if(is_null($key)) {
            throw new \Exception('set sccret key please.');
        }
        if(is_null($signKey)) {
            throw new \Exception('set sign key please.');
        }
        $this->key = $key;
        $this->signKey = $signKey;

    }
    /**
     * 加密
     * @param String input 加密的字符串
     * @param String key   解密的key
     * @return HexString
     */
    public function encrypt($input) {

        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = $this->pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $this->key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = base64_encode($data);
        return $data;

    }
    /**
     * 填充方式 pkcs5
     * @param String text        原始字符串
     * @param String blocksize   加密长度
     * @return String
     */
    private function pkcs5_pad($text, $blocksize) {

        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);

    }

    /**
     * 解密
     * @param String input 解密的字符串
     * @param String key   解密的key
     * @return String
     */
    public function decrypt($sStr) {

        $decrypted= mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$this->key,base64_decode($sStr), MCRYPT_MODE_ECB);
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
}

iOS客户端

使用了Reader 库:https://github.com/vfr/Reader,这是一个非常强大的开源pdf阅读器。经过研究发现系统加载pdf文件可以通过二进制也可以通过文本路径,所有我们可以以二进制的方式读取文件,先得到二进制数据,然后对NSData进行解密后交给Reader库处理。通过观察可以发现该库判断一个文件是不是pdf就是根据pdf文件格式的前面部分是否包含pdf版本信息来确定的,加密后的文件是不会包含这些信息的,所以这可以作为是否加密的依据,这样就可以同时打开加密的和不加密文件了。

更改 ReadContentPage.m 文件

    - (instancetype)initWithURL:(NSURL *)fileURL page:(NSInteger)page password:(NSString *)phrase
_PDFDocRef = CGPDFDocumentCreateUsingUrl((__bridge CFURLRef)fileURL, phrase);
        
        if (!_PDFDocRef) {
            NSData * data =  [NSData dataWithContentsOfURL:fileURL]; // CFURLRef from NSURL
            NSString *base64Encoded = [[NSString alloc]
                                       initWithData:data encoding:NSUTF8StringEncoding];
            data = [[NSData alloc]
                    initWithBase64EncodedString:base64Encoded options:0];
            data = [data AES256_Decrypt:@"1234567812345678"];;
            
            _PDFDocRef  = CGPDFDocumentCreateUsingData(CGDataProviderCreateWithCFData((CFDataRef)data), phrase);
        }

更改 ReaderDocument.m

- (instancetype)initWithFilePath:(NSString *)filePath password:(NSString *)phrase {
        if ([ReaderDocument isPDF:filePath] == YES) {
            CFURLRef docURLRef = (__bridge CFURLRef)[self fileURL]; // CFURLRef from NSURL
            thePDFDocRef = CGPDFDocumentCreateUsingUrl(docURLRef, _password);
        } else {
            NSData * data =  [NSData dataWithContentsOfFile:filePath]; // CFURLRef from NSURL
            NSString *base64Encoded = [[NSString alloc]
                                       initWithData:data encoding:NSUTF8StringEncoding];
            data = [[NSData alloc]
                    initWithBase64EncodedString:base64Encoded options:0];
            data = [data AES256_Decrypt:@"1234567812345678"];;
            thePDFDocRef  = CGPDFDocumentCreateUsingData(            CGDataProviderCreateWithCFData((CFDataRef)data), _password);
        }
}

iOS客户端加密代码 :

@interface NSString (AES)

- (NSString *) AES256_Encrypt:(NSString *)key;

 - (NSString *) AES256_Decrypt:(NSString *)key;

- (NSString *)stringFromByte:(Byte)byteVal;
- (NSString *)hexStringFromData:(NSData *)data;

@end

//
//  NSString+AES.m
//  UIImage+PDF example
//
//  Created by Me on 17/7/2.
//
//

#import "NSString+AES.h"
#import "NSData+AES.h"

@implementation NSString (AES)
- (NSString *) AES256_Encrypt:(NSString *)key{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    //对数据进行加密
    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;
}

- (NSString *)stringFromByte:(Byte)byteVal
{
    NSMutableString *str = [NSMutableString string];
    
    //取高四位
    Byte byte1 = byteVal>>4;
    //取低四位
    Byte byte2 = byteVal & 0xf;
    //拼接16进制字符串
    [str appendFormat:@"%x",byte1];
    [str appendFormat:@"%x",byte2];
    return str;
}

- (NSString *)hexStringFromData:(NSData *)data
{
    NSMutableString *str = [NSMutableString string];
    Byte *byte = (Byte *)[data bytes];
    for (int i = 0; i<[data length]; i++) {
        // byte+i为指针
        [str appendString:[self stringFromByte:*(byte+i)]];
    }
    return str;
}
@end

//
//  NSData+AES.h
//  UIImage+PDF example
//
//  Created by Me on 17/7/2.
//
//

#import 
#import 
#import 

@interface NSData (AES)

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

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

- (NSString *)newStringInBase64FromData;

+(NSString*)base64encode:(NSString*)str;

- (NSData *)dataFromHexString:(NSString *)hexStr;
@end

//
//  NSData+AES.m
//  UIImage+PDF example
//
//  Created by 王国栋 on 17/7/2.
//
//

#import "NSData+AES.h"

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation NSData (AES)
- (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;
}

- (NSString *)newStringInBase64FromData
{
    NSMutableString *dest = [[NSMutableString alloc] initWithString:@""]; 
    unsigned char * working = (unsigned char *)[self bytes];
    int srcLen = (int)[self length];
    for (int i=0; i= 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  = (int)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;
    
}
@end

算法升级

上面的是固定密钥,不安全。可以考虑每个文件一个密钥,可以由服务器记录每个文件和对应的密钥,但是麻烦。所以可以考虑到把密钥进行加密后写在文件的末尾或者头部,客户端直接从相应位置提取,根据相应的算法先解密密钥,比如可以使用RSA算法加密密钥。服务器用公钥加密,客户端保存私钥。

你可能感兴趣的:(AES实现文件加密)