編者注
由於需要注重安全,則需要對關鍵信息進行加密,防止被竊取。
Dart
目錄結構
├── test
│ ├── resources
│ │ ├── rsa
│ │ │ ├── private.pem
│ │ │ └── public.pem
│ │ └── static
│ ├── rsaTest.dart
公鑰私鑰
首先計算機應當具有openssl,生成私鑰文件
openssl genrsa -out private.pem 2048
根據私鑰生成公鑰
openssl rsa -in private.pem -pubout -out public.pem
單元測試
import 'dart:convert';
import 'dart:io';
import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt_io.dart';
import 'package:pointycastle/asymmetric/api.dart';
void main() async {
final publicKey = await parseKeyFromFile<RSAPublicKey>('test/resources/rsa/public.pem');
final privKey = await parseKeyFromFile<RSAPrivateKey>('test/resources/rsa/private.pem');
final plainText = 'hello world.';
final encrypter = Encrypter(RSA(publicKey: publicKey, privateKey: privKey));
final encrypted = encrypter.encrypt(plainText);
final decrypted = encrypter.decrypt(encrypted);
print(decrypted); // Lorem ipsum dolor sit amet, consectetur adipiscing elit
print(encrypted.base64); // kO9EbgbrSwiq0EYz0aBdljHSC/rci2854Qa+nugbhKjidlezNplsEqOxR+pr1RtICZGAtv0YGevJBaRaHS17eHuj7GXo1CM3PR6pjGxrorcwR5Q7/bVEePESsimMbhHWF+AkDIX4v0CwKx9lgaTBgC8/yJKiLmQkyDCj64J3JSE=
}
flutter async
new FlatButton(
child: new Text('sra'),
color: Colors.grey[100],
onPressed: () async{
RSAPublicKey publicKey = await parseKeyFromFile<RSAPublicKey>('test/public.pem');
RSAPrivateKey privateKey= await parseKeyFromFile<RSAPrivateKey>('test/private.pem');
final plainText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
final encrypter = Encrypter(RSA(publicKey: publicKey, privateKey: privateKey));
final encrypted = encrypter.encrypt(plainText);
final decrypted = encrypter.decrypt(encrypted);
print(decrypted);
print(encrypted.bytes);
print(encrypted.base16);
print(encrypted.base64);
}),
輸出
hello world.
l7OwX2QLfzgNdAFVYVk3YNbmVPyDjD3UC/LiG76o+XVMPLr1wccW4viE/u3KDMqYOkibi4MLqd3XxlK03GJO253henrcK0MBsO7OM8t+PD0ZVY2GSfw6LudhbuNDogOzDoMYv1tFYCknHKvIyD5nRYCLSNR902/nFdQuAhlxJqtqPLifcoSzIL1zzzlvLTnjLYdJZ2Z9oS2TDS3WRk4w5hOvbcZSVxltjILO2F21msEIqRE4VN75AmevSRSejJ4b4ZxpkIcmosOhBmeqzmjU/TRewdHBQ8z8XTDjlz4CQ+HIs8Atzk4yThIfAf058dlZK1ubBKunku5I2vpaClqvRQ==