---
eip: 198
label: EIP-198
title: Big integer modular exponentiation
status: Final
type: Standards Track
category: Core
created: 2017-01-30
official: https://eips.ethereum.org/EIPS/eip-198
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-198.md
canonical: https://eips.huatuo.xyz/zh/eip-198/
lang: zh
tldr: 在地址 0x05 新增 MODEXP 预编译，可对任意大的整数计算 (base^exp) mod m，使合约能够验证 RSA 签名及其他基于数论的密码学。
tags: [precompile, cryptography, modexp, rsa, byzantium]
---

# EIP-198: Big integer modular exponentiation

**TL;DR:** 在地址 0x05 新增 MODEXP 预编译，可对任意大的整数计算 (base^exp) mod m，使合约能够验证 RSA 签名及其他基于数论的密码学。

## 它解决什么问题？

许多密码学方案（包括 RSA 签名验证）需要对远大于 256 位的数进行模幂运算。EVM 原生的 `EXP` 和 `MULMOD` 只能处理 256 位的字。在 Solidity 中做 2048 位或 4096 位的运算既慢又消耗大量 gas。

EIP-198 增加了一个预编译合约，原生执行大整数模幂运算，其 gas 价格基于计算的实际难度。

## 它如何运作

该预编译位于地址 `0x05`。其输入是三个 32 字节的长度字段，后面跟着三个数：

```
<len(BASE)> <len(EXP)> <len(MOD)> <BASE> <EXP> <MOD>
```

- 每个长度都是大端序的 32 字节整数，表示后面那个值的字节长度。
- 缺失的输入视为在右侧用零填充，多余的字节会被忽略。
- 输出为 `BASE**EXP % MOD`，并填充到与 `MOD` 相同的字节长度。

最初的 gas 公式结合了两部分。第一部分是基于 `max(len(BASE), len(MOD))` 的 `mult_complexity` 项，用来近似 Karatsuba 乘法。第二部分是"调整后的指数长度"（大致是指数的位长度）除以 `GQUADDIVISOR = 20`。将成本与指数位数挂钩，可以让 3 和 65537 这类常见的 RSA 指数保持低成本。

规范指出，也可以借助该预编译来做乘法，方法是 `a*b = ((a+b)^2 - (a-b)^2) / 4`。

## 示例代码

从 Solidity 调用 MODEXP：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

library ModExp {
    function modexp(bytes memory base, bytes memory exp, bytes memory mod)
        internal view returns (bytes memory result)
    {
        bytes memory input = abi.encodePacked(
            uint256(base.length), uint256(exp.length), uint256(mod.length),
            base, exp, mod
        );
        result = new bytes(mod.length);
        bool ok;
        assembly {
            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),
                             add(result, 32), mload(mod))
        }
        require(ok, "modexp failed");
    }
}

// Example: 3^65535 mod 2^255
// ModExp.modexp(hex"03", hex"ffff", abi.encodePacked(uint256(1) << 255));
```

## 需要注意

- 该提案状态为 Final。它在 2017 年的 Byzantium 升级（[EIP-609](/eip-609/)）中上线。
- 本 EIP 中的 gas 公式**已不是当前版本**。[EIP-2565](/eip-2565/) 在 Berlin 升级中重新定价了 MODEXP，[EIP-7883](/eip-7883/) 再次提高了价格。[EIP-7823](/eip-7823/) 将每个输入的长度上限设为 1,024 字节。估算 gas 时请以当前客户端行为为准，而不是本 EIP 的公式。
- `BASE` 的长度为零表示不为它读取任何字节，接下来的字节会被当作指数读取。请谨慎编码长度。
- 输出的长度始终与模数相同，并带有前导零，因此请将结果作为定长字节串进行比较。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-198
