0

I thought doing the Cryptopals exercises in Nim would be a nice way to learn the language. On set 1 exercise 2, I'm getting an unexpected result on the xor part. The exercise:

If your function works properly, then when you feed it the string:

1c0111001f010100061a024b53535009181c

... after hex decoding, and when XOR'd against:

686974207468652062756c6c277320657965

... should produce:

746865206b696420646f6e277420706c6179

The Python solution is very obvious. I've been doing the exercises in Node.js and it's a no-brainer as well.

My solution in Nim:

import strutils as strutils

var a, b = 0

a = toU16(strutils.parseHexInt("1c0111001f010100061a024b53535009181c"))
b = toU16(strutils.parseHexInt("686974207468652062756c6c277320657965"))

let result = toHex(a xor b)

The outputs are:

  • a: 165317428619319324
  • b: 7812662828999211365
  • (a xor b): 7937440550937715065
  • hex(a xor b): 0000000000006179

This is not at all what I'd expect. Am I parsing hexadecimals and/or binary incorrectly?

filipe
  • 414
  • 1
  • 5
  • 14

1 Answers1

1

You should use parseHexStr on both the input and the input for the second parameter of the XOR operation. Then you can XOR each byte separately and store the result in a new array.

Nim integers are the same size as Nim pointers. You're parsing two large byte arrays in hexadecimals, while the result is a smaller integer. Or, to be more specific, the input values and result you're getting are calculated modulus two to the power 64 as you're probably working on a 64 bit CPU.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • I was able to at least get a proper `xor`ed string in the end, although it's not what's expected. Perhaps it's best to learn Nim some other way. Thanks for the help! – filipe Jul 13 '18 at 07:16
  • @FilipeCatraia You've just been pampered by Python, which is able to use unlimited precision integers by default :) Not many language do (while this would clearly be a boon, especially from a testing / security perspective, where handling values that silently overflow is a complete nightmare). – Maarten Bodewes Jul 14 '18 at 11:30
  • yes, higher-level languages in general make one too comfortable. Nim has been a real eye-opener. – filipe Jul 16 '18 at 10:06