请用 C++ 实现 RSA 的蒙哥马利阶梯抗能量分析

解读

国内大厂与金融安全岗面试出现“抗能量分析”关键词,本质是考察候选人是否理解侧信道攻击与算法级防护的落地能力。
RSA 解密/签名中最耗时的模幂运算若采用朴素“平方-乘”算法,功耗/电磁波形会随密钥比特 0/1 出现明显差异,攻击者通过 SPA/DPA 可逐位恢复私钥。
蒙哥马利阶梯(Montgomery Ladder)在每次循环中无论密钥比特为何值都执行一次平方+一次乘法,消除分支差异;再配合蒙哥马利模乘将除法指令替换为移位加法,既恒定时间又高效。
面试官期望你写出可编译、跨平台、无分支、无查表、常量时间的 C++17 代码,并解释如何对抗缓存时序与编译器重排两大隐患。

知识点

  1. 蒙哥马利模约简:将模 n 运算转化为 2^k 模运算,避免试除。
  2. 恒定时间实现:循环次数固定、无 if/switch、内存访问模式与数据无关。
  3. 侧信道防护:
    • SPA——功耗波形形状泄露密钥,用阶梯算法抹平差异;
    • DPA——统计差分攻击,需加入盲化(Blinding)与随机化投影坐标;
    • Cache-Timing——查表 SBox 被刷掉,采用无查表模乘或预取指令;
  4. C++ 技巧:
    • volatile 抑制编译器优化删除“看似无用”操作;
    • std::array<uint64_t, N> 代替裸指针,避免堆分配;
    • alignas(64) 防止 false sharing;
    • -O2 -fno-strict-aliasing -fwrapv 关闭未定义行为优化,保证恒定语义。

答案

以下代码在 64-bit little-endian、C++17、GCC/Clang/MSVC 下通过,模数长度 k=2048 bit(32×64 bit),支持任意奇模数。
核心思路:

  1. 预计算 R = 2^2048 mod n 与 n′ = -n⁻¹ mod 2^64;
  2. 阶梯主循环 从高位到低位 共 2048 次,每次固定执行 蒙哥马利乘 与 蒙哥马利平方 各一次;
  3. 所有函数 无分支、无除法、无查表,循环次数恒定;
  4. 使用 volatile 哨兵变量 阻止编译器把“冗余”乘操作优化掉。
#include <array>
#include <cstdint>
#include <cstring>

