Flutter 自定義插件包

前言

近期做個(gè)小demo,網(wǎng)絡(luò)請求需要用到RSAAES兩種方式加密解密,在flutter插件倉庫pub.dev上花了一兩天找了好幾個(gè)庫,但加密解密都和服務(wù)器不一致,而原始的iOS和Android、H5都已經(jīng)匹配好了服務(wù)器的加解密,于是決定自己講iOS和Android原始的加解密做成插件包提供給flutter使用

參考資料:


第一步,準(zhǔn)備工作

1.1 創(chuàng)建一個(gè)插件包
flutter create --org com.example --template=plugin hello
第二步,進(jìn)入項(xiàng)目的example目錄,并編譯,
1.2 cd hello/example
1.3 flutter build ios --no-codesign
1.4 用Xcode打開xxx/hello/example/ios/Runner.xcworkspace并運(yùn)行
運(yùn)行后的效果:

準(zhǔn)備環(huán)境就緒

TIPS:

如果不進(jìn)行上面的過程直接用Xcode打開xxx/hello/example/ios/Runner.xcworkspace會(huì)報(bào)
如下的錯(cuò)誤:[解決辦法:重新執(zhí)行1.2、1.3兩步]

error: xxxx/hello/example/ios/Flutter/Debug.xcconfig:1: could not find included file 'Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig' in search paths (in target 'Runner')

或者如下錯(cuò)誤:

error: Multiple commands produce '/Users/xxx/Library/Developer/Xcode/DerivedData/Runner-ahuwjiirmcnmaqfoqhkenntiufto/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework':

  1. Target 'Runner' has copy command from '/Users/xxx/hello/example/ios/Flutter/Flutter.framework' to '/Users/xxx/Library/Developer/Xcode/DerivedData/Runner-ahuwjiirmcnmaqfoqhkenntiufto/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework'
  2. That command depends on command in Target 'Runner': script phase “[CP] Embed Pods Frameworks”

第二步,編寫業(yè)務(wù)代碼

2.1、由于我要寫的這個(gè)RSA加解密需要用到第一第三方庫,直接將該第三方庫復(fù)制到xxx/hello/ios/Classes/GTMBase64/,結(jié)構(gòu)如下如下:
GTMBase64
RSA
iOS AES128加解密(NSDate+AES)

tmp6bfcba69.png

2.2、在xxx/hello/ios/Classes/HelloPlugin.m里編輯原生代碼

#import "HelloPlugin.h"
#import "RSA.h"
// AES
#import "GTMBase64.h"
#import "NSData+AES.h"

@implementation HelloPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"hello"
            binaryMessenger:[registrar messenger]];
  HelloPlugin* instance = [[HelloPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS sadhfas " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  }else if ([@"rsaPublicKeyEncrypt" isEqualToString:call.method]) {
      // RSA公鑰加密
      NSString *originTxt = call.arguments[@"originTxt"];
      NSString *publicKey = call.arguments[@"publicKey"];
      NSString *encryptByPublicKeyString = [RSA encryptString:originTxt publicKey:publicKey];
      result(encryptByPublicKeyString);
  }else if ([@"rsaPublicKeyDecrypt" isEqualToString:call.method]) {
      // RSA公鑰解密
      NSString *originTxt = call.arguments[@"originTxt"];
      NSString *publicKey = call.arguments[@"publicKey"];
      NSString *decryptByPublicKeyString = [RSA decryptString:originTxt publicKey:publicKey];
      result(decryptByPublicKeyString);
  }else if ([@"aesEncrypt" isEqualToString:call.method]) {
      // AES加密
      NSString *originTxt = call.arguments[@"originTxt"];
      NSString *aesKey = call.arguments[@"aesKey"];
      NSString *aesIV = call.arguments[@"aesIV"];
      NSData *data1 = [originTxt dataUsingEncoding:NSUTF8StringEncoding];
      NSData *data2 = [data1 AES128EncryptWithKey:aesKey iv:aesIV];
      NSData *data3 = [GTMBase64 encodeData:data2];
      NSString *encryptString = [[NSString alloc] initWithData:data3 encoding:NSUTF8StringEncoding];
      result(encryptString);
  }else if ([@"aesDecrypt" isEqualToString:call.method]) {
      // AES解密
      NSString *originTxt = call.arguments[@"originTxt"];
      NSString *aesKey = call.arguments[@"aesKey"];
      NSString *aesIV = call.arguments[@"aesIV"];
      NSData *data = [originTxt dataUsingEncoding:NSUTF8StringEncoding];
      data = [GTMBase64 decodeData:data];
      NSData *data5 = [data AES128DecryptWithKey:aesKey iv:aesIV];
      NSString *decryptString = [[NSString alloc] initWithData:data5 encoding:NSUTF8StringEncoding];
      result(decryptString);
  } else {
    result(FlutterMethodNotImplemented);
  }
}

@end

NSDate+AES.h

#import <Foundation/Foundation.h>

@interface NSData (AES)
//加密
- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv;
//解密
- (NSData *)AES128DecryptWithKey:(NSString *)key iv:(NSString *)iv;
@end

