I'm trying to get TweetNaCl.js working.
My problem is that when I decrypt the data, the output is encoded wrong.
Encrypted data:
你好,世界
Decrypted data:
ä½ å¥½ï¼ä¸ç
Here is my decryption function:
Crypto.decrypt = function(key, nonce, ciphertext) {
var message, box;
try {
key = nacl.util.decodeBase64(key);
nonce = nacl.util.decodeBase64(nonce);
} catch(ex) {
alert('Error decoding');
return;
}
try {
box = nacl.util.decodeBase64(ciphertext);
} catch(ex) {
alert('Cannot decode box');
return;
}
message = nacl.secretbox.open(box, nonce, key);
if (message === false) {
alert('Failed to decrypt');
return;
}
try {
message = nacl.util.encodeUTF8(message);
console.log(message);
} catch(ex) {
alert('Cannot decode decrypted message to string');
return;
}
return message;
}
So if I encrypt the text 你好,世界
with key noIIyNy5sH61LdrmChTHW24qAFbNOv1brq9QnR9vsoE=
and with nonce XeB7tdP8CB8Y2/aybsK498gCRJz469yM
the encrypted text will be iFcrAeRqrnhu67zZupYO23UmEC0kl21Dcuo6b33gsg==
.
So now when I decrypt:
Crypto.decrypt('noIIyNy5sH61LdrmChTHW24qAFbNOv1brq9QnR9vsoE=', 'XeB7tdP8CB8Y2/aybsK498gCRJz469yM', 'iFcrAeRqrnhu67zZupYO23UmEC0kl21Dcuo6b33gsg==');
Output: ä½ å¥½ï¼ä¸ç
instead of the original input 你好,世界
.
Output is working perfectly fine in this example page: https://tweetnacl.js.org/#/secretbox but somehow my decryption function gives wrong encoding.
What am I doing wrong here?
EDIT: I made a fiddle, where the encoding is working fine... My program has a bug somewhere else then it seems. https://jsfiddle.net/user88593902/t78kb92n/
he.js library was conflicting with the TweetNaCl library. Removing it and it started to work like it should.