3

I need to encrypt and decrypt short strings (Ex. 'product1234'). I have used mcrypt_encrypt and mcrypt_decrypt with various ciphers. The problem is that invariably it throws in extended characters into resulting string, which causes some issues with certain aspects of my application code that I cannot control.

So, the question is whether there is either a cipher that reduces the list of characters that are used in the encrypted string (i.e. leaving out things such as '+', '\', or '/').

6
  • 3
    Please show us the code which exhibits the problem, as it is hard to envision. It is very likely you can correct the issue via base64_encode() Commented Jun 18, 2012 at 2:02
  • @Michael base64_encode will always output a longer string than the original Commented Jun 18, 2012 at 2:15
  • 1
    What do you want to achieve? Cryptographic security? Just shortening the number of characters? Commented Jun 18, 2012 at 2:16
  • @Mahn I understood the request to be limiting the character set, not necessarily the length. Commented Jun 18, 2012 at 2:18
  • If you want to achieve a short string, but only using certain characters, you could gzip encode the string, then encode it in an arbitrary base (depending on what characters you want to use). Commented Jun 18, 2012 at 2:19

1 Answer 1

7

You can make base64_encode web safe:

function base64url_encode($plainText)
{
    return strtr(base64_encode($plainText), '+/=', '-_,');
}

function base64url_decode($b64Text)
{
    return base64_decode(strtr($b64Text, '-_,' '+/='));
}

Or use hexadecimal encoding:

bin2hex($plainText);

hex2bin($hexText);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. just one comma is forgotten: return base64_decode(strtr($b64Text, '-_,', '+/='));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.