I am trying to do a signature in rust(v1.77.1) with ring, followed by the official document https://docs.rs/ring/latest/ring/signature/index.html like this, this is the main.rs
:
use ring::{rand, rsa, signature};
fn main() {
let result = sign_and_verify_rsa();
match result {
Ok(data) => {
print!("{:?}", data);
}
Err(e) => {
print!("{:?}", e)
}
}
}
fn sign_and_verify_rsa() -> Result<(), MyError> {
// Create an RSA keypair from the DER-encoded bytes. This example uses
// a 2048-bit key, but larger keys are also supported.
let private_key_der = "-----BEGIN PRIVATE KEY-----
MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAv2YlvorgVCb5FMzf
rzP7xkYGh2FIm4J34GIsTikZ9rWMtSJG3a2YD/s5QgFveYsxv1GnixkxqGsKYVsj
RJQl/QIDAQABAkBGxlTqspvlQkwUvvVv6f8OAFLluLmKl6IQXP0ZIeWx7iiLDM6d
WBE8hblDr12KYpWuNLn3b1X+HCDvMfHbbiiBAiEA4rVYZhozGKsr93p0xcyflwj+
/Bnx7+16YeiNgs76vs0CIQDYIObpFg7eaxhsVhFfLt+PohQhhWEsP+SlkD7LezKj
8QIhALADX8iV2snyS8Zueq7/eYBH6cBNXHuNAxF0/jlq/V6ZAiBeERPvZvZZv+sF
XAB7mP8cmMKCRHcitzxhAwMRtTE5QQIgCcnXlJ+Odfzy/vJr3BPlDWXJAZBHok54
UwWW2C74w/Y=
-----END PRIVATE KEY-----".as_bytes();
let key_pair = rsa::KeyPair::from_pkcs8(&private_key_der).map_err(|_| MyError::BadPrivateKey)?;
// Sign the message "hello, world", using PKCS#1 v1.5 padding and the
// SHA256 digest algorithm.
const MESSAGE: &'static [u8] = b"hello, world";
let rng = rand::SystemRandom::new();
let mut signature = vec![0; key_pair.public().modulus_len()];
key_pair
.sign(&signature::RSA_PKCS1_SHA256, &rng, MESSAGE, &mut signature)
.map_err(|_| MyError::OOM)?;
let pub_key = "-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL9mJb6K4FQm+RTM368z+8ZGBodhSJuC
d+BiLE4pGfa1jLUiRt2tmA/7OUIBb3mLMb9Rp4sZMahrCmFbI0SUJf0CAwEAAQ==
-----END PUBLIC KEY-----".as_bytes();
// Verify the signature.
let public_key =
signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, pub_key);
public_key
.verify(MESSAGE, &signature)
.map_err(|_| MyError::BadSignature)
}
#[derive(Debug)]
enum MyError {
BadPrivateKey,
OOM,
BadSignature,
}
this code shows:
BadPrivateKey
the private key format is pkcs8, am I missing something? what should I do to make the signature process works? This is the Cargo.toml
:
[dependencies]
rsa = "0.5"
ring = "0.17.8"