【问题标题】:How to add custom encryption to gRPC C++?如何向 gRPC C++ 添加自定义加密?
【发布时间】:2021-02-18 16:56:49
【问题描述】:

我正在尝试在 gRPC C++ 客户端中添加自定义加密。

在 Python 等某些端口中,有用于 unary_unary 调用的序列化程序参数。

我看到some issue 说它可以通过使用自定义Codec 来存档,但这在 C++ 中是不可能的。

那么我是否有机会使用 gRPC C++ API 添加自定义加密?

【问题讨论】:

    标签: c++ grpc grpc-c++


    【解决方案1】:

    在这里发布我的部分解决方案。我可以加密请求有效负载,但无法解密响应正文。 我创建了一个Inceptor 并挂钩了所有方法。

    class TestInterceptor: public grpc::experimental::Interceptor {
        void Intercept(grpc::experimental::InterceptorBatchMethods* methods) override {
            const uint8_t aes_key[] = "0123456789123456";
            const uint8_t aes_iv[] = "0123456789123456";
            if (methods->QueryInterceptionHookPoint(grpc::experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
                auto s1 = methods->GetSerializedSendMessage();
                std::vector<grpc::Slice> v;
                s1->Dump(&v);
                size_t l = 0;
                for (const auto& s: v) {
                    l += s.size();
                }
                ustring buf;
                buf.resize(l);
                size_t ptr = 0;
                for (const auto& s: v) {
                    memcpy(buf.data() + ptr, s.begin(), s.size());
                    ptr += s.size();
                }
    
                // encrypt
                ustring crypted = Crypto::aes_encrypt(buf, aes_key, aes_iv);
                grpc::Slice new_slice(crypted.data(), crypted.size());
                grpc::ByteBuffer s2(&new_slice, 1);
                s1->Swap(&s2);
            }
            if (methods->QueryInterceptionHookPoint(grpc::experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
                char* s2 = (char *) methods->GetRecvMessage();
            }
            methods->Proceed();
        }
    };
    
    class TestInterceptorFactory: public grpc::experimental::ClientInterceptorFactoryInterface {
        grpc::experimental::Interceptor* CreateClientInterceptor(grpc::experimental::ClientRpcInfo* info) override {
            auto *m = info->method();
            return new TestInterceptor();
        }
    };
    

    对于通道创建,只需传递拦截器即可。

        std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface> fac_ptr = std::make_unique<TestInterceptorFactory>();
        std::vector<std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> vec = {};
        vec.push_back(std::move(fac_ptr));
        m_channel = grpc::experimental::CreateCustomChannelWithInterceptors(
                "example.com",
                channel_credentials,
                channel_arguments,
                std::move(vec)
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-26
      • 2011-10-18
      • 2017-12-20
      • 2015-08-26
      • 2019-09-12
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多