title: FFI Encryption/Decryption with LuaJit
body: <p>I'm trying to encrypt and decrypt using OpenSSL through FFI in LuaJIT - I've tried a lot of different variations but I'm not having a lot of luck. My code seems to return empty strings all the time.</p>
  
  <p>I'm attempting to following the pattern described as part of the OpenSSL docs: <a href="https://www.openssl.org/docs/manmaster/crypto/EVP_PKEY_decrypt.html" rel="nofollow">https://www.openssl.org/docs/manmaster/crypto/EVP_PKEY_decrypt.html</a></p>
  
  <pre><code>    local ffi = require "ffi"
      ffi.cdef[[
        EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e);
        void *malloc(size_t size);
        void free(void *ptr);
  
        int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx);
        int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen);
  
        int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx);
        int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen);
      ]]
  
      local s = "hello world"
      local s_len = #s
      local out_len1 = ffi.new("size_t[1]")
  
      local ctx = ffi.C.EVP_PKEY_CTX_new(gen_key, nil)
      if not ctx then
        return nil
      end
  
      if ffi.C.EVP_PKEY_encrypt_init(ctx) == 0 then
        return nil
      end
  
      if ffi.C.EVP_PKEY_encrypt(ctx, nil, out_len1, s, s_len) == 0 then
        return nil
      end
  
      local buf = ffi.new("unsigned char[?]", out_len1[0])
  
      if ffi.C.EVP_PKEY_encrypt(ctx, buf, out_len1, s, s_len) == 0 then
        return nil
      end
  
      local s = ffi.string(buf, out_len1[0])
      local s_len = #s
      local out_len2 = ffi.new("size_t[1]")
  
      if ffi.C.EVP_PKEY_decrypt_init(ctx) == 0 then
        return nil
      end
  
      if ffi.C.EVP_PKEY_decrypt(ctx, nil, out_len2, s, s_len) == 0 then
        return nil
      end
  
      local buf = ffi.new("unsigned char[?]", out_len2[0])
      if ffi.C.EVP_PKEY_decrypt(ctx, buf, out_len2, s, s_len) == 0 then
        return nil
      end
  
      return ffi.string(buf, out_len2[0])
  </code></pre>