Encryption string on Codeigniter - php

just wanted to verify if on Codeigniter Encryption say like this one
hhNa0fUcOc3k0jUhPcRBJshpiXLpUSug+NhgPk89O7eSjerHk6go360U9rl8LazZo6DR6M1N4IqG0PYIwPyKhQ==
Is the structure of this string always have a '+', '=' and a '/' character?. Just wanted to verify things before i parse them. Is there a case wherein when a string is encrypted it may contain special character other than '+, =, /' signs? Just a heads up, i didn't used any mcrypt thing other than the default specified on CI.

This seems like a base-64 encoded string. + and / are valid characters, and = are padding which will always show up on the end. +, / and = are the only special characters in a standard base-64 implementation.

use this to remove = from the encoded string while using base64_encode
<?php echo rtrim(base64_encode($content_string),'=') ?>

Related

php simple encode decode function using only (0-9 A-Z a-z)

I'm setting up a PHP email tracking system that uses url parameters to track link click throughs. Something like:
www.example.com?trackToken=10
I'm looking for a simple PHP encode / decode function I can put in place that will take a number (in this case 10) and convert in to strictly to number and letters. something like:
www.example.com?trackToken=7aj8nG93nDpw9M9Nk1
I have found several variations of encrypt / decrypt functions using mcrypt. However, the encrypted output always ends up containing strange characters. These strange characters make it hard for my email messages to be sent/delivered.
Does anyone know of a good encrypt function that only outputs numbers 0-9 and letters a-z or A-Z? Additionally, I'm looking for a decrypt function to complement the encrypt function so I can actually use it.
I'm not looking for something super secure here. Just a way to mask the actual tracking token so the user can't change it on their own.
Base64 should be fine in any modern system - and any system handling email in PHP fits the definition of "modern". There is absolutely no reason I can think of to limit to just alphanumerics. The only catch is that as a URL parameter you don't want to have a '+' or '/' in the string. There is base64url to solve this problem but that doesn't have a standard PHP function. You can easily replicate that by using base64_encode() and str_replace() and to decode str_replace followed by base64_decode():
$coded = str_replace('+','-',str_replace('/','_',base64_encode($original)));
$original = base64_decode(str_replace('_','/',str_replace('-','+',$coded)));

MCRYPT mode is generating slashes

I'm new to this encryption thing, so i'm not realy sure how to format my question.
Anyways i'm using framework called kohana and for encryption it uses three things:
key, cipher, mode so my problem is that when it encodes some string sometimes i get / in encryption like this fclzSev6DVfOk2Z/BSSi4dRYFn4t and i don't want that so my guess is that i should change mode which right now is MCRYPT_MODE_NOFB so if i'm right what mode do i have to use?
As Francis Avila notes, the encrypted output seems to be Base64-encoded, and so may contain slashes and plus signs (and possibly equals signs at the end) in addition to letters and numbers.
You can safely replace those signs with something else, as long as you remember to change them back before decoding. The PHP strtr() function is handy for this. For example, here's how to convert a string from normal Base64 to the RFC 4648 URL-safe Base64 variant and back:
$url_safe_base64 = strtr( $base64_string, "+/", "-_" );
$base64_string = strtr( $url_safe_base64, "-_", "+/" );
mode has absolutely nothing to do with whether the generated output has slashes, but specifies what mode of encryption mcrypt should use. If you don't know what it's for use the default.
The reason there are slashes is that Kohana's encode() method will encode the binary output from the encryption in base64, which may contain slashes.
You can str_replace() the slashes with something else, but this will probably create more problems and headaches than it solves.

get values in url

I need to get values in the url as it is
ex:
http://www.example.com/index?url=1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA==
but vriable url give me value of "1 LY2ePh1pjX4tjZ4 GS393Y2pjd16Cbq63T3tbfzMzd16CarA=="
Even though i have expected "1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA=="
any one can help me for this or know the reason
You see, you need to encode certain characters if you need to send them in a URL. For further references, I suggest you should read this Page. It seems that the URL you are getting isn't being encoded properly. If the URL is coming from your site, then I would suggest you to encode it properly.
In PHP, there is a function called urlencode, which may help you with this task.
A short explanation
URLs can only be sent over internet using ASCII character set.If you want to send characters which is outside this set, you need to encode it.URL encoding replaces unsafe ASCII characters with % followed by two hexadecimal digits corresponding to the character values in the ISO-8859-1 character-set.
The client sending the request apparently isn't URL encoding the value correctly. You can re-encode it after it's being decoded like this:
urlencode($_GET["url"])
IT convert %2B to space
The parameter you sent is wrong, it should have been encoded like so..
<?php
echo '<a href="http://www.example.com/index?url=', urlencode('1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA=='), '">';
?>
i have added encoding correctly now,It convert == correctly, but + sign encode to %2B correctly but in decode process it convert to space
As it seems that you’re having a Base-64 value there: You can use the URL safe alphabet for Base-64 that uses - and _ instead of + and / respectively:
$base64 = "1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA==";
// plain Base-64 to URL safe Base-64
$base64_safe = strtr($base64, '+/', '-_');
// URL safe Base-64 to plain Base-64
$base64 = strtr($base64_safe, '-_', '+/');
And if you know the length of the data, you can also omit the = padding:
rtrim($base64, '=')

Passing base64 encoded strings in URL

