title: rijndael: Encrypt/decrypt the same data in C and Python
body: <p>I'm trying to figure out how to mirror encryption/decryption from an existing C function over to python. However, in my tests of encrypting with C and decrypting with python, I can't figure out some elements around the key.</p>
  
  <p>These were all code samples online, so I commented things like the base64 call in Python, and at this point I'm unsure on:</p>
  
  <p><strong>1) If I correctly determined the KEYBIT to KEY_SIZE/BLOCK_SIZE settings.</strong></p>
  
  <p><strong>2) How to get from password to key in python to match the C code.</strong></p>
  
  <p><strong>3) Am I  missing any core conversion steps?</strong></p>
  
  <p>rijndael.h in C:</p>
  
  <pre><code>#define KEYLENGTH(keybits) ((keybits)/8)
  #define RKLENGTH(keybits)  ((keybits)/8+28)
  #define NROUNDS(keybits)   ((keybits)/32+6)
  </code></pre>
  
  <p>encrypting in C</p>
  
  <pre><code>#define KEYBITS 256
  
  unsigned long rk[RKLENGTH(KEYBITS)];
  unsigned char key[KEYLENGTH(KEYBITS)];
  
  char *password = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
  
  for (i = 0; i &lt; sizeof(key); i++)
      key[i] = *password != 0 ? *password++ : 0;  
  
  nrounds = rijndaelSetupEncrypt(rk, key, 256);
  
  count = 0;
  while (count &lt; strlen(input)) {
      unsigned char ciphertext[16];
      unsigned char plaintext[16];
      for (i = 0; i &lt; sizeof(plaintext); i++) {
          if (count &lt; strlen(input))
              plaintext[i] = input[count++];
          else
              plaintext[i] = 0;
      }
      rijndaelEncrypt(rk, nrounds, plaintext, ciphertext);
      if (fwrite(ciphertext, sizeof(ciphertext), 1, output) != 1)             
          fclose(file);
          fputs("File write error", stderr);
          return 0;
      }
  }
  </code></pre>
  
  <p>Decrypt in Python</p>
  
  <pre><code>KEY_SIZE = 32
  BLOCK_SIZE = 16
  
  def decrypt(password, filename):
  
      #
      # I KNOW THIS IS WRONG, BUT HOW DO I CONVERT THE PASSWD TO KEY?
      #
      key = password
  
      padded_key = key.ljust(KEY_SIZE, '\0')
  
      #ciphertext = base64.b64decode(encoded)
      ciphertext = file_get_contents(filename);
  
      r = rijndael(padded_key, BLOCK_SIZE)
  
      padded_text = ''
      for start in range(0, len(ciphertext), BLOCK_SIZE):
          padded_text += r.decrypt(ciphertext[start:start+BLOCK_SIZE])
  
      plaintext = padded_text.split('\x00', 1)[0]
  
      return plaintext
  </code></pre>
  
  <p>Thanks!</p>