fn hex(bytes: &[u8]) -> String { bytes.iter().fold("".to_owned(), |s, b| format!("{}{:x}", s, b)) } fn main(){ let s = hex(&[10, 32, 123]); println!("{:?}", s); }
$ ./main
“a207b”
これを秘密鍵、公開鍵のコードに実装します。
use hex_literal::hex; use k256::{ecdsa::{SigningKey, Signature, signature::Signer, signature::Verifier, VerifyingKey}}; fn hex(bytes: &[u8]) -> String { bytes.iter().fold("".to_owned(), |s, b| format!("{}{:x}", s, b)) } fn main(){ let private_key: SigningKey = SigningKey::from_bytes(&hex!( "DCDFF4B7CA287CC7BD30ECAEF0622265DB4E14054E12954225457C3A6B84F135" ).into()).unwrap(); let public_key: &VerifyingKey = private_key.verifying_key(); let message = b"hello, world"; let signature: Signature = private_key.sign(message); let verified = public_key.verify(message, &signature).is_ok(); println!("private key: {:X?}", hex(&private_key.to_bytes())); println!("public key: {:X?}", hex(&public_key.to_encoded_point(false).to_bytes())); println!("message: {:X?}", message); println!("Signature: {:X?}", hex(&signature.to_bytes())); println!("verified: {:X?}", verified); }
private key: “dcdff4b7ca287cc7bd30ecaef0622265db4e1454e12954225457c3a6b84f135”
public key: “4bac6cb0f4ad6397752c3d73b88c5c86e3d88ac695118494a1732e2abd16c76acad3d6586c37c8db7e69c2f812f99275198936957d72c38d71981991123”
message: [68, 65, 6C, 6C, 6F, 2C, 20, 77, 6F, 72, 6C, 64]
Signature: “f690afffd24623627bfa97996873a6a9d8ca8e9bb7ab6ad269c929453b42985573cdc4c05b8522224065757fef6c181c8418ffd3debdab4be22a73b2e5b6ce”
verified: true
うん、いい感じ