chemist
Applying :crypto and Jason.encode on Unicode characters
Spent quite a bit of time pondering this as I am unable to get the desired output similar to the PHP function that im trying to duplicate:
plaintext = ["<foo>","'bar'","\"baz\"","&blong&"] |> Jason.encode!
key = "secreted"
iv = "PlayerAZ"
:crypto.crypto_one_time(:des_cbc, key, iv, plaintext, [{:encrypt, :true},{:padding, :pkcs_padding}] ) |> Base.encode64
PHP:
<?php
$plaintext = json_encode(array('<foo>',"'bar'",'"baz"','&blong&'));
$key = 'secreted';
$vector = 'PlayerAZ';
$encryptedString = openssl_encrypt($plaintext, 'des-cbc', $key, OPENSSL_RAW_DATA, $vector);
echo 'Encrypted: '.$encryptedString."\n";
echo ''.$plaintext."\n";
$encryptedStringBase64 = base64_encode($encryptedString);
echo 'Encrypted + base 64:'.$encryptedStringBase64."\n";
echo 'Decrypted:'.openssl_decrypt(base64_decode($encryptedStringBase64),'des-cbc', $key, OPENSSL_RAW_DATA, $vector)."\n";
Sandbox: https://wtools.io/php-sandbox/b8Xw
In both cases: the output is the same for both: “rQnm2tysllww+bZLSwOa9UQUc0EEH3sNlu84k5o33VgbmbnHnIZx0g==”
The problem when i change the plaintext variable to include unicode character, “\xc3\xa9” as follows:
array(’’,"‘bar’",’“baz”’,’&blong&’, “\xc3\xa9” (PHP)
["","‘bar’","“baz”","&blong&","\xc3\xa9"] (Elixir)
Both function outputs diverge and no longer agree.
May I know what am i doing wrong? Thanks.
Most Liked
derek-zhou
You can normalize the unicode string in one of 2 ways: NFC or NFD:
iex(3)> :unicode.characters_to_nfc_list("\u00e9")
[233]
iex(4)> :unicode.characters_to_nfd_list("\u00e9")
[101, 769]
iex(5)> :unicode.characters_to_nfd_list("\xc3\xa9")
[101, 769]
iex(6)> :unicode.characters_to_nfc_list("\xc3\xa9")
[233]
al2o3cr
Trying out the Unicode version in that PHP sandbox shows that PHP encodes é as \u00e9 in JSON.
Jason (and the JSON standard) permits Unicode characters in strings, so they pass the character through unescaped.
You can tell Jason to escape everything but ASCII characters by passing the escape: :unicode_safe option to Jason.encode!








