Reputation: 6365
What would be the best way to encode a json array into an alphanumeric string which can be used in a URL querystring?
I need something that is simple, yet not easy to crack. I've read through all the encrypt and decrypt documentation.
I need to encrypt a json array Eg: {"firstName":"John","lastName":"Doe"}
to something like a14iw58swd33s541dg2k58kv3s4gvkjsdf33s9f3
, so it can be used in a url query string like http://www.example.com/?v=a14iw58swd33s541dg2k58kv3s4gvkjsdf33s9f3
.
I'll later decrypt this server side. Since it part of a URL, I cannot have something like ȃZ Vì§n‹ØfjÒ šçæ¹ä¯
What would be an easy and safe way to do this?
Upvotes: 5
Views: 6813
Reputation: 438
If I read the question right, the solution should result in only alphanumeric characters. Base64 does not fit that requirement, as it uses 2 extra characters to encode.
As mentioned earlier, you should use any suitable encryption algorithm first, but then you need a base62 encoder and decoder. There are a few of those on the net. Here is one: https://gist.github.com/Synchro/1139429
However, the questioner's example did not include upper case letters. If lower-case only letters are required, you want a base36 encoding.
On another note, the questioner was asking for what is appropriate for a URL. You can use base64, but you must use a special case, making sure that the extra characters are OK to use. Some base64 implementations include '/' and '+' as the extra 2 characters, and end with a '='. You could change those to '_' and '-', and throw away the '='. See the Encrypt and Decrypt functions here, and notice the blnBase64 flag:
Upvotes: 1
Reputation: 1708
Note: you are limited to 1024 bytes when passing data through the url. Therefore if your encryption string is truncated (even by 1 character), it will not decrypt correctly.
Upvotes: 0
Reputation: 499
Why don't you just use the strong PHP encryption methods it seems like you've already investigated, and simply encode the result? Let's you pass it via URL without issues, but you don't lock yourself into a specific or weaker encryption method in your attempt to get something that uses a URL-friendly character set.
<?php
$ciphertext = /* some encryption code here */
$url_string = urlencode( base64_encode ($ciphertext));
?>
Upvotes: 2
Reputation: 21783
1) Encrypt it using a symmetrical cypher, for example AES. The key you use for it should not be possible to see in any public code (javascript, etc)
2) Run the result of the encruption through base64 encoding, so that it will contain only printable characters.
3) To do the reverse, base64 decode then decrypt using the same key and algorithm.
Upvotes: 2
Reputation: 522382
base64_encode
to get an ASCII-only string.Upvotes: 8