You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PubNub v7与v3.16.5跨版本互发消息异常:对方接收内容显示加密

PubNub v7与v3.16.5跨版本消息加密不兼容问题解决

问题场景

网站使用PubNub v7(最新版本),移动端应用固定用v3.16.5(无法升级),出现双向加密异常:

  • 网站发送的消息自身可正常查看,但移动端接收内容为加密乱码
  • 移动端发送的消息自身可正常查看,网站接收内容也显示加密乱码
    将网站降级至v3.16.5后,所有功能恢复正常,确认是版本差异导致的加密逻辑不匹配。

网站核心配置代码如下:

function CreatePubNubInstance(userId: string) {
    return new PubNub({
        publishKey: "pubNubPublishKey",
        subscribeKey: "pubNubSubscribeKey",
        secret_key: "pubNubSecretKey",
        cipher_key: "pubNubCipherKey",
        userId,
    });
}

const pubnub = PubnubFactory.CreatePubNubInstance(userId);
pubnub.subscribe({channels: [state.ChannelName]})
pubnub.addListener({
  // Messages
  message: function (m: any) {
    const pubTT = m.timetoken; // Publish timetoken
    const msg = m.message; // Message payload
    handleMessage(msg, pubTT);
  }
})
pubnub.fetchMessages(
    {
        channels: [state.ChannelName],
    },
    (status: any, response: any) => {
        const { channels } = response;
        const history = channels[state.ChannelName as string].map((message: any) => message.message);
    console.log(history); // 对应截图中的输出
    }
);
const res = await pubnub.publish({
    message: msg,
    channel: state.ChannelName,
    storeInHistory: true,
});

问题原因

PubNub v7默认采用GCM加密模式,而v3.x版本默认使用CBC加密模式,两种模式的加密格式、解密逻辑完全不兼容,导致跨版本收发消息时无法正常解密对方内容。

解决方案

在v7的实例配置中强制指定加密模式为CBC,和v3.16.5保持一致,修改CreatePubNubInstance函数:

function CreatePubNubInstance(userId: string) {
    return new PubNub({
        publishKey: "pubNubPublishKey",
        subscribeKey: "pubNubSubscribeKey",
        secret_key: "pubNubSecretKey",
        cipher_key: "pubNubCipherKey",
        userId,
        // 强制启用CBC加密模式,兼容v3.x版本
        crypto: {
            mode: "cbc"
        }
    });
}

验证步骤

  1. 网站端应用修改后的配置,重新发送消息
  2. 验证移动端是否能正常解密显示消息
  3. 移动端发送消息,验证网站端接收是否正常
  4. 调用fetchMessages拉取历史消息,确认历史内容也能正常解密

内容的提问来源于stack exchange,提问作者DAMAR225

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:00:29