C++ JAVA源码 HMAC计算 openssl 消息认证码计算 https消息防篡改 通信安全

签名和验签

把所有消息按顺序合并成一条信息,对这个信息用密钥进行签名。
签名信息通过 HTTP 头 Sign 传递,没有携带签名或者签名验证不通过的请求,将会被认为异常请求,并返回相应 code 码。

校验方法:根据 http请求的原始 Body 及请求头内参数等所有消息按顺序合并成一条信息 进行签名生成 sign。对自生成的 sign 与 传过来的Sign 做对比,相同则校验通过,反之则校验失败。

在线工具 https://www.lddgo.net/encrypt/hmac

在这里插入图片描述

在这里插入图片描述

C++代码验证

要在 C++ 中计算 HMAC-SHA256 的结果并将其转换为 Base64 输出,你可以结合 OpenSSL 库进行 HMAC 计算,并使用 Base64 编码函数来转换结果。下面是一个示例代码:

#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <iostream>
#include <string>

// Convert HMAC result to Base64
std::string base64_encode(const unsigned char* buffer, size_t length) {
    BIO* bio = BIO_new(BIO_f_base64());
    BIO* mem = BIO_new(BIO_s_mem());
    bio = BIO_push(bio, mem);

    // Do not use newlines to flush buffer
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
    BIO_write(bio, buffer, length);
    BIO_flush(bio);

    BUF_MEM* mem_ptr;
    BIO_get_mem_ptr(bio, &mem_ptr);

    std::string base64_result(mem_ptr->data, mem_ptr->length);
    BIO_free_all(bio);

    return base64_result;
}

// Compute HMAC-SHA256 and encode result in Base64
std::string hmac_sha256_base64(const std::string& key, const std::string& message) {
    unsigned char* digest;
    unsigned int digest_len;

    digest = HMAC(EVP_sha256(),
                  key.c_str(), key.length(),
                  reinterpret_cast<const unsigned char*>(message.c_str()), message.length(),
                  nullptr, &digest_len);

    // Convert the HMAC digest to Base64
    return base64_encode(digest, digest_len);
}

int main() {
    std::string key = "your-key";        // Replace with your key
    std::string message = "your-message";  // Replace with your message

    std::string hmac_base64 = hmac_sha256_base64(key, message);

    std::cout << "HMAC-SHA256 (Base64): " << hmac_base64 << std::endl;

    return 0;
}

编译与运行

  1. 编译

    g++ -o hmac_tool hmac_tool.cpp -lssl -lcrypto
    
  2. 运行

    ./hmac_tool
    

代码解释:

  • HMAC Calculation: 使用 HMAC 函数来计算 HMAC-SHA256,结果保存在 digest 中。
  • Base64 编码: 使用 OpenSSL 的 BIO 来进行 Base64 编码。BIO 是 OpenSSL 中用于处理数据流的结构。
  • BIO_f_base64BIO_s_mem: 分别用于创建 Base64 过滤器和内存 BIO。BIO_push 将它们连接在一起,使数据能够经过 Base64 编码后存储在内存中。
  • BIO_flush: 确保所有数据都已写入 BIO
  • base64_encode 函数: 将 digest 转换为 Base64 字符串并返回。

运行程序后,它将输出 HMAC-SHA256 结果的 Base64 编码版本。

java

public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));

        return Base64.getUrlEncoder().encodeToString(array); //这里不要用urlEncoder,以免c++没有对应的库 对Hmac转base64就行。
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
HMAC算法(Hash-based Message Authentication Code)是一种基于哈希函数和密钥的消息鉴别码算法,常用于网络通信中的身份验证和消息完整性验证。在Java中,可以使用javax.crypto包中的Mac类来实现HMAC算法的计算。 以下是一个示例代码,演示如何使用Java实现HMAC算法的计算: ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class HMACExample { public static void main(String[] args) { try { String message = "Hello World!"; String key = "SecretKey"; String algorithm = "HmacSHA256"; byte[] keyBytes = key.getBytes("UTF-8"); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKeySpec); byte[] messageBytes = message.getBytes("UTF-8"); byte[] signatureBytes = mac.doFinal(messageBytes); String signature = bytesToHex(signatureBytes); System.out.println("HMAC signature: " + signature); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { e.printStackTrace(); } } private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = HEX_ARRAY[v >>> 4]; hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } } ``` 在这个示例中,我们使用HmacSHA256算法计算消息“Hello World!”的HMAC值,使用密钥“SecretKey”。我们首先将密钥转换为字节数组,并使用SecretKeySpec类创建一个密钥规范对象。然后,我们获取一个Mac实例,使用密钥规范对象初始化它。接下来,我们将消息转换为字节数组,并使用Mac实例的doFinal方法计算HMAC值。最后,我们将HMAC值转换为16进制字符串并打印出来。 输出应该类似于以下内容: ``` HMAC signature: F111D6E7F6CE3C3D46C503975D2BC1C0A2B2B1A0C9D9CB0BAA61A60A6CBF8B89 ``` 注意:HMAC算法的安全性取决于密钥的保密性,因此应该谨慎处理密钥。建议使用安全的随机数生成器来生成密钥,并使用安全的存储方式(例如密钥库)来存储密钥。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄人软件

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值