2 * Copyright (C) 2013 Toni Gundogdu <legatvs@gmail.com>
4 * This file is part of libquvi <http://quvi.sourceforge.net/>.
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU Affero General Public
8 * License as published by the Free Software Foundation, either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General
17 * Public License along with this program. If not, see
18 * <http://www.gnu.org/licenses/>.
24 * The 'key', the 'ciphertext' and the 'plaintext' are all expected to
25 * be hexadecimal strings when passed from and to a Lua script.
37 #include "gcrypt/crypto.h"
38 #include "lua/quvi/crypto/opts.h"
39 #include "lua/quvi/crypto/err.h"
40 #include "lua/quvi/opts.h"
41 #include "lua/getfield.h"
42 #include "lua/setfield.h"
45 static gint
_exec(lua_State
*l
, const CryptoMode crypto_mode
,
48 struct l_quvi_object_crypto_opts_s co
;
49 gboolean croak_if_error
;
54 memset(&co
, 0, sizeof(struct l_quvi_object_crypto_opts_s
));
58 q
= (_quvi_t
) l_get_reg_userdata(l
, USERDATA_QUVI_T
);
63 co
.text
= luaL_checkstring(l
, 1);
68 opts
= l_quvi_object_opts_new(l
, 2);
69 croak_if_error
= l_quvi_object_opts_croak_if_error(opts
);
70 l_quvi_object_crypto_chk_opts(l
, opts
, &co
);
72 /* encrypt/decrypt (return as a hexstring). */
74 c
= crypto_new(co
.algoname
, crypto_mode
, co
.cipher
.key
,
75 co
.cipher
.mode
, co
.cipher
.flags
);
76 q
->status
.rc
= l_quvi_object_crypto_chk_if_failed(l
, c
, croak_if_error
, q
);
81 s
= crypto_hex2bytes(co
.text
, &n
);
85 crypto_dump("s", s
, n
);
91 l_quvi_object_crypto_chk_if_failed(l
, c
, croak_if_error
, q
);
94 l_quvi_object_crypto_invalid_hexstr(l
, q
, croak_if_error
);
97 /* Return a table of results. */
100 l_setfield_s(l
, QO_ERROR_MESSAGE
, q
->status
.errmsg
->str
, -1);
101 l_setfield_n(l
, QO_QUVI_CODE
, q
->status
.rc
);
103 if (q
->status
.rc
== QUVI_OK
)
105 gchar
*s
= crypto_bytes2hex(c
->out
.data
, c
->out
.dlen
);
106 l_setfield_s(l
, push_as
, s
, -1);
110 l_quvi_object_opts_free(opts
);
113 return (1); /* no. of returned values (a table) */
116 gint
l_quvi_crypto_encrypt(lua_State
*l
)
118 return (_exec(l
, CRYPTO_MODE_ENCRYPT
, QO_CIPHERTEXT
));
121 gint
l_quvi_crypto_decrypt(lua_State
*l
)
123 return (_exec(l
, CRYPTO_MODE_DECRYPT
, QO_PLAINTEXT
));
126 /* vim: set ts=2 sw=2 tw=72 expandtab: */