@@ -43,6 +43,52 @@ static int lrandomkey(lua_State *L) {
4343/* -- xor_str -- */
4444
4545
46+ /* 获取证书序列号 */
47+ static int lcert_get_sn (lua_State * L ) {
48+
49+ size_t tsize = 0 ;
50+ const char * text = luaL_checklstring (L , 1 , & tsize );
51+
52+ #if OPENSSL_VERSION_NUMBER >= 0x10002000L
53+
54+ /* 从字符串读取 */
55+ BIO * io = NULL ; X509 * cert = NULL ;
56+ io = BIO_new (BIO_s_mem ()); BIO_write (io , text , tsize );
57+ cert = PEM_read_bio_X509 (io , NULL , NULL , NULL ); BIO_free (io );
58+ if (!cert )
59+ {
60+ io = BIO_new_file (text , "rb" );
61+ if (!io )
62+ { lua_pushnil (L ); lua_pushliteral (L , "[x509 ERROR]: Can't load cert." ); return 2 ; }
63+
64+ cert = PEM_read_bio_X509 (io , NULL , NULL , NULL ); BIO_free (io );
65+ if (!cert )
66+ {
67+ char buf [512 ]; memset (buf , 0 , sizeof (buf ));
68+ ERR_error_string_n (ERR_get_error (), buf , sizeof (buf ));
69+ lua_pushnil (L ); lua_pushfstring (L , "[ssl load_certificate]: %s." , buf );
70+ return 2 ;
71+ }
72+ }
73+
74+ const ASN1_INTEGER * sn = X509_get0_serialNumber (cert );
75+ if (!sn )
76+ { lua_pushnil (L ); lua_pushliteral (L , "[x509 ERROR]: can't load cert serial Number" ); return 2 ; }
77+
78+ char buf [64 ]; char * p = buf ;
79+ int len = i2d_ASN1_INTEGER (sn , (uint8_t * * )& p );
80+ if (len < 0 )
81+ { lua_pushnil (L ); lua_pushliteral (L , "[x509 ERROR]: serial Number can't write buffer failed." ); return 2 ; }
82+
83+ /* 多出2个字节, 暂时不清楚为什么 */
84+ lua_pushlstring (L , buf + (len - 20 ), len - (len - 20 ));
85+ return 1 ;
86+ #else
87+ return luaL_error (L , "[x509 ERROR]: can't load cert serial Number" );
88+ #endif
89+ }
90+
91+
4692#define lua_set_key_INT (L , key , value ) ({ lua_pushstring((L), (key)); lua_pushinteger((L), (value)); lua_rawset((L), -3); })
4793#define lua_set_key_STR (L , key , value ) ({ lua_pushstring((L), (key)); lua_pushstring((L), (value)); lua_rawset((L), -3); })
4894#define lua_set_key_PTR (L , key , value ) ({ lua_pushstring((L), (key)); lua_pushlightuserdata((L), (void*)(value)); lua_rawset((L), -3); })
@@ -178,6 +224,8 @@ LUAMOD_API int luaopen_lcrypt(lua_State *L) {
178224 { "sm4_ofb_decrypt" , lsm4_ofb_decrypt },
179225 { "sm4_ctr_encrypt" , lsm4_ctr_encrypt },
180226 { "sm4_ctr_decrypt" , lsm4_ctr_decrypt },
227+ // 证书相关
228+ { "get_cert_sn" , lcert_get_sn },
181229 { NULL , NULL },
182230 };
183231 luaL_newlib (L , lcrypt );
0 commit comments