RustCrypto / RSA

RSA implementation in pure Rust
Apache License 2.0
557 stars 154 forks source link

How to verify the signature with the public key and new api? #416

Closed tk-zc closed 8 months ago

tk-zc commented 8 months ago

Can you provide an example of verifying a signature with the public key of RSA 9.0?

tarcieri commented 8 months ago

What type of signature are you interested in? PKCS#1 v1.5 or PSS?

There are code examples for each in the rustdoc:

tk-zc commented 8 months ago

@tarcieri

What type of signature are you interested in? PKCS#1 v1.5 or PSS?

There are code examples for each in the rustdoc:

How to use the RsaPublicKey interface below to verify signatures using public keys? How are the three parameters scheme, hashed, and sig defined?

https://docs.rs/rsa/latest/rsa/struct.RsaPublicKey.html#method.verify

pub fn verify<S: SignatureScheme>(
    &self,
    scheme: S,
    hashed: &[u8],
    sig: &[u8]
) -> Result<()>
Verify a signed message.

hashed must be the result of hashing the input using the hashing function passed in through hash.

If the message is valid Ok(()) is returned, otherwise an Err indicating failure.

Using the following code to sign data using a private key, now I want to verify the obtained signature using a public key. What is the next step?

    let mut rng = rand::thread_rng();

    let bits = 2048;
    let private_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");

    let public_key = RsaPublicKey::from(&private_key);

    let signing_key = SigningKey::<Sha256>::new(private_key);
    let verifying_key = signing_key.verifying_key();

    // Sign
    let data = b"hello world";
    let signature = signing_key.sign_with_rng(&mut rng, data);
    assert_ne!(signature.to_bytes().as_ref(), data.as_slice());

    println!("{:?}", signature.to_string());
tarcieri commented 8 months ago

Is there some reason you can't use the verifying_key you have bound in the example?

In order to use RsaPublicKey::verify you need to pick a SignatureScheme, However, your code example lacks use statements that correspond to the types so I can't tell which signature scheme you want to use.

tk-zc commented 8 months ago

@tarcieri I found a lot of test code in the source code, and now the problem has been resolved. Thank you. https://docs.rs/rsa/latest/src/rsa/pkcs1v15.rs.html#560