NSDate+AES.m

#import "NSData+AES.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (AES)

//加密
- (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];
}

- (NSData *)AES128operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    // IV
    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    size_t bufferSize = [self length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
    
    CCCryptorStatus cryptorStatus = CCCrypt(operation, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                            keyPtr, kCCKeySizeAES128,
                                            ivPtr,
                                            [self bytes], [self length],
                                            buffer, bufferSize,
                                            &numBytesEncrypted);
    
    if(cryptorStatus == kCCSuccess){
        NSLog(@"Success");
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        
    }else{
        NSLog(@"Error");
    }
    
    free(buffer);
    return nil;
}
@end

2.4、寫flutter里的API方法xxx/hello/lib/hello.dart

import 'dart:async';

import 'package:flutter/services.dart';

class Hello {
  static const MethodChannel _channel =
      const MethodChannel('hello');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  /**
   * RSA公鑰加密
   * originTxt: 需要加密的文本
   * publicKey: 公鑰字符串
   */
  static Future<String> rsaPublicKeyEncrypt(String originTxt,String publicKey) async{
     var params = {'originTxt':originTxt,'publicKey':publicKey};
     String encryptTxt = await _channel.invokeMethod('rsaPublicKeyEncrypt',params);
    return encryptTxt;
  }
  /**
   * RSA公鑰解密
   * originTxt: 需要解密的文本
   * publicKey: 公鑰字符串
   */
  static Future<String> rsaPublicKeyDecrypt(String originTxt,String publicKey) async{
     var params = {'originTxt':originTxt,'publicKey':publicKey};
     String decryptTxt = await _channel.invokeMethod('rsaPublicKeyDecrypt',params);
    return decryptTxt;
  }
  /**
   * AES加密
   * originTxt: 需要解密的文本
   * aesKey AES秘鑰
   * aseIV AES解密IV
   */
  static Future<String> aesEncrypt(String originTxt,String aesKey,String aesIV) async{
     var params = {'originTxt':originTxt,'aesKey':aesKey,'aesIV':aesIV};
     String encryptTxt = await _channel.invokeMethod('aesEncrypt',params);
    return encryptTxt;
  }
  /**
   * AES解密
   * originTxt: 需要解密的文本
   * aesKey AES秘鑰
   * aseIV AES解密IV
   */
  static Future<String> aesDecrypt(String originTxt,String aesKey,String aesIV) async{
     var params = {'originTxt':originTxt,'aesKey':aesKey,'aesIV':aesIV};
     String decryptTxt = await _channel.invokeMethod('aesDecrypt',params);
    return decryptTxt;
  }
}

2.4 添加公鑰和私鑰文件用來測試
/Users/xxx/hello/example/assets/keys/public_key.pem
/Users/xxx/hello/example/assets/keys/private_key.pem

2.5 在xxx/hello/example/lib/main.dart里寫代碼測試運(yùn)行效果

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:hello/hello.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _originTxt =  'Hello 中文 12345 {name:小名}';
  String _rsaEncrypt;
  String _rsaDecrypt;
  String _aesEncrypt;
  String _aesDecrypt;

  @override
  void initState() {
    super.initState();
    initPlatformState();
    rsaDemo();
    aesDemo();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await Hello.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }
  // RSA公鑰加解密
  Future<void> rsaDemo() async {
    // 獲取到公鑰的文本
    String publicKey = await rootBundle.loadString('assets/keys/public_key.pem');
    String rsaEncryptTxt = await Hello.rsaPublicKeyEncrypt(_originTxt, publicKey);
    String rsaDecryptTxt = await Hello.rsaPublicKeyDecrypt(rsaEncryptTxt, publicKey);
    setState(() {
      _rsaEncrypt = rsaEncryptTxt;
      _rsaDecrypt = rsaDecryptTxt;
    });
  }
// AES加解密
  Future<void> aesDemo() async {
  
    String aesKey = 'xxxxxx';
    String aesIV = 'xxxxxx';
    String aesEncryptTxt = await Hello. aesEncrypt(_originTxt, aesKey,aesIV);
    String aesDecryptTxt = await Hello. aesDecrypt(aesEncryptTxt, ,aesKey,aesIV);
    setState(() {
      _aesEncrypt = aesEncryptTxt;
      _aesDecrypt = aesDecryptTxt;
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Text('Running on: $_platformVersion\n'),
            Text('originTxt on: $_originTxt\n'),
            Text('rsaEncrypt on: $_rsaEncrypt\n'),
            Text('rsaDecrypt on: $_rsaDecrypt\n'),
          ],
        )
        
      ),
    );
  }
}

第三步,將編寫的插件引入到主flutter項(xiàng)目中路徑

詳情參看【 使用 packages
依賴: 一個(gè)Flutter應(yīng)用可以依賴一個(gè)插件通過文件系統(tǒng)的path:依賴。路徑可以是相對的,也可以是絕對的。例如,要依賴位于應(yīng)用相鄰目錄中的插件’hello’,請使用以下語法

dependencies:
  hello:
    path: ../hello/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容