0

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)

7
  • 1
    And your expected output would be? Commented Feb 20, 2015 at 18:08
  • 9299dd089611fa47f130c4e92aaa09ff Commented Feb 20, 2015 at 18:09
  • The "another attempt" has a syntax error. Commented Feb 20, 2015 at 18:09
  • Sorry about that. fixed. Commented Feb 20, 2015 at 18:10
  • @Tarik - that gives me the same output as $bytes[15] = 0xff Commented Feb 20, 2015 at 18:12

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

So it was a matter of converting the integer to a character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.