Skip to content

Instantly share code, notes, and snippets.

@larsr
Last active February 7, 2020 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsr/cfe31ff104b69e0fbce6e8532b4c1056 to your computer and use it in GitHub Desktop.
Save larsr/cfe31ff104b69e0fbce6e8532b4c1056 to your computer and use it in GitHub Desktop.

Haskell

import Crypto.Cipher.AES
import Data.ByteString.UTF8 (fromString, toString)
import Data.ByteString.Base16 (encode)


main = do
  print $ encode $ crypto
  putStrLn $ toString $ dec $ crypto
  where enc = encryptCBC (initAES (fromString password)) (fromString iv)
        dec = decryptCBC (initAES (fromString password)) (fromString iv)
        crypto = enc $ fromString "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbå"
        password = "very secret shared key.........."
        iv = "0000000000000000"

-- output:
-- "3d6818b1f5c4ee148673a8b41b34878e09270b230d8a0234a30d07856de56d7247d8472ec7158898bc40506258b3c1e2"
-- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbå

C implementation using mbedtls for comparison

compile with gcc test.c -lmbedcrypto

#include <stdio.h>
#include <mbedtls/aes.h>

void dump( const char *format, const unsigned char *x, size_t len ) {
  for ( int i = 0; i < len; i++ ) { printf(format, (int) x[i]); }
  printf("\n");
}

int main() {
  mbedtls_aes_context aes;

  unsigned char key[32] = "very secret shared key..........";
  unsigned char iv[16]  = "0000000000000000";  /* gets modified by mbedtls_aes_crypt_cbc */
  unsigned char iv2[16]  = "0000000000000000";

  unsigned char input [128] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbå";
  unsigned char output[128], decrypt[128];

  size_t input_len = 48;  /* in bytes, must be a multiple of 16 */

  unsigned int keybits = sizeof(key) * 8;
  int ret;

  
  mbedtls_aes_init( &aes );
  mbedtls_aes_setkey_enc( &aes, key, keybits );
  ret = mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, input_len, iv, input, output );

  dump("%02x", output, input_len);
  
  mbedtls_aes_init( &aes );
  mbedtls_aes_setkey_dec( &aes, key, keybits );
  ret = mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_DECRYPT, input_len, iv2, output, decrypt );
  if ( ret != 0 ) { printf("couldn't decrypt.\n"); goto done; }

  dump("%c", decrypt, input_len);

  printf("hello world!\n");
  
 done:
  return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment