说明
以太坊有一个personal_hash的服务,可以对任意消息进行签名,但,调用这个服务会通过网络传递私钥,不安全,下面说明如何离线实现,并给出rust代码。
输入:消息,私钥
处理步骤:
1. 消息拼装
- 在消息前面加上
"\u{19}Ethereum Signed Message:\n"
,再加上消息长度字符串,再拼接消息
2. hash值计算
使用Keccak256对拼装的消息计算Hash值
3. 签名
使用私钥,对Hash值进行签名,签名结果一共65个字节,分成3个部分
- r,1 到 32 字节
- s,33到 64 字节
- 第 65 字节
对65个字节的值加上27,对应下文代码into_electrum
。
4. 拼装成JSON格式
{
"address":"地址",
"msg":"消息",
"sig":"0x...",
"version":"3",
"signer":"..."
}
下面是完整的Rust代码实现。
use parity_crypto::publickey::{sign, Secret, Signature};
use crypto::sha3::Sha3Mode::Keccak256;
use crypto::sha3::Sha3;
use crypto::digest::Digest;
use rustc_serialize::hex::ToHex;
pub fn personal_hash(message: &[u8]) -> String {
let mut prefix = String::from("\u{19}Ethereum Signed Message:\n");
let length = message.len().to_string();
prefix += &length;
let mut data = prefix.into_bytes();
data.extend(message.iter());
let mut keccak256 = Sha3::keccak256();
keccak256.input(data.as_slice());
keccak256.result_str()
}
fn personal_sign(message: &str, private_key: &str, address: &str) -> String {
let hash = personal_hash(message.as_bytes());
let msg = hash.parse().unwrap();
let secret = Secret::copy_from_str(private_key).unwrap();
let signature_wrap = sign(&secret, &msg);
let signature = signature_wrap.unwrap().into_electrum().to_hex();
format!(r#"{{"address":"{}",
"msg":"{}",
"sig":"0x{}",
"version":"3",
"signer":"wallet_connect"}}
"#, address, message, signature)
}
fn main() {
let privatey_key_in_hex = "5678123456781234567812345678123456781234567812345678123456781234";
let message = "yanggaofeng";
let address = "0x27ea18dfa8269bb88f03f4cf3d5674a97284a87b";
println!("{}", personal_sign(message, privatey_key_in_hex, address));
}