gpt4 book ai didi

rust - crypto::hmac::Hmac::new 中的参数类型不匹配

转载 作者:行者123 更新时间:2023-11-29 08:36:33 28 4
gpt4 key购买 nike

我正在使用 https://github.com/DaGenix/rust-crypto并且有一些奇怪的错误:

extern crate crypto;
use crypto::sha2::{Sha256, Sha384, Sha512};
use crypto::hmac::Hmac;
use crypto::digest::Digest;
use crypto::mac::Mac;


enum MyType {
Type1,
Type2,
Type3
}

//......

let mut hmac = Hmac::new(match myType {
MyType::Type1 => Sha256::new(),
MyType::Type2 => Sha384::new(),
MyType::Type3 => Sha512::new()
}, my_secret.to_string().as_bytes()
);

错误是:

error: match arms have incompatible types:
expected `crypto::sha2::Sha256`,
found `crypto::sha2::Sha384`
(expected struct `crypto::sha2::Sha256`,
found struct `crypto::sha2::Sha384`) [E0308]
let mut hmac = Hmac::new(match algorithm {
MyType::Type1 => Sha256::new(),
MyType::Type2 => Sha384::new(),
MyType::Type3 => Sha512::new(),
_ => panic!()
}, secret.to_string().as_bytes()
note: match arm with an incompatible type
MyType::Type2 => Sha384::new(),
^~~~~~~~~~~~~
help: methods from traits can only be called if the trait is implemented and in scope; the following traits define a method `input`, perhaps you need to implement one of them:
help: candidate #1: `crypto::cryptoutil::FixedBuffer`
help: candidate #2: `crypto::digest::Digest`
help: candidate #3: `crypto::mac::Mac`
help: methods from traits can only be called if the trait is implemented and in scope; the following traits define a method `result`, perhaps you need to implement one of them:
help: candidate #1: `crypto::digest::Digest`
help: candidate #2: `crypto::mac::Mac`

这是为什么呢? Sha256::new()Sha384::new()Sha512::new() 的类型不一样吗?

最佳答案

Doesn't Sha256::new() have the same type as Sha384::new() and Sha512::new()?

没有。如果您查看源代码,它们非常明显是不同的类型,不要介意编译器告诉您它们是不同的类型。

不仅如此,您还试图在单个表达式中创建三种不同类型的 Hmac 之一,这也是不可能的。如果您查看源代码中的定义,您会看到

impl <D: Digest> Hmac<D> {
// ...
pub fn new(mut digest: D, key: &[u8]) -> Hmac<D> {
// ...
}
// ...
}

也就是说,每种可能的 Digest 类型都有不同的 Hmac 类型。

您需要通过某种动态调度才能使其正常工作。例如:

let (hmac_sha256, hmac_sha384, hmac_sha512);
let mac: &mut crypto::mac::Mac = match myType {
MyType::Type1 => {
hmac_sha256 = Hmac::new(Sha256::new(), my_secret.to_string().as_bytes();
&mut hmac_sha256 as &mut crypto::mac::Mac
},
// ...
};

或者如果引用不起作用,您可以使用 Boxes。

关于rust - crypto::hmac::Hmac::new 中的参数类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337381/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com