在Linux中使用OpenSSL进行密钥交换通常涉及非对称加密算法(如RSA、ECDH等)来安全地协商共享密钥。以下是常见场景和操作步骤:
生成RSA密钥对(接收方操作):
# 生成私钥
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
# 提取公钥
openssl rsa -pubout -in private_key.pem -out public_key.pem
发送方加密对称密钥:
# 生成一个随机的AES密钥(32字节=256位)
openssl rand -hex 32 > symmetric_key.txt
# 用接收方的公钥加密该密钥
openssl pkeyutl -encrypt -pubin -inkey public_key.pem -in symmetric_key.txt -out encrypted_key.bin
接收方解密对称密钥:
openssl pkeyutl -decrypt -inkey private_key.pem -in encrypted_key.bin -out decrypted_key.txt
双方生成ECDH密钥对:
# 生成私钥(P-256椭圆曲线)
openssl genpkey -algorithm EC -out ec_private.pem -pkeyopt ec_paramgen_curve:P-256
# 提取公钥
openssl pkey -pubout -in ec_private.pem -out ec_public.pem
双方交换公钥后计算共享密钥:
# 假设对方公钥为peer_public.pem,计算共享密钥
openssl pkeyutl -derive -inkey ec_private.pem -peerkey peer_public.pem -out shared_secret.bin
# 将共享密钥转换为十六进制查看
xxd -p shared_secret.bin
后续步骤:使用HKDF等算法从共享密钥派生实际加密密钥。
在TLS通信中,密钥交换自动完成。以下是模拟服务端/客户端的密钥交换:
# 服务端(启用ECDHE)
openssl s_server -cert server.crt -key server.key -cipher ECDHE-RSA-AES256-GCM-SHA384 -www
# 客户端连接
openssl s_client -connect localhost:4433
ECDHE
自动完成密钥交换。bash
openssl s_client -connect example.com:443 -tls1_3 -ciphersuites TLS_AES_256_GCM_SHA384 -status
bash
openssl s_client -debug -connect example.com:443
通过以上方法,可以灵活实现安全密钥交换。实际应用中建议结合TLS协议(如1.3版本)获得最佳安全性。