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

求问2018年可运行该AES加密代码的SageMath版本

适配旧版SageMath的AES代码版本溯源与问题分析

问题背景

这段AES加密代码在2018年Ubuntu环境下能正常运行,现在升级到Python 3.10.10 + SageMath 9.8(2023年2月11日发布)后出现兼容性问题:

  • 旧版依赖Python 2风格的SageMath,用xrange()做循环,且^^可直接当异或运算符使用
  • 新版里^^会被解析成幂运算符号**导致报错;map()返回迭代器而非列表,无法直接索引操作,必须改成list(map(...))才行

2018年可运行的原代码片段

def aes_encrypt(round_key, plain):
    R.< x >= GF(2)[]
    F = GF(2).extension(x ^ 8 + x ^ 4 + x ^ 3 + x + 1, 'a')
    a = F.gen()
    plain  # '0189fe7623abdc5445cdba3267ef9810'
    ar = map(ord, plain)  # .decode('hex') 注:原代码多了一个右括号,已修正
    #ar = list(map(ord, plain))  # .decode('hex')) NEW VERSION FIX
    print('printing AR')
    print_ar(ar)
    k = 0
    while k < 10:  # each round
        round = k*16
        print("round_key")
        print_key(round_key, k)
        print('END of KEY ',type(round_key),round_key[0])
        print(type(ar),' TYPE ar ')
        print(list(ar))
        print("XOR")
        for x in range(0, 4):
            #print(ar[x]," "," ",round_key[4*x+16*k])
            ar[x] = ar[x] ^^round_key[4*x+16*k]
            ar[x+4] = ar[x+4] ^^round_key[4*x+1+16*k]
            ar[x+8] = ar[x+8] ^^round_key[4*x+2+16*k]
            ar[x+12] = ar[x+12] ^^round_key[4*x+3+16*k]

2018年对应的SageMath版本推断

2018年发布的SageMath主流版本是8.1(2018年1月8日)和8.2(2018年5月24日),这两个版本均基于Python 2.7:

  • 完全兼容xrange()循环
  • 支持^^作为异或运算符,不会被解析成幂运算
  • 直到2020年发布的SageMath 9.0才彻底切换到Python 3,之后版本移除了xrange(),调整了^^的语法解析规则

新版环境下的代码适配方案

如果不想回退旧版本,直接修改代码适配新版:

  • 把所有^^替换成Python 3/SageMath新版支持的异或运算符^
  • 将ar = map(ord, plain)改为ar = list(map(ord, plain)),确保得到可直接索引的列表
  • 修正原代码里的语法错误:map(ord, plain))多了一个右括号,需删除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:32:35