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

如何用Piheaan在Python中加密二维数字数组并输出平方结果

解决Piheaan处理二维numpy数组加密平方解密的TypeError问题

问题原因

np.ndenumerate返回的是元组类型的索引(比如(0,0)、(0,1)),而heaan.Message仅支持整数类型的索引赋值,这就是触发TypeError的核心原因。

解决方案

放弃使用np.ndenumerate,改为逐行处理二维数组——复用原有一维列表的加密/平方/解密逻辑,对每个子列表单独操作,最后将结果组合成二维数组。

完整代码示例

import numpy as np
import heaan

# 初始化Heaan上下文与密钥(根据实际需求调整参数预设)
params = heaan.ParameterPreset.FGb
context = heaan.Context(params)
sk = heaan.SecretKey(context)
pk = heaan.PublicKey(context, sk)
evaluator = heaan.Evaluator(context, pk)

def process_single_row(row):
    """处理单行一维数组:加密→平方→解密"""
    # 初始化Message并赋值(使用整数索引,符合Heaan要求)
    msg = heaan.Message(context)
    for idx, val in enumerate(row):
        msg[idx] = val
    
    # 加密
    cipher = heaan.Ciphertext(context)
    heaan.encrypt(msg, pk, cipher)
    
    # 平方运算
    evaluator.square(cipher, cipher)
    
    # 解密
    decrypted_msg = heaan.Message(context)
    heaan.decrypt(cipher, sk, decrypted_msg)
    
    # 转换为numpy数组返回
    return np.array([decrypted_msg[i] for i in range(len(row))])

# 输入二维数组
input_arr = np.array([[2,5,4,3],[1,2,2,3]])

# 逐行处理并组合结果
output_rows = [process_single_row(row) for row in input_arr]
output_arr = np.vstack(output_rows)

print(output_arr)
# 输出结果:
# array([[4., 25., 16., 9.],
#        [1., 4., 4., 9.]])

关键说明

  1. 逐行处理:将二维数组拆解为多个一维子数组,每个子数组用原有逻辑处理,避免了元组索引的问题
  2. 整数索引赋值:使用enumerate获取单行内的整数索引,完全符合heaan.Message的赋值要求
  3. 结果组合:用np.vstack将处理后的单行数组堆叠为二维数组,还原输入的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:05:27