4

I am fairly new to Rust but I am trying to build a command line tool similar to OpenSSL written in Rust.

I am trying to implement a digital signature using Rust Crypto and the ecdsa crate. I already have a hashed file and my next steps would be as followed:

  • Generate private and public key
  • encrypt the hash value with the private key (that would be my signature)

Now I am not sure how to use the ecdsa crate. How can I generate a private key?

Lachr
  • 63
  • 8

1 Answers1

2

An example of generation of the private key can be found here in the documentation. It's a bit hidden because the key pair generation is specific to the curve used:

use p256::{
    ecdsa::{SigningKey, Signature, signature::Signer},
};
use rand_core::OsRng; // requires 'getrandom' feature

// Signing
let signing_key = SigningKey::random(&mut OsRng); // Serialize with `::to_bytes()`

Do note that ECDSA works a bit different from RSA, so you do not "encrypt" the hash with the private key (actually, that's a bad description for RSA as well). You'd use a signer instead, and the hashing of the message is generally considered part of that. The example also shows how to do this.

The documentation is pretty horrible, it seems SHA-256 is used as hashing underneath but that's not on this page. In the source code I found:

impl ecdsa_core::hazmat::DigestPrimitive for NistP256 {
    type Digest = sha2::Sha256;
}

So I hope that Rust users do understand how to set / unset a hash given that.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Thanks for your help! I agree the documentation is pretty horrible. I am trying to implement it like in the example, but it wont let me import the SigningKey `unresolved import p256::ecdsa::SigningKey` . The docs say _This example requires the ecdsa Cargo feature is enabled_ so maybe that is missing? I tried to put this in my Cargo.toml under the features section: `ecdsa = [] ` but that wont work. Any tips? – Lachr Apr 09 '21 at 16:13
  • 2
    @Lachr the p256 dependency in your cargo.toml should look like this: `p256 = { version = "0.7.2", features = ["ecdsa"] }`. The `[features]` section you tried is for the features of the *current* crate, not its dependents'. – kmdreko Apr 13 '21 at 04:58