I am trying to encrypt some JSON with simple-crypto-js (which implements crypto-js), then deserialize the decripted text later, but no matter what I try, I always get this error when calling JSON.parse on it:
SyntaxError: Unexpected token o in JSON at position 1
Here's my code:
import SimpleCrypto from "simple-crypto-js"
var crypto = new SimpleCrypto("My key")
var testObject = { data: "cupcake" }
var stringToEncrypt = JSON.stringify(testObject);
var encryptedString = crypto.encrypt(stringToEncrypt);
console.log("Decrypted text:")
console.log(crypto.decrypt(encryptedString))
console.log();
var tries = [
["NO ENCRYPTION ",stringToEncrypt],
["(plain) ",crypto.decrypt(encryptedString)],
["as string ",crypto.decrypt(encryptedString) as string],
["toLocaleString() ",crypto.decrypt(encryptedString).toLocaleString()],
["toString() ",crypto.decrypt(encryptedString).toString()],
["toString(8) ",crypto.decrypt(encryptedString).toString(8)],
["toString(16) ",crypto.decrypt(encryptedString).toString(16)],
]
for(let aTry of tries)
{
try {
var obj = JSON.parse(aTry[1] as any);
console.log(`${aTry[0]}: SUCCESS: ${obj.data}`)
}
catch (err)
{
console.log(`${aTry[0]}: FAIL: (string: ${aTry[1]}) ${err.message}`)
}
}
... which outputs this:
Decrypted text:
{ data: 'cupcake' }
NO ENCRYPTION : SUCCESS: cupcake
(plain) : FAIL: (string: [object Object]) Unexpected token o in JSON at position 1
as string : FAIL: (string: [object Object]) Unexpected token o in JSON at position 1
toLocaleString() : FAIL: (string: [object Object]) Unexpected token o in JSON at position 1
toString() : FAIL: (string: [object Object]) Unexpected token o in JSON at position 1
toString(8) : FAIL: (string: [object Object]) Unexpected token o in JSON at position 1
toString(16) : FAIL: (string: [object Object]) Unexpected token o in JSON at position 1