dongshi6710 2014-09-08 04:31
浏览 34
已采纳

操纵二进制字符串中的字节

I have some encryption code that works fine. In order to make it a bit sneakier, I wanted to tweak the byte array after its encrypted and un-tweak it on the other side before decryption. This way if somebody gets my encryption key, just maybe they won't figure out why its not working.

However whenever I manipulate the bytes it breaks things, which to me means I am not correctly modifying the string byte array. Here is my implementation as suggested below. Its doing the encrypt and decrypt directly after each other for testing purposes.

$string = "My Test String";
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_RAND);
$key = pack('H*', encryptKey());
$result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addpadding($string), MCRYPT_MODE_CBC, $iv);

$ordVal = ord($result[5]);
if($ordVal == 0)
{
    $ordVal = 255;
}
else
{
    $ordVal--;
}
//$result[5] = $ordVal;
$data = base64_encode($iv . $result);

$str = base64_decode($data);
if(!str)
{
    dieEncrypted("Unable to base64 decode string");
}
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = substr($str,0,$ivSize);
$str = substr($str,$ivSize);
$ordVal = ord($str[5]);
if($ordVal == 255)
{
    $ordVal = 0;
}
else
{
    $ordVal++;
}
//$str[5] = $ordVal;
$key = pack('H*', encryptKey());
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_CBC, $iv);
if(!$result)
{
    dieEncrypted("Unable to unencrypt string");
}
$result = strippadding($result);
echo "The result is: $result|"; 
  • 写回答

3条回答 默认 最新

  • dsfovbm931034814 2014-09-08 16:59
    关注

    Ok I figured this out. It looks like the string format of this data is such that you can't manipulate a single character. Perhaps its multi byte characters or something. Anyhow the solution was to encode to base64 as suggested above, then perform the byte manipulation using a rollover logic since base64 is not linear. This combines the ord\chr solution mentioned in the 2nd answer. So both answers put together in this manner seemed to do the trick. Thanks all!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源