dart Flutter中的加密和java中的解密(AES-256)

mbzjlibv  于 2023-02-20  发布在  Flutter
关注(0)|答案(2)|浏览(526)

我尝试在Flutter中实现加密,我使用java作为后端和dart用于移动的应用程序。我已经从这个Encryption in Java and Decryption in Flutter (AES-256)中获取了代码,但它只在Flutter中提供解密,我想在Flutter中实现加密,以便Java代码可以解密它。
你能帮我提供Flutter的加密代码吗?
这是加密和解密的java代码。

public class EncryptionService {
    public String encrypt(String item) throws Exception {
        byte[] ivBytes;
        String password = "Hello";
        /* you can give whatever you want for password. This is for testing purpose */
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        byte[] saltBytes = bytes;
        // Derive the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);

        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        System.out.println("saltBytes : " + saltBytes);

        // encrypting the word
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
        System.out.println("ivBytes : " + ivBytes);

        byte[] encryptedTextBytes = cipher.doFinal(item.getBytes("UTF-8"));
        // prepend salt and vi
        byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
        System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
        System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
        System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
        return new Base64().encodeToString(buffer);
    }

    public String decrypt(String encryptedText) throws Exception {
        String password = "Hello";
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // strip off the salt and iv
        ByteBuffer buffer = ByteBuffer.wrap(new Base64().decode(encryptedText));
        byte[] saltBytes = new byte[20];
        buffer.get(saltBytes, 0, saltBytes.length);
        byte[] ivBytes1 = new byte[cipher.getBlockSize()];
        buffer.get(ivBytes1, 0, ivBytes1.length);
        byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];

        buffer.get(encryptedTextBytes);
        // Deriving the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return new String(decryptedTextBytes);
    }
}

解密的Dart实现如下所示

class EncryptionHelper {
  static String decrypt(
    String ciphertext,
  ) {
    Uint8List ciphertextlist = base64.decode(ciphertext);
    var salt = ciphertextlist.sublist(0, 20);
    var iv = ciphertextlist.sublist(20, 20 + 16);
    var encrypted = ciphertextlist.sublist(20 + 16);

    Uint8List key = generateKey("Hello", salt);
    CBCBlockCipher cipher = new CBCBlockCipher(new AESFastEngine());

    ParametersWithIV<KeyParameter> params =
        new ParametersWithIV<KeyParameter>(new KeyParameter(key), iv);

    PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null>
        paddingParams =
        new PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null>(
            params, null);
    PaddedBlockCipherImpl paddingCipher =
        new PaddedBlockCipherImpl(new PKCS7Padding(), cipher);
    paddingCipher.init(false, paddingParams);
    var val = paddingCipher.process(encrypted);

    return new String.fromCharCodes(val);
  }

  static Uint8List generateKey(String passphrase, Uint8List salt) {
    Uint8List passphraseInt8List = Uint8List.fromList(passphrase.codeUnits);

    KeyDerivator derivator =
        PBKDF2KeyDerivator(HMac(SHA1Digest(), 64)); // 64 byte block size
    Pbkdf2Parameters params =
        Pbkdf2Parameters(salt, 65556, 32); // 32 byte key size
    derivator.init(params);
    return derivator.process(passphraseInt8List);
  }
}
3gtaxfhh

3gtaxfhh1#

你为什么不使用pointcastle呢?它是弹跳城堡的一个dart移植,正如我在他们的页面上读到的,还没有实现AES算法的解密/加密。
此外,用途:
https://pub.dev/packages/encrypt
这是一个方便的 Package 上点城堡。

yzuktlbb

yzuktlbb2#

我写了java和dart一起工作使用AES CBC模式PKCS 5填充注意Java中的PKCS 5等效于Dart中的PKCS 7-它们一起工作您可以在java中加密和在Dart中解密,反之亦然此Java部分

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/*********this class to Encrypt and decrypt data used in sending and receiving  data**** */

public class Encryptor {

    static Encryptor instance = null;

    private Encryptor(){
        instance=this;
    }

    final static String AccKey = "ShaniaTwain2023f";
       
    public static void main(String[] args)  throws Exception{
        //() TODO Auto-generated method stub
         
          String originalString = "I like Shaina Twain Songs";
          
          byte[] ecryptedString =Encryptor.getInstance().encrypt(Encryptor.AccKey, originalString);
          String decryptedString = Encryptor.getInstance().decrypt(new String(ecryptedString) , Encryptor.AccKey) ;    
        }
     public    byte[]  encrypt (String key, String value) {
         
             String encryptString = "";
             byte[] keyBytes = new byte[16];
        
           try {
              Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //1
               SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");//2
               IvParameterSpec ivSpec = new IvParameterSpec(keyBytes); //3
               cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); //4
                encryptString = Base64.getEncoder().encodeToString(cipher.doFinal(value.getBytes("UTF-8")));//5
           
           } catch (Exception e) {
               e.printStackTrace();
           }
           return encryptString.getBytes();
            }
        public   String decrypt (String encrypted , String Key) {
            byte[] keyBytes = new byte[16];//1
            
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");//1
                SecretKeySpec skeySpec = new SecretKeySpec(Key.getBytes("UTF-8"), "AES");//2
                IvParameterSpec iv = new IvParameterSpec(keyBytes);//3
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);//4
                byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));//5
                    return new String(original);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                return null;
        }
        public static Encryptor getInstance() {
            // TODO Auto-generated method stub
            if (instance==null) {
                return new Encryptor();
            }else {
                return instance;
            }
        }
}

此Dart部件使用加密5.0.1

import 'dart:typed_data';
import 'package:encrypt/encrypt.dart' as ency;
import 'package:flutter/material.dart';

 
class Encryptor_ {
  static final key = ency.Key.fromUtf8('ShaniaTwain2023f');
  static final iv = ency.IV.fromLength(16);
  static final encrypter =
      ency.Encrypter(ency.AES(key, mode: ency.AESMode.cbc, padding: 'PKCS7'));

  static String encrypt(plainText) {
    return encrypter.encrypt(plainText, iv: iv).base64.toString();
  }

  static String decrypt(plainText) {
    ency.Encrypted encrypted = ency.Encrypted.from64(plainText);
    return encrypter.decrypt(encrypted, iv: iv).toString();
  }
}

void main() {
  print(Encryptor_.encrypt("Hassan"));
}

相关问题