Skip to content
Advertisement

Plain text encrypt from Dart code but decrypt from Java code

When I encrypt plain text using Dart,and encrypted text is decrypted from Java code, I get this error:

JavaScript

Same IV, salt and passphase value using Java side for key generation, but the generated key is different and also cipher test is different. I am using same method for key generation. I don’t know what is missing in Dart code.

JavaScript

Dart code is:

JavaScript

And Java code is:

JavaScript

Encryption code in Java:

JavaScript

Advertisement

Answer

The decryption fails because in both codes different salts are used and therefore different keys are generated. Ultimately, this is due to an inappropriate design of the PBKDF2 implementation of the password_hash_plus Dart library.

In the Java code a random salt is applied, in this case 0xb9266c74df614967d9acaa2878bff87c. In main(), the salt is passed hex encoded to encrypt(), hex decoded in generateKey(), and the resulting byte sequence is used for key derivation.

The generateBase64Key() method of the password_hash_plus library, on the other hand, expects the salt as string and does a UTF-8 encoding internally, see here. Therefore, only salts that are UTF-8 decodable can be processed. This is generally not true for random salts, since these are corrupted by a UTF-8 decoding.
The hex encoding of the salt applied in the Dart code does not work either, of course, because generateBase64Key() does not perform a hex decoding internally but a UTF-8 encoding.

Since salts are generally random byte sequences, the design of the PBKDF2 implementation of the password_hash_plus library is unsuitable. Instead, an implementation is required where the salt is passed as byte sequence (Uint8List or List<int>), e.g. the PBKDF2 implementation of PointyCastle:

JavaScript

The Dart code returns salt and IV hex encoded and the ciphertext Base64 encoded. If this data is passed with these encodings to the decrypt() method of the Java code, decryption is successful.

Be aware that an iteration count of 1000 is generally too small for PBKDF2.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement