# HG changeset patch # User Matthew Wild # Date 1288995460 0 # Node ID 4e3da35cc9ab32c9769cee4ead64bc204753941c # Parent 0cefcdd5b635f40f6bba0b6697e2f6fec468829c x509: Add :digest() method to return cert sha1 fingerprint diff -r 0cefcdd5b635 -r 4e3da35cc9ab src/x509.c --- a/src/x509.c Fri Nov 05 21:25:30 2010 +0000 +++ b/src/x509.c Fri Nov 05 22:17:40 2010 +0000 @@ -170,12 +170,51 @@ return 1; } +const char* hex_tab = "0123456789abcdef"; +void to_hex(const char* in, int length, char* out) { + int i; + for (i = 0; i < length; i++) { + out[i*2] = hex_tab[(in[i] >> 4) & 0xF]; + out[i*2+1] = hex_tab[(in[i]) & 0xF]; + } +} + +int meth_digest(lua_State* L) +{ + X509 *cert; + unsigned int bytes; + unsigned char buffer[EVP_MAX_MD_SIZE]; + char hex_buffer[EVP_MAX_MD_SIZE*2]; + const EVP_MD *digest; + cert = luasec_to_x509(L, 1); + if(lua_gettop(L) < 2 || strcmp(luaL_checkstring(L, 1), "sha1") == 0) + { + digest = EVP_sha1(); + } + else + { + lua_pushnil(L); + lua_pushstring(L, "digest algorithm not supported"); + return 2; + } + if(!X509_digest(cert, digest, buffer, &bytes)) + { + lua_pushnil(L); + lua_pushstring(L, "out of memory"); + return 2; + } + to_hex((char*)buffer, bytes, hex_buffer); + lua_pushlstring(L, hex_buffer, bytes*2); + return 1; +} + /** * Certificate metamethods */ static luaL_Reg meta[] = { {"decode", meth_decode}, {"pem", meth_pem}, + {"digest", meth_digest}, {NULL, NULL} };