1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- // ignore_for_file: constant_identifier_names
- import 'dart:convert';
- import 'package:dart_des/dart_des.dart';
- import 'package:dart_sm/dart_sm.dart';
- import 'package:encrypt/encrypt.dart';
- import 'package:hex/hex.dart';
- import 'package:pointycastle/asymmetric/api.dart';
- /// JSON-RPC 加密配置
- class JsonRpcEncryptConfig {
- /// 是否启用
- final bool enable;
- /// 加密方式
- final String encryptMode;
- /// 秘钥
- final String encryptKey;
- JsonRpcEncryptConfig({
- this.enable = false,
- this.encryptMode = "sm2",
- this.encryptKey = "",
- });
- Map<String, dynamic> toJson() {
- return {
- "enable": enable,
- "encryptMode": encryptMode,
- "encryptKey": encryptKey,
- };
- }
- }
- abstract class JsonRpcEncryptUtils {
- /// RSA公钥
- static const _RSA_PUB_KEY = "-----BEGIN PUBLIC KEY-----\n"
- "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAln7CnpiqYguFVRUL5oCdFAQL6ypYQdnd84XN++mRvjkdjtpbCdGEj6S2U2Vn+Bt+vHL5bvUk6gtTx5FpV0Z8kDvDgBRweIvtJTZLx6ZjbI7habxclW9aB3b0SW3zuFuHMteDivTI0lkZ6y0QRiG7nMZYsi18IjReBssXsx38fpgIBAHIbkb98wtEffBbrbwfdxQnfc8r9Hy7iIbfVP0h7nR0FDMu1vYqi5PsnYDw681iO6GNxV6VHA6wcWkMokLZn51OP+OQmomJPElWfPgLDp1AxBeRhuHFlXslcE550bzWUs3iBylTgXwdTGqppCjCXhSLBiOnTc0ggHpDQHh17wIDAQAB\n" +
- "-----END PUBLIC KEY-----";
- /// RSA加密
- static String rsaEncrypt(String message) {
- final publicKey = RSAKeyParser().parse(_RSA_PUB_KEY) as RSAPublicKey;
- final encrypter = Encrypter(RSA(publicKey: publicKey));
- // Encrypt the message using RSA-OAEP encryption
- final encrypted = encrypter.encrypt(message);
- final encryptedText = encrypted.base64;
- return encryptedText;
- }
- /// DES解密
- static String desDecrypt(String ciphertext, String key) {
- // IV
- const List<int> iv = [1, 2, 3, 4, 5, 6, 7, 8];
- final ivHexString = String.fromCharCodes(iv);
- final ivString = utf8.encode(ivHexString);
- final DES desCBC = DES(
- key: key.codeUnits,
- mode: DESMode.CBC,
- iv: ivString,
- paddingType: DESPaddingType.PKCS7,
- );
- final ciphertextHexDecoded = HEX.decode(ciphertext);
- final decryptedBytes = desCBC.decrypt(ciphertextHexDecoded);
- final decryptedString = utf8.decode(decryptedBytes);
- return decryptedString;
- }
- /// 国密2加密
- static String sm2Encrypt(String message, String key) {
- // 1 - C1C3C2; 0 - C1C2C3; 默认为1
- const int cipherMode = 1; // 特别注意,此处前后端需保持一致
- // 加密结果
- String encryptData = SM2.encrypt(message, key, cipherMode: cipherMode);
- // 加密后的密文前需要添加04,后端才能正常解密
- encryptData = "04$encryptData";
- return encryptData;
- }
- /// 国密4解密
- static String sm4Decrypt(String cipherText, String key) {
- return SM4.decrypt(cipherText, key: key);
- }
- }
|