BASH
Securely Download and Verify File Integrity with Bash
Ensure the integrity and authenticity of downloaded files in Bash by fetching them securely with `curl` over HTTPS and verifying their SHA256 checksum against a known, trusted value.
#!/bin/bash
URL="https://raw.githubusercontent.com/username/repo/branch/file.txt"
EXPECTED_SHA256="a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890"
LOCAL_FILE="downloaded_file.txt"
# Ensure curl is available
if ! command -v curl &> /dev/null
then
echo "Error: curl is not installed. Please install it to proceed." >&2
exit 1
fi
# Download the file securely
echo "Downloading $URL..."
if curl -sSL -o "$LOCAL_FILE" "$URL"; then
echo "Download successful. Verifying integrity..."
else
echo "Error: Failed to download $URL" >&2
exit 1
fi
# Verify the file's SHA256 checksum
if ! command -v sha256sum &> /dev/null
then
echo "Error: sha256sum is not installed. Cannot verify file integrity." >&2
rm "$LOCAL_FILE" # Clean up potentially compromised file
exit 1
fi
ACTUAL_SHA256=$(sha256sum "$LOCAL_FILE" | awk '{print $1}')
if [ "$ACTUAL_SHA256" = "$EXPECTED_SHA256" ]; then
echo "Integrity check passed: File is authentic."
echo "File saved to $LOCAL_FILE"
else
echo "Error: Integrity check failed! SHA256 mismatch." >&2
echo " Expected: $EXPECTED_SHA256" >&2
echo " Actual: $ACTUAL_SHA256" >&2
rm "$LOCAL_FILE" # Remove the potentially corrupted/malicious file
exit 1
fi
How it works: This snippet demonstrates how to securely download a file and verify its integrity using cryptographic checksums. `curl -sSL -o` is used to download the file silently, follow redirects, and save it to a specified local path. After download, `sha256sum` calculates the file's hash, which is then compared against a predefined `EXPECTED_SHA256` value. This ensures that the downloaded file has not been tampered with and is the exact version expected, crucial for secure deployments and dependency management.