x509: Add :digest() method to return cert sha1 fingerprint

Fri, 05 Nov 2010 22:17:40 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Fri, 05 Nov 2010 22:17:40 +0000
changeset 17
4e3da35cc9ab
parent 16
0cefcdd5b635
child 18
2c6fbfe07883

x509: Add :digest() method to return cert sha1 fingerprint

src/x509.c file | annotate | diff | comparison | revisions
--- 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}
 };
 

mercurial