Flutter的RSA加密(支援modules和exponent)
- 2020 年 1 月 3 日
- 筆記
因為RSA加解密,前端一般只會使用加密處理,所以只探討加密方式。
一、已知道公鑰的情況下.
已知道公鑰的情況下,進行RSA加密很簡單,網上都有文章說明。
- 首先pubspec.yaml中添加依賴:
encrypt: ^4.0.0
- 然後類似這樣程式碼:
import 'package:encrypt/encrypt.dart'; static Future<String> encrypt(String text) async { String publicKeyString = await rootBundle.loadString('keys/public_key.pem'); RSAPublicKey publicKey = parser.parse(publicKeyString); ///創建加密器 final encrypter = Encrypter(RSA(publicKey: publicKey)); return encrypter.encrypt(text).base64; }
然而開發過程中存在其它情況,如下面的:
二、通過modules和exponent來生成公鑰.
這種情況,encrypt這個庫是不支援的,然後居然在網上找不到相關文章說明。剛好某項目用到此種方式,就去看有什麼第三方庫支援的,後來發現有個這樣的庫pointycastle,就嘗試一下,居然可以!
- pubspec.yaml中添加依賴:
pointycastle: ^1.0.2
- 如下程式碼:
import 'package:pointycastle/asymmetric/api.dart'; static getPublicKey(String modules, String exponent) { var modulusInt = BigInt.parse(modules, radix: 16); var exponentInt = BigInt.parse(exponent, radix: 16); return RSAPublicKey(modulusInt, exponentInt); } static rsaEncrypt(String text, String modules) { var publicKey = getPublicKey(modules, Config.exponent); final encrypter = Encrypter(RSA(publicKey: publicKey)); final res = encrypter.encrypt(text).base64; return res; }