您需要使用 Rust 对文件进行签名。我正在尝试这样做:
extern crate openssl;
use std::env;
use std::string::String;
use std::fs::File;
use std::path::Path; use openssl::pkey::PKey;
use openssl::sign::Signer; use openssl::hash::MessageDigest;
use std::io::Write;
use std::io::Read;
fn sign(file: String, key: String, sigfile: String) {
if Path::new(&file).exists() {
if Path::new(&key).exists() {
let kd = File::open(key).expect("File not found!");
let mut strdata = String::new();
kd.read_to_string(&mut strdata).expect("Error reading of file!");
let data: &[u8] = strdata.as_bytes();
let pkd = File::open(key).expect("Private key not found!");
let mut pkdata = String::new();
pkd.read_to_string(&mut pkdata).expect("Error reading of private key!");
let pkb: Vec<u8> = pkdata.as_bytes().to_vec();
let privk = PKey::private_key_from_pem(&pkb);
let mut signer = Signer::new(MessageDigest::sha512(), &privk).unwrap();
signer.update(data).unwrap();
let signature = signer.sign_to_vec().unwrap();
let sigdump = signature.as_slice();
let fd = match File::create(sigfile) {
Err(why) => panic!("Cant open signature file {}: {}", sigfile, why),
Ok(fd) => fd
};
fd.write_all(&sigdump);
} else {
eprintln!("Keyfile {} is not found!", key);
panic!();
}
} else {
eprintln!("File {} is not found!", file);
panic!();
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() == 4 {
sign(args[1].clone(), args[2].clone(), args[3].clone());
} else {
println!("Usage: signfile (file) (private.key) (out.sig)");
}
}
build的时候报错:
~/signfile $ cargo build
error[E0308]: mismatched types
--> src/main.rs:26:61
|
26 | let mut signer = Signer::new(MessageDigest::sha512(), &privk).unwrap();
| ----------- ^^^^^^ expected `&PKeyRef<_>`, found `&Result<PKey<...>, ...>`
| |
| arguments to this function are incorrect
|
= note: expected reference `&PKeyRef<_>`
found reference `&Result<PKey<Private>, ErrorStack>`
note: associated function defined here
--> /root/.cargo/registry/src/github.com-1ecc6299db9ec823/openssl-0.10.46/src/sign.rs:142:12
|
142 | pub fn new<T>(type_: MessageDigest, pkey: &'a PKeyRef<T>) -> Result<Signer<'a>, Erro...
| ^^^
For more information about this error, try `rustc --explain E0308`.
Vo1,我对 Rust 仍然知之甚少,v2,在我在 Internet 上找到的所有示例中,密钥都是在一个可执行文件中生成的,并且文件会立即使用它们进行签名。但问题是我从文件中获取了(私钥)密钥,但我不知道如何将Result<PKey<...>>
其转换为...PKeyRef<...>
看 - 你
expect
到处都写着 -s,如果操作失败就会恐慌,并且在从中提取私钥的行中PEM
,既没有expect
, 也没有unwrap
:let privk = PKey::private_key_from_pem(&pkb);
把它改成类似的东西
并在通话时,
pkey
替换而不是pkey.as_ref()
,因为您需要类型PKeyRef
修复这个错误后,rustc 会给你更多关于使用移动值和对非可变值调用非常量方法的通知。您可以像这样修复它们:
编译、运行,但
openssl
无法验证签名。