0

I'm trying to rewrite some JS (which uses the SJCL library) in Python using pycrypto. I'm having trouble figuring out how to implement the following code

aes = new sjcl.cipher.aes( this.key );
bits = sjcl.codec.utf8String.toBits( text );
cipher = sjcl.mode.ccm.encrypt( aes, bits, iv );
cipherIV = sjcl.bitArray.concat( iv, cipher );
return sjcl.codec.base64.fromBits( cipherIV );

My issue isn't the crypto, but the way the library handles the fromBits conversions. According to the SJCL docs:

Most of our crypto primitives operate on arrays of 4-byte words internally, but many of them can take arguments that are not a multiple of 4 bytes. This library encodes arrays of bits (whose size need not be a multiple of 8 bits) as arrays of 32-bit words. The bits are packed, big-endian, into an array of words, 32 bits at a time. Since the words are double-precision floating point numbers, they fit some extra data. We use this (in a private, possibly-changing manner) to encode the number of bits actually present in the last word of the array.

To me this seems to imply that conversion to a bit array adds on some sort of additional information, which I am concerned will be prevalent during the concat operation. Additionally, after the concat, the result is returned as a base64 string. I am unsure of the proper 'struct' packing parameters to replicate this.

dan
  • 305
  • 1
  • 13

1 Answers1

1

If you look closely at this code you should see that it is self-contained. SJCL's "bits" (native binary data representation) are not needed after this code has run. This internal data is given into the encryption and concatenation functions, and the result is then converted back to a "normal" Base64-encoded string which is portable.

The only problem that may exist with this code is the encoding of this.key and ìv.

PyCrypto doesn't have a special internal binary data encoding, because the Python language already provides us with binary strings or bytes (depending on the Python version). But you still need to encode to / decode from string with a Base64 encoding.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222