1、客户端掌握公钥,服务端掌握私钥
上一篇Flutter RSA加密、解密之我见一我们了解到客户端使用公钥加密,私钥解密。那么本文我们要介绍下,客户端掌握公钥、服务端掌握私钥。客户端公钥加密,服务端私钥解密;服务端私钥加密,客户端公钥解密。
安卓可以使用java Cipher,iOS 使用Openssl这个库,对于Flutter前端来说要怎么做。
2、flutter_cipher
引入flutter_cipher这个库
flutter_cipher: ^0.0.3
3、头文件引入
import 'package:flutter_cipher/flutter_cipher.dart';
import 'package:flutter/services.dart' show rootBundle;
4、分段加密实现
static Future<String> encodeString(String content) async{
var publicKeyStr = await rootBundle.loadString('assets/data/rsa_public_key.pem');
var publicKey = RSAKeyParser().parse(publicKeyStr);
Asymmetric rsa = Cipher.getAsymmetricInstance(RSA(publicKey: publicKey));
int inputLen = content.length;
int maxLen = 117;
List<int> totalBytes = List();
for (var i = 0; i < inputLen; i += maxLen) {
int endLen = inputLen - i;
String item;
if (endLen > maxLen) {
item = content.substring(i, i + maxLen);
}
else {
item = content.substring(i, i + endLen);
}
totalBytes.addAll(rsa.encryptPublic(item).bytes);
}
return base64.encode(totalBytes);
}
5、分段解密实现
static Future<String> decodeString(String content) async{
var publicKeyStr = await rootBundle.loadString('assets/data/rsa_public_key.pem');
var publicKey = RSAKeyParser().parse(publicKeyStr);
Asymmetric rsa = Cipher.getAsymmetricInstance(RSA(publicKey: publicKey));
Uint8List sourceBytes = base64.decode(content);
int inputLen = sourceBytes.length;
int maxLen = 128;
String totalBytes = "";
print("inputLen = $inputLen");
for (var i = 0; i < inputLen; i += maxLen) {
int endLen = inputLen - i;
Uint8List item;
if (endLen > maxLen) {
item = sourceBytes.sublist(i, i + maxLen);
} else {
item = sourceBytes.sublist(i, i + endLen);
}
Encrypted en = Encrypted(item);
String s = rsa.decryptPublic(en);
totalBytes = totalBytes + s;
}
return totalBytes;
}
5、总结
通过以上步骤,我们就可以实现当服务端掌握私钥,客户端掌握公钥;
客户端公钥加密,服务端私钥解密;
服务端私钥加密,客户端公钥解密。
这个问题