duanliao5995 2015-02-20 18:05
浏览 41
已采纳

将字节数组位置设置为任意整数值

I'm implementing an AES encryption algorithm, and I need to come up with a way to increment my iv. I'm stuck on a pretty simple question:

If I have a 16-byte, randomly generated array, how can I set a specific byte to an arbitrary value?

For example, say that I just want to arbitarily set my least-significant byte to 0xff:

<?php

$bytes = openssl_random_pseudo_bytes(16);
echo bin2hex($bytes) . "<br>";

$bytes[15] = 0xff; // arbitrarily set this byte
echo bin2hex($bytes) . "<br>";

?>

This yields output like this (clearly wrong):

9299dd089611fa47f130c4e92aaa09dc
9299dd089611fa47f130c4e92aaa0932

I'm trying to get to this output:

9299dd089611fa47f130c4e92aaa09ff

I've been at this for hours, and I just can't figure it out. Can anyone help? Thank you.

EDIT: I've also tried to output the array like this: echo var_dump(unpack('C*', $bytes));

This yields output like this (these numbers won't cross reference to what you see above, but just focus on the last byte):

array(16) { [1]=> int(242) [2]=> int(106) [3]=> int(88) [4]=> int(109) [5]=> int(145) [6]=> int(251) [7]=> int(38) [8]=> int(54) [9]=> int(39) [10]=> int(61) [11]=> int(175) [12]=> int(183) [13]=> int(27) [14]=> int(98) [15]=> int(13) [16]=> int(106) }

array(16) { [1]=> int(242) [2]=> int(106) [3]=> int(88) [4]=> int(109) [5]=> int(145) [6]=> int(251) [7]=> int(38) [8]=> int(54) [9]=> int(39) [10]=> int(61) [11]=> int(175) [12]=> int(183) [13]=> int(27) [14]=> int(98) [15]=> int(13) [16]=> int(50) }

Shouldn't the last byte show

[16]=> int(255)

  • 写回答

1条回答 默认 最新

  • douxian7117 2015-02-20 18:20
    关注

    You should use string manipulation routines to manipulate raw byte arrays. See Byte manipulation in PHP

    Try:

    $bytes = substr_replace ($bytes, chr(0xFF), 15 , 1);
    

    Also try:

    $bytes[15] =  chr(0xff)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题