Mac OS与Linux下OpenSSL哈希重算差异:HMAC命令适配问题
Ah, I've run into this exact issue before! The problem boils down to the outdated OpenSSL version that comes pre-installed on macOS—Apple ships an older 0.9.8-based release, while the -mac and -macopt flags you're using were introduced in OpenSSL 1.0.0+. Here are two solid solutions to get your HMAC-SHA256 working:
Option 1: Install a modern OpenSSL version with Homebrew
This is the most straightforward long-term fix, as it gives you access to all the latest OpenSSL features:
- First, install Homebrew if you haven't already (skip this step if you have it):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - Install the latest OpenSSL:
brew install openssl - By default, macOS will still use the system's old OpenSSL when you run
openssl. To use the new version, either:- Call it directly with its full path:
/usr/local/opt/openssl/bin/openssl dgst -sha256 -mac HMAC -macopt hexkey:xxxx - Or add the modern OpenSSL binary path to your shell's PATH (persistently):
For zsh (default on macOS Catalina+):
For bash:echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.zshrc source ~/.zshrcecho 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile source ~/.bash_profile
- Call it directly with its full path:
Option 2: Use the legacy HMAC flag with hex-to-binary conversion
If you don't want to install a new OpenSSL version, you can use the older -hmac flag supported by the system's OpenSSL. The catch is you need to convert your hex key to binary first (since -hmac expects a raw binary key):
- For string input:
echo -n "your_input_string" | openssl dgst -sha256 -hmac "$(echo -n xxxx | xxd -r -p)" - For file input:
Theopenssl dgst -sha256 -hmac "$(echo -n xxxx | xxd -r -p)" filenamexxd -r -pcommand takes your hex key (xxxx) and converts it into the raw binary data required for the HMAC calculation.
Quick verification
To make sure this works, test with a sample hex key and input. For example, using hex key deadbeef and input test:
- Modern command:
echo -n "test" | openssl dgst -sha256 -mac HMAC -macopt hexkey:deadbeef - Legacy command:
echo -n "test" | openssl dgst -sha256 -hmac "$(echo -n deadbeef | xxd -r -p)"
Both should output the same hash: HMAC-SHA256(stdin)= 7f4a4932d9b946f298d48582f7c492d59b468e08f64029990964b2020e2e7fd8
内容的提问来源于stack exchange,提问作者user868543

