openssl: 兼容openssl1.1.0及旧版本

openssl: 兼容openssl1.1.0及旧版本

openssl 1.1.0+ 版本和低版本有很多接口不兼容问题,例如:

openssl 1.1.0+ 版本中,很多 struct 是不透明的,不能在栈中直接声明变量,需要通过指定的函数来在堆中创建非透明的struct对象并返回指针。

	HMAC_CTX *ctx;
	ctx = HMAC_CTX_new();
	HMAC_Init_ex(ctx, key, keyLen, md, NULL);
	HMAC_Update(ctx, msg, msgLen);
	HMAC_Final(ctx, md_value, &md_len);
	HMAC_CTX_free(ctx);

而低版本的openssl(例如1.0.2)是可以直接在栈上声明 struct 对象。

	HMAC_CTX ctx;
	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, key, keyLen, md, NULL);
	HMAC_Update(&ctx, msg, msgLen);
	HMAC_Final(&ctx, md_value, &md_len);
	HMAC_CTX_cleanup(&ctx);

但是,我的应用程序,应该具备一定的兼容性,既能兼容低版本openssl,也能兼容高版本openssl。

依据:https://wiki.openssl.org/index.php/OpenSSL_1.1.0_Changes

Backward compatibility
Since some structures have become opaque you can’t directly access the member any more. You might need to create backward compatible macros or functions if you still want to support older versions of OpenSSL. A suggested way of doing that is:
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#define OBJ_get0_data(o) ((o)->data)
#define OBJ_length(o) ((o)->length)
#endif

我们可以通过 OPENSSL_VERSION_NUMBER 宏来判断当前使用的openssl版本,进行条件编译:

#if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x10100000L
	HMAC_CTX ctx;
	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, key, keyLen, md, NULL);
	HMAC_Update(&ctx, msg, msgLen);
	HMAC_Final(&ctx, md_value, &md_len);
	HMAC_CTX_cleanup(&ctx);
#else
	HMAC_CTX *ctx;
	ctx = HMAC_CTX_new();
	HMAC_Init_ex(ctx, key, keyLen, md, NULL);
	HMAC_Update(ctx, msg, msgLen);
	HMAC_Final(ctx, md_value, &md_len);
	HMAC_CTX_free(ctx);
#endif

这样,在编译时自动依据使用的openssl库版本,条件编译选择不同的代码,保证向后兼容。

如果有更好的办法,请大家随时联系我~谢谢!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章