Having seen Java’s getBytes() function for a Caesar cipher I am thinking about the possibility to clone this functionality to PHP.
In Java the function is:
private static final SHIFT_LENGTH = 0x3;
public static String encode(String str)
{
str = "teststring";
byte[] bytes = str.getBytes("UTF8");
for (int i=0; i < bytes.length; ++i)
{
bytes[i] = bytes[i] + SHIFT_LENGTH;
}
// Base-64 encode
return new BASE64Encoder().encode(bytes);
}
The function should be adding three to each byte in the string and then base-64 encoding it. I’ve tried a bunch of variations in PHP, like the following:
function encode_php($str)
{
$str = utf8_encode("teststring");
$new_str = '';
for ($i = 0; $i < strlen($str); $i++) {
$new_str .= ord($str[$i])+3;
}
return base64_encode($new_str);
}
I’m obviously missing something in terms of encoding or how to handle individual bytes in PHP, but I’m not sure what. I’ve tried using dechex() and bin2hex() to mess with the encoding but can’t get the results to match. Any ideas?
Don’t you mean
$new_str .= chr((ord($str[$i])+3)%256);