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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False