Flutter - AES256加解密封装(CBC + PKCS7)

demo 地址: https://github.com/iotjin/jh_flutter_demo

aes加密使用的是 encrypt
md5使用的是 flustars
key的长度决定密文长度
除了aes另外还有base64和md5加密方法

JhEncryptUtils

/**
 *  jh_encrypt_utils.dart
 *
 *  Created by iotjin on 2020/08/18.
 *  description: base64 , aes加解密(CBC/PKCS7)
 */

import 'dart:convert';

import 'package:encrypt/encrypt.dart';
import 'package:flustars/flustars.dart';

var _KEY = "sdfg5468wwdfd542sd4asdf4sadfqd12"; 
var _IV = "0000000000000000";

//128的keysize=16,192keysize=24,256keysize=32

class JhEncryptUtils {
  //Base64编码
  static String encodeBase64(String data) {
    return base64Encode(utf8.encode(data));
  }

  //Base64解码
  static String decodeBase64(String data) {
    return String.fromCharCodes(base64Decode(data));
  }

  // md5 加密 32位小写
  static String encodeMd5(String plainText) {
    return EncryptUtil.encodeMd5(plainText);
  }

  //AES加密
  static aesEncrypt(plainText) {
    try {
      final key = Key.fromUtf8(_KEY);
      final iv = IV.fromUtf8(_IV);
      final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
      final encrypted = encrypter.encrypt(plainText, iv: iv);
      return encrypted.base64;
    } catch (err) {
      print("aes encode error:$err");
      return plainText;
    }
  }

  //AES解密
  static dynamic aesDecrypt(encrypted) {
    try {
      final key = Key.fromUtf8(_KEY);
      final iv = IV.fromUtf8(_IV);
      final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
      final decrypted = encrypter.decrypt64(encrypted, iv: iv);
      return decrypted;
    } catch (err) {
      print("aes decode error:$err");
      return encrypted;
    }
  }

调用

    var text = '123';
    print('明文:${text}');

    var base = JhEncryptUtils.encodeBase64(text);
    print('base64: ${base}');

    var enStr = JhEncryptUtils.aesEncrypt(text);
    print('AES 加密:${enStr}');
    var deStr = JhEncryptUtils.aesDecrypt(enStr);
    print('AES 解密:${deStr}');

    var md5 = JhEncryptUtils.encodeMd5(text);
    print('md5 :${md5}');

打印

flutter: 明文:123
flutter: base64: MTIz
flutter: AES 加密:jkrxORUNfAjv237qbO1o2A==
flutter: AES 解密:123
flutter: md5 :202cb962ac59075b964b07152d234b70

你可能感兴趣的:(Flutter - AES256加解密封装(CBC + PKCS7))