I want to Bitwise-XOR a string (actually its binary representation) with a KEY.
The result of the operation should be represented as HEX.
What I have:
‘a’ – the UTF-8 String to be changed.
‘ACF123456’ – the key in HEX.
Result seen as BIGINT:
select CONV(HEX('a'), 16, 10) ^ CONV('ACF123456', 16, 10);
Result seen as HEX:
select CONV( CONV(HEX('a'), 16, 10) ^ CONV('ACF123456', 16, 10), 10, 16);
Questions:
- Is the conversion above done correctly?
- What happens if the string is too long (i.e instead of ‘a’ we have ‘a veeeeeery long string’)? It seems that the conv() function has a limitation (is it the 64-bit precision from the documentation)? And besides the XOR operator ^ has also a limitation, related to the nr. of bits of the returned result. Any solutions that work for any string (a stored procedure is allowed)?
Thanks.
Your conversions look fine to me.
And as you point out, both
CONV()and^have indeed a 64-bits precision.2^64 = 16^16, therefore strings of more than 16 hexadecimal digits should convert to integers larger than 2^64. However, such strings will be brutally (silently) truncated from the left when attempting to convert them to integers.
The point of my solution here is to slice such strings. Obviously, the result may not be displayed as an integer, but only as a string representation.
Let
@inputbe your “string to be changed” and@key, your “key”.HEX(@input)to@hex_input. No problem here sinceHEX()works with strings.@hex_inputinto 16 hexadecimal digit long strings, starting from the right@keyinto 16 digit long strings.X-ORof each 64-bit slice of@hex_inputwith each 64-bit slice of@key, starting from the right. UseCONV(@slice, 16, 10). If either@hex_inputor@keyhas less slices than the other string, thenX-ORthe remaining slices of the other string with 0.X-ORin point 4. back into an hexadecimal string withUNHEX().A three-columns
TEMPORARYtable could be used as an array to store slices of@hex_input,@maskand the resulting slices.Put this all together into a stored procedure, and voilà!
You sound like you have some skills in MySQL, you should be able to translate the above into real code. But I’ll be happy to help if you need further guidance.