Skip to main content

tibba_crypto/
lib.rs

1// Copyright 2026 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use snafu::Snafu;
16use tibba_error::Error as BaseError;
17
18#[derive(Debug, Snafu)]
19pub enum Error {
20    /// 封装 hmac crate 的 `InvalidLength`,使调用方可直接使用 `.context(HmacSha256Snafu)`。
21    #[snafu(display("hmac sha256 error: {source}"))]
22    HmacSha256 { source: hmac::digest::InvalidLength },
23
24    /// 密钥列表为空,无法执行签名或验签操作。
25    #[snafu(display("key grip empty"))]
26    KeyGripEmpty,
27
28    /// Argon2 哈希计算失败(参数异常,正常不会发生)。
29    #[snafu(display("argon2 hash error: {source}"))]
30    Argon2Hash {
31        source: argon2::password_hash::Error,
32    },
33
34    /// 解析已存储的 Argon2 PHC 串失败(库中哈希损坏 / 校验阶段内部异常)。
35    #[snafu(display("argon2 parse error: {source}"))]
36    Argon2Parse {
37        source: argon2::password_hash::Error,
38    },
39}
40
41impl From<Error> for BaseError {
42    fn from(val: Error) -> Self {
43        let err = match val {
44            Error::HmacSha256 { source } => BaseError::new(source).with_sub_category("hmac_sha256"),
45            Error::KeyGripEmpty => BaseError::new("key grip empty")
46                .with_sub_category("key_grip")
47                .with_status(500)
48                .with_exception(true),
49            Error::Argon2Hash { source } => BaseError::new(source)
50                .with_sub_category("argon2_hash")
51                .with_status(500)
52                .with_exception(true),
53            Error::Argon2Parse { source } => BaseError::new(source)
54                .with_sub_category("argon2_parse")
55                .with_status(500)
56                .with_exception(true),
57        };
58        err.with_category("crypto")
59    }
60}
61
62mod key_grip;
63mod password;
64
65pub use key_grip::*;
66pub use password::*;