Is it safe to pass raw base64 encoded strings via GET parameters?
There are additional base64 specs. (See the table here for specifics ). But essentially you need 65 chars to encode: 26 lowercase + 26 uppercase + 10 digits = 62.
You need two more ['+', '/'] and a padding char '='. But none of them are url friendly, so just use different chars for them and you're set. The standard ones from the chart above are ['-', '_'], but you could use other chars as long as you decoded them the same, and didn't need to share with others.
I'd recommend just writing your own helpers. Like these from the comments on the php manual page for base64_encode:
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '._-');
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '._-', '+/='));
}
No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.
Valid base64 characters are below.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
#joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.
$str = 'Some String';
$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );
Introductory Note I'm inclined to post a few clarifications since some of the answers here were a little misleading (if not incorrect).
The answer is NO, you cannot simply pass a base64 encoded parameter within a URL query string since plus signs are converted to a SPACE inside the $_GET global array. In other words, if you sent test.php?myVar=stringwith+sign to
//test.php
print $_GET['myVar'];
the result would be:
stringwith sign
The easy way to solve this is to simply urlencode() your base64 string before adding it to the query string to escape the +, =, and / characters to %## codes.
For instance, urlencode("stringwith+sign") returns stringwith%2Bsign
When you process the action, PHP takes care of decoding the query string automatically when it populates the $_GET global.
For example, if I sent test.php?myVar=stringwith%2Bsign to
//test.php
print $_GET['myVar'];
the result would is:
stringwith+sign
You do not want to urldecode() the returned $_GET string as +'s will be converted to spaces.
In other words if I sent the same test.php?myVar=stringwith%2Bsign to
//test.php
$string = urldecode($_GET['myVar']);
print $string;
the result is an unexpected:
stringwith sign
It would be safe to rawurldecode() the input, however, it would be redundant and therefore unnecessary.
Yes and no.
The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()).
Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.
Its a base64url encode you can try out, its just extension of joeshmo's code above.
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
I don't think that this is safe because e.g. the "=" character is used in raw base 64 and is also used in differentiating the parameters from the values in an HTTP GET.
If you have sodium extension installed and need to encode binary data, you can use sodium_bin2base64 function which allows you to select url safe variant.
for example encoding can be done like that:
$string = sodium_bin2base64($binData, SODIUM_BASE64_VARIANT_URLSAFE);
and decoding:
$result = sodium_base642bin($base64String, SODIUM_BASE64_VARIANT_URLSAFE);
For more info about usage, check out php docs:
https://www.php.net/manual/en/function.sodium-bin2base64.php
https://www.php.net/manual/en/function.sodium-base642bin.php
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
For url safe encode, like base64.urlsafe_b64encode(...) in Python the code below, works to me for 100%
function base64UrlSafeEncode(string $input)
{
return str_replace(['+', '/'], ['-', '_'], base64_encode($input));
}

What character replacements should be performed to make base 64 encoding URL safe?

In looking at URL safe base 64 encoding, I've found it to be a very non-standard thing. Despite the copious number of built in functions that PHP has, there isn't one for URL safe base 64 encoding. On the manual page for base64_encode(), most of the comments suggest using that function, wrapped with strtr():
function base64_url_encode($input)
{
return strtr(base64_encode($input), '+/=', '-_,');
}
The only Perl module I could find in this area is MIME::Base64::URLSafe (source), which performs the following replacement internally:
sub encode ($) {
my $data = encode_base64($_[0], '');
$data =~ tr|+/=|\-_|d;
return $data;
}
Unlike the PHP function above, this Perl version drops the '=' (equals) character entirely, rather than replacing it with ',' (comma) as PHP does. Equals is a padding character, so the Perl module replaces them as needed upon decode, but this difference makes the two implementations incompatible.
Finally, the Python function urlsafe_b64encode(s) keeps the '=' padding around, prompting someone to put up this function to remove the padding which shows prominently in Google results for 'python base64 url safe':
from base64 import urlsafe_b64encode, urlsafe_b64decode
def uri_b64encode(s):
return urlsafe_b64encode(s).strip('=')
def uri_b64decode(s):
return urlsafe_b64decode(s + '=' * (4 - len(s) % 4))
The desire here is to have a string that can be included in a URL without further encoding, hence the ditching or translation of the characters '+', '/', and '='. Since there isn't a defined standard, what is the right way?
There does appear to be a standard, it is RFC 3548, Section 4, Base 64 Encoding with URL and Filename Safe Alphabet:
This encoding is technically identical
to the previous one, except for the
62:nd and 63:rd alphabet character, as
indicated in table 2.
+ and / should be replaced by - (minus) and _ (understrike) respectively. Any incompatible libraries should be wrapped so they conform to RFC 3548.
Note that this requires that you URL encode the (pad) = characters, but I prefer that over URL encoding the + and / characters from the standard base64 alphabet.
I don't think there is right or wrong. But most popular encoding is
'+/=' => '-_.'
This is widely used by Google, Yahoo (they call it Y64). The most url-safe version of encoders I used on Java, Ruby supports this character set.
I'd suggest running the output of base64_encode through urlencode. For example:
function base64_encode_url( $str )
{
return urlencode( base64_encode( $str ) );
}
If you're asking about the correct way, I'd go with proper URL-encoding as opposed to arbitrary replacement of characters. First base64-encode your data, then further encode special characters like "=" with proper URL-encoding (i.e. %<code>).
Why don't you try wrapping it in a urlencode()? Documentation here.

Categories