iOS热修复 JSPatch 在程序中的使用

2017-01-13  本文已影响0人  Erica0708

1、选择使用cocoaPods安装##

pod 'JSPatch'

2、github下载,拖入工程目录##

地址:https://github.com/whihail/JSPatch---comment

3、使用代码##

#import "JSPatchRepair.h"
#import <JSPatch/JPEngine.h>
//密钥
NSString * const JSPatchEncryptKey = @"2017171616QWERTT";
//向量
NSString * const JSPatchEncryptIV  = @"2W3W4QQQ23242A";
@implementation JSPatchRepair
+ (void)runJSPatch{
    NSInteger v = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] integerValue];//bundle内部版本号
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];//发布版本号,3位如:1.1.0
    NSString *fileName = [NSString stringWithFormat:@"patch.%@.%ld.luac",version,(long)v];
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filepath = [docuPath stringByAppendingPathComponent:fileName];
//此处是服务器地址,我使用的是本地服务器测试
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"localhost:8080?version=%@&main.js",version]];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval:3];
        NSError *error;
        NSHTTPURLResponse *response;
        
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        
        if(!error && response.statusCode == 200)
        {
            [data writeToFile:filepath atomically:YES];
        }
        else
        {
            data = [NSData dataWithContentsOfFile:filepath];
        }
       if(data)
            {
                data = [data decryptWithKey:[JSPatchEncryptKey stringOfHexString]  iv:[JSPatchEncryptIV stringOfHexString]];
                if(!error)
                {
                    NSString *js = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
                    if(js)
                    {
                        [JPEngine startEngine];
                        [JPEngine evaluateScript:js];
                    }
                }
            }
}
- (NSString *)stringOfHexString
{
    return [[NSString alloc] initWithData:[self dataUsingHexEncoding] encoding:NSASCIIStringEncoding];
}

- (NSData *)dataUsingHexEncoding
{
    NSMutableData *stringData = [[NSMutableData alloc] init];
    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);
        [stringData appendBytes:&whole_byte length:1];
    }
    return [stringData copy];
}
/** des解密 */
- (NSData *)decryptWithKey:(NSString *)key iv:(NSString *)iv
{
    return [self crypto:kCCDecrypt key:key.UTF8String iv:iv.UTF8String];
}
/** des加密 */
- (NSData *)encryptWithKey:(NSString *)key iv:(NSString *)iv
{
    return [self crypto:kCCEncrypt key:key.UTF8String iv:iv.UTF8String];
}

- (NSData *)crypto:(CCOperation)operation  key:(const char *)key iv:(const char *)iv
{
    if(!self.length)
    {
        return nil;
    }
    
    //密文长度
    size_t size = self.length + kCCKeySizeDES;
    
    Byte *buffer = (Byte *)malloc(size * sizeof(Byte));
    
    //结果的长度
    size_t numBytes = 0;
    
    //CCCrypt函数 加密/解密
    CCCryptorStatus cryptStatus = CCCrypt(
                                          operation,//  加密/解密
                                          kCCAlgorithmDES,//  加密根据哪标准(des3desaes)
                                          kCCOptionPKCS7Padding,//  选项组密码算(des:每块组加密  3DES:每块组加三同密)
                                          key,//密钥    加密解密密钥必须致
                                          kCCKeySizeDES,//  DES 密钥(kCCKeySizeDES=8)
                                          iv,//  选初始矢量
                                          self.bytes,// 数据存储单元
                                          self.length,// 数据
                                          buffer,// 用于返数据
                                          size,
                                          &numBytes
                                          );
    
    
    NSData *result = nil;
    
    if(cryptStatus == kCCSuccess)
    {
        result = [NSData dataWithBytes:buffer length:numBytes];
    }
    
    //释放指针
    free(buffer);
    
    return result;
}

到这里使用基本就没问题了,为了避免把文件传到后台之后出现错误,可以本地测试一下,把JS文件放入到工程

//这里测试js写的是否正确
   NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"js"];
   NSString *js = [[NSString alloc] initWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil];
   if(js)
   {
       [JPEngine startEngine];
       [JPEngine evaluateScript:js];
   }

这里对写好且正确的js文件加密,然后给后台

//------- js加密---加密后给运营的
//------- js加密---加密后给运营的
   NSString *toEncptyPath = @"/Users/fuchun/Desktop/main.js";
   NSData *toEncptyData = [NSData dataWithContentsOfFile:toEncptyPath];
   NSData *encptyData = [toEncptyData encryptWithKey:[JSPatchEncryptKey stringOfHexString] iv:[JSPatchEncryptIV stringOfHexString]];
   // 写到桌面,到时候给运营上传到后台管理系统
   [encptyData writeToFile:@"/Users/用户/Desktop/main.data" atomically:YES];

这里是本地测试加密后测试能否修复,以保证给后台的到时候有效

// 测试加密是否有用
  NSString *jsFilePath = @"/Users/fuchun/Desktop/release.toService.data";
  NSData * deEncptyData = [NSData dataWithContentsOfFile:jsFilePath];
  if(deEncptyData)
  {
      deEncptyData = [deEncptyData decryptWithKey:[JSPatchEncryptKey stringOfHexString]  iv:[JSPatchEncryptIV stringOfHexString]];
      NSString *js = [[NSString alloc] initWithData:deEncptyData encoding:NSUTF8StringEncoding];
      if(js)
      {
          [JPEngine startEngine];
          [JPEngine evaluateScript:js];
      }
  }

demo地址:https://github.com/SevenTian/JSPatchRepair

上一篇下一篇

猜你喜欢

热点阅读