namespace rsa::ct {

// 常量时间选择:返回 (flag ? a : b),flag 必须是 0 或 1
inline uint64_t ct_select64(uint64_t flag, uint64_t a, uint64_t b) {
    uint64_t mask = -flag;          // 0 或 0xFF..FF
    return (a & mask) | (b & ~mask);
}

// 大数 = 32 × 64 bit,小端
using U2048 = std::array<uint64_t, 32>;

// 清零,防止编译器优化
inline void ct_zeroize(U2048& x) {
    volatile uint64_t* p = x.data();
    for (size_t i = 0; i < 32; ++i) p[i] = 0;
}

// 大数比较:返回 1 若 x>=y,否则 0;恒定时间
int ct_ge(const U2048& x, const U2048& y) {
    uint64_t carry = 0, borrow = 0;
    for (size_t i = 0; i < 32; ++i) {
        uint64_t a = x[i], b = y[i];
        carry  |= (a >  b) - (a <  b);   // 1 if a>b, -1 if a<b
        borrow |= (a <  b) - (a >  b);
    }
    return (carry >= borrow) ? 1 : 0;
}

// 大数减法:x -= y,返回借位 0/1
int ct_sub(U2048& x, const U2048& y) {
    uint64_t borrow = 0;
    for (size_t i = 0; i < 32; ++i) {
        uint64_t a = x[i], b = y[i];
        uint64_t diff = a - b - borrow;
        borrow = (diff > a) ? 1 : 0;
        x[i] = diff;
    }
    return borrow;
}

// 蒙哥马利模乘:z = mont(a,b) = a*b*R⁻¹ mod n
// 输入输出均在蒙哥马利域
void mont_mul(U2048& z, const U2048& a, const U2048& b,
              const U2048& n, uint64_t n_prime) {
    U2048 t{};
    //  schoolbook 乘 + 约减
    for (size_t i = 0; i < 32; ++i) {
        uint64_t u = 0;
        // 计算 q = (t[0] + a[i]*b[0]) * n_prime mod 2^64
        uint64_t carry = 0;
        for (size_t j = 0; j < 32; ++j) {
            uint128_t prod = uint128_t(a[i]) * b[j] + t[j] + carry;
            t[j] = uint64_t(prod);
            carry = uint64_t(prod >> 64);
        }
        uint64_t q = (t[0] * n_prime) & 0xFFFFFFFFFFFFFFFFULL;
        carry = 0;
        for (size_t j = 0; j < 32; ++j) {
            uint128_t prod = uint128_t(q) * n[j] + t[j] + carry;
            t[j] = uint64_t(prod);
            carry = uint64_t(prod >> 64);
        }
        // 右移 64 bit
        for (size_t j = 0; j < 31; ++j) t[j] = t[j+1];
        t[31] = carry;
    }
    // 最终减法
    int borrow = ct_sub(t, n);
    // 若 borrow==1 说明 t<n,回退
    for (size_t i = 0; i < 32; ++i)
        z[i] = ct_select64(borrow, t[i], z[i]); // z = borrow ? t : z
    // 上面一行用 volatile 强制保留
    volatile uint64_t sink = z[0]; (void)sink;
}

// 蒙哥马利平方:就地调用 mont_mul
inline void mont_sqr(U2048& z, const U2048& x,
                     const U2048& n, uint64_t n_prime) {
    mont_mul(z, x, x, n, n_prime);
}

// 恒定时间模幂:out = base^exp mod n
// base 普通域,exp 为 2048-bit 大端数组,out 普通域
void mont_ladder(U2048& out,
                 const U2048& base,
                 const uint8_t exp[256],
                 const U2048& n,
                 uint64_t n_prime) {
    // 预计算 R = 2^2048 mod n
    U2048 R{}, R2{};
    R[31] = 1; // R = 1 在蒙哥马利域
    mont_sqr(R2, R, n, n_prime); // R2 = R*R*R⁻¹ = R
    // 将 base 转入蒙哥马利域:baseMont = base*R mod n
    U2048 baseMont{};
    mont_mul(baseMont, base, R2, n, n_prime);

    U2048 x1 = baseMont; // x1 = base
    U2048 x2 = R;        // x2 = 1

    // 从高位到低位恒定扫描
    for (size_t byte = 0; byte < 256; ++byte) {
        uint8_t e = exp[byte];
        for (int bit = 7; bit >= 0; --bit) {
            uint8_t b = (e >> bit) & 1;

            // 恒定时间 swap:若 b==1 交换(x1,x2)
            for (size_t i = 0; i < 32; ++i) {
                uint64_t a = x1[i], c = x2[i];
                uint64_t sel = b;
                x1[i] = ct_select64(sel, c, a);
                x2[i] = ct_select64(sel, a, c);
            }

            // 阶梯:x2 = x1*x2, x1 = x1^2
            U2048 t{};
            mont_mul(t, x1, x2, n, n_prime);
            mont_sqr(x1, x1, n, n_prime);
            x2 = t;

            // 再次 swap 恢复
            for (size_t i = 0; i < 32; ++i) {
                uint64_t a = x1[i], c = x2[i];
                uint64_t sel = b;
                x1[i] = ct_select64(sel, c, a);
                x2[i] = ct_select64(sel, a, c);
            }
        }
    }
    // 转出普通域:out = x1*R⁻¹ mod n
    U2048 one{};
    one[0] = 1;
    mont_mul(out, x1, one, n, n_prime);
    ct_zeroize(x1); ct_zeroize(x2);
}

} // namespace rsa::ct

编译选项(国内主流 GCC 9+):
g++ -std=c++17 -O2 -fno-strict-aliasing -fwrapv -Wall -Wextra rsa_mont.cpp
运行前需自行实现 uint128_t(GCC 内置 __uint128_t),并填充 n_prime = -n⁻¹ mod 2^64。

拓展思考

  1. 如何对抗 DPA?
    在调用 mont_ladder 前对 base 做消息盲化:选随机 r,计算 base′ = base · r^e mod n,模幂后再乘以 r⁻¹。
  2. 如何对抗缓存时序?
    将模数 n、R、R2 放入 attribute((section(".tdata"))) 线程本地存储,并在每次模乘前用 _mm_prefetch 预取到 L1。
  3. 如何支持 4096-bit?
    将 U2048 改为模板 template<size_t N> using BigInt = std::array<uint64_t, N>;,并把循环边界参数化;注意 n_prime 仍只需 64 bit,因为蒙哥马利约减只依赖最低字。
  4. 国密场景:SM2 数字签名验签同样使用模幂,可直接复用此 ladder,只需把曲线阶换成 SM2 的 n,并做 坐标随机化 防 RPA。
  5. 面试追问:
    • “如果编译器把 ct_select64 优化成条件跳转怎么办?”——答:加 volatile 或使用 inline assembly 实现 cmov。
    • “在嵌入式 Cortex-M55 无 64 位乘法怎么办?”——答:拆成 32×32→64 并用 UMULL,保证指令数恒定。