'How to use 15 length character key in flutter encrypt package

I'm going to use this package for encryption in the flutter application. It doesn't accept keys lower than 16 characters long. But I want to use 15 characters key in length. Because in the backend, it was used this same key for encryption and decryption. So cannot change this key. What I need to do is, encrypt a plain text using the given 15 length characters key and send it to the backend via API.

In the Java backend, the below code is used to encrypt the file.

public SecretKeySpec generateKey(String myKey){
    SecretKeySpec secretKey = null;
        byte[] key;       
        try {
            key = myKey.getBytes("UTF-8");
            key = MessageDigest.getInstance("SHA-1").digest(key);
            key = Arrays.copyOf(key, 16); 
            secretKey = new SecretKeySpec(key, "AES");
        }catch (NoSuchAlgorithmException e) {
            log.error("Error occured while generating key",e);
        } catch (UnsupportedEncodingException e) {
            log.error("Error occured while generating key",e);
        }
        return secretKey;
    }

In my flutter application, this is how I've used the above encryption package.

final key = enc.Key.fromUtf8('fifteenCharactersKey');
final iv = enc.IV.fromSecureRandom(16);
final encrypter = enc.Encrypter(
      enc.AES(key), //, mode: enc.AESMode.cbc, padding: 'PKCS7'
    );
final encrypted = encrypter.encrypt(plainText, iv: iv);

**enc is imported package {import 'package:encrypt/encrypt.dart' as enc}

Please give me an idea to generate the key with a 15 characters string.



Solution 1:[1]

Finally, I was able to find a solution. As stated in the above java code, I got a byte array with 16 lengths using the given private key string. The array is as below,

[-107, -23, -101, 71, 19, -45, -126, -59, -40, 38, -45, -85, -92, 17, -72, -81]

In flutter code, I converted extracted byte array to a Uint8List.

Uint8List x = Uint8List.fromList([-107, -23, -101, 71, 19, -45, -126, -59, -40, 38, -45, -85, -92, 17, -72, -81]);

final key = enc.Key(x);
final iv = enc.IV.fromSecureRandom(16);
final encrypter = enc.Encrypter(
  enc.AES(key,
    mode: enc.AESMode.cbc
  ),
);

final encrypted = encrypter.encrypt(plainText, iv: iv);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anjanagnet