对称及非对称加解密示例

发布于 2023-05-21  17 次阅读


非对称加密方法及示例

1、 创建一对公钥和私钥

# 私钥
openssl genpkey -algorithm RSA -out private_key.pem
# 公钥
openssl rsa -pubout -in private_key.pem -out public_key.pem

2、通过公钥加密

# 公钥加密的信息,只有私钥才能解密
echo "Hello, World!" > plaintext.txt
openssl rsautl -encrypt -pubin -inkey public_key.pem -in plaintext.txt -out ciphertext.bin

3、通过私钥解密

openssl rsautl -decrypt -inkey private_key.pem -in ciphertext.bin -out decrypted.txt

同理,通过私钥加密的内容,通过公钥解密

对称加密示例

1、生成一个des秘钥

openssl rand -hex 8 > des_key.txt

2、数据加密

echo "Hello, World!" > plaintext.txt
openssl enc -des-ecb -e -K $(cat des_key.txt) -in plaintext.txt -out ciphertext.bin

3、数据解密

openssl enc -des-ecb -d -K $(cat des_key.txt) -in ciphertext.bin -out decrypted.txt