我正在尝试创建一个简单的加密货币,我使用 bip39 和 crypto 模块在 Node.JS 中创建了一个钱包。该计划是能够创建一个钱包,以便脚本生成一个随机助记词,并从中生成私钥和公钥。相同的助记词应该产生相同的密钥对,而不同的助记词应该产生不同的密钥对。
由于某种原因,如果生成后我尝试从与之前相同的助记符生成相同的私钥/公钥,则会返回不同的密钥对。我刚刚学习密码学,我可能做错了一些事情。无论如何,提前感谢您的帮助,这是我的代码:
function generateRandomMnemonic() {
// Generate a random 256-bit (32-byte) entropy
const entropy = crypto.randomBytes(32);
// Convert the entropy to a mnemonic phrase
const mnemonic = bip39.entropyToMnemonic(entropy);
return mnemonic;
}
function generateKeyPairFromMnemonic(mnemonic) {
// Derive a seed from the mnemonic phrase
const seed = bip39.mnemonicToSeedSync(mnemonic);
// Generate key pair from the seed
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
},
seed,
});
return keyPair;
}
function getAddress(publicKey) {
const addressHash = crypto.createHash('sha256').update(publicKey).digest('hex').slice(-30);
return `csc.${addressHash}`
}
function signTransaction(transaction, privateKey) {
const dataToSign = JSON.stringify(transaction);
// Sign the data correctly
const sign = crypto.createSign('sha256');
sign.update(JSON.stringify(transaction));
const signature = sign.sign(privateKey, 'base64');
return signature;
}
生成钱包的代码:
app.get('/signup', async (req, res) => {
const mnemonic = generateRandomMnemonic();
const keypair = generateKeyPairFromMnemonic(mnemonic);
const address = getAddress(keypair.publicKey);
console.log("Generated address: ", address);
req.session.mnemonic = mnemonic;
req.session.address = address;
res.render(DIRECTORY + "/register.html", {mnemonic:mnemonic});
});
app.get('/signin', async (req, res) => {
res.render(DIRECTORY + "/login.html");
});
app.post('/signin', async (req, res) => {
let mnemonic = req.body.mnemonic;
const keypair = generateKeyPairFromMnemonic(mnemonic);
const address = getAddress(keypair.publicKey);
req.session.mnemonic = mnemonic;
req.session.address = address;
res.redirect('/success');
});
我应该使用椭圆曲线吗?
const bip39 = require('bip39');
const crypto = require('crypto');
const elliptic = require('elliptic');
function generateKeyPairFromMnemonic(mnemonic) {
// Derive a seed from the mnemonic phrase
const seed = bip39.mnemonicToSeedSync(mnemonic);
// Create an elliptic curve key pair
const ec = new elliptic.ec('secp256k1');
const keyPair = ec.genKeyPair({
entropy: seed.slice(0, 32), // Take the first 32 bytes of the seed for entropy
});
return {
privateKey: keyPair.getPrivate('hex'),
publicKey: keyPair.getPublic('hex'),
};
}
// Example usage
const mnemonic = 'your twelve word mnemonic phrase';
const keyPair = generateKeyPairFromMnemonic(mnemonic);
console.log('Private Key:', keyPair.privateKey);
console.log('Public Key:', keyPair.publicKey);