line_bot_sdk_rust/parser/
signature.rs

1/*
2* Copyright 2023 nanato12
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8*     http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17//! Functions for parser
18
19use base64::{engine::general_purpose, Engine as _};
20use hmac::{Hmac, Mac};
21use sha2::Sha256;
22
23/// Signature validator
24/// # Note
25/// The signature in the `x-line-signature` request header must be verified to confirm that the request was sent from the LINE Platform. [\[detail\]](https://developers.line.biz/en/reference/messaging-api/#signature-validation)
26/// # Example
27/// ```
28/// if validate_signature(channel_secret, signature, body) {
29///     // OK
30/// } else {
31///     // NG
32/// }
33/// ```
34pub fn validate_signature(channel_secret: &str, signature: &str, body: &str) -> bool {
35    type HmacSha256 = Hmac<Sha256>;
36
37    let mut mac = HmacSha256::new_from_slice(channel_secret.as_bytes())
38        .expect("HMAC can take key of any size");
39    mac.update(body.as_bytes());
40    let mut buf = String::new();
41    general_purpose::STANDARD.encode_string(mac.finalize().into_bytes(), &mut buf);
42    buf == signature
43}