以太坊私钥如何生成地址

以太坊使用ECDSA生成私钥,使用的曲线是secpk256k1。

私钥长度为32 bytes

公钥由私钥生成,公钥格式一般为SEC1,具体参考SEC 1, Version 2.0, Section 2.3.3. SEC 1 PDF

以太坊地址生成过程:

  1. 由私钥生成公钥
  2. 将公钥序列化为SEC1格式,使用uncompress
  3. 去掉公钥的0x04前缀
  4. 使用keccak256对去掉前缀的公钥进行hash keccak256(public_key[1:])
  5. 取hash结果的后20bytes (后40个字符),即为该私钥的以太坊地址

Rust代码示例:

use secp256k1::{ecdsa::RecoverableSignature, Message, PublicKey, Secp256k1, SecretKey};
use sha3::{Digest, Keccak256};

// generate eth key by secp256k1
let secp = Secp256k1::new();
let private_key_bytes =
	hex::decode("348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709").unwrap();
let secret_key =
	SecretKey::from_slice(&private_key_bytes).expect("32 bytes, within curve order");
println!("private key: 0x{}", hex::encode(secret_key.secret_bytes()));

let public_key = PublicKey::from_secret_key(&secp, &secret_key);
let public_key_bytes = public_key.serialize_uncompressed();
println!("public key: 0x{}", hex::encode(public_key_bytes));

// get address from public key
let hash = Keccak256::digest(&public_key_bytes[1..]); // need to remove the 0x04 prefix
let hash_hex_strng = hex::encode(hash);
println!("keccack256: 0x{}", &hash_hex_strng);
println!(
  "address: 0x{}",
  &hash_hex_strng[hash_hex_strng.len() - 40..]	// get the last 20 bytes of the hash
);

你可能感兴趣的:(密码学,区块链,密码学,rust,安全)