工具
Web 开发
Web 服务
OpenSSL 加解密
用 openssl 工具加解密字符串、文件和文件夹。
基础用法
用 openssl enc
加密字符串:
$ echo 'Nice to meet you.' | openssl enc -aes-256-cbc -a
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
U2FsdGVkX1/VitYRcVenXdZmPHuseoq9Tx1yAps/g0680udvVAg6lztpMED6obkK
-a
(或 -base64
)表示用 base64 编码输出,否则会输出二进制数据。
以上会让两次输入密码。
-d
解密字符串:
$ echo 'U2FsdGVkX1+1H6Q7NKSQhJStKjTb06TR5yGDVHAdDXUyxx+vE1+VLGfuBuYPOq0Z' | openssl enc -aes-256-cbc -a -d
enter aes-256-cbc decryption password:
Nice to meet you.
以上需要输入密码才能解密。
保存为加密文件
加密后保存到文件:
$ echo 'Nice to meet you.' | openssl enc -aes-256-cbc > nice.dat
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
可查看文件:
$ file nice.dat
nice.dat: openssl enc'd data with salted password
解密文件:
$ openssl enc -aes-256-cbc -d -in nice.dat
enter aes-256-cbc decryption password:
Nice to meet you.
加解密文件
创建一个测试文件:
$ echo 'Nice to meet you.' > nice.txt
-in
指定待加密文件,-out
输出到文件:
$ openssl enc -aes-256-cbc -in nice.txt -out nice.dat
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
解密文件:
$ openssl enc -aes-256-cbc -d -in nice.dat -out dec-nice.txt
enter aes-256-cbc decryption password:
查看解密后的文件:
$ cat dec-nice.txt
Nice to meet you.
加解密文件夹
创建测试文件夹:
$ mkdir nicefiles
$ mv nice.txt dec-nice.txt nicefiles/
加密文件夹:
$ tar cz nicefiles/ | openssl enc -aes-256-cbc -out nice.tar.gz.dat
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
解压加密文件夹:
$ mv nicefiles/ old-nicefiles
$ openssl enc -aes-256-cbc -d -in nice.tar.gz.dat | tar xz
enter aes-256-cbc decryption password:
用公钥/私钥加解密
生成私钥:
$ openssl genrsa -des3 -out private.pem 2048
以上需要输入密码。
生成公钥:
$ openssl rsa -in private.pem -out public.pem -outform PEM -pubout
Enter pass phrase for private.pem:
writing RSA key
-pubout
表示指定输出公钥。
加解密字符串
用公钥加密字符串:
$ echo 'Nice to meet you.' | openssl rsautl -encrypt -inkey public.pem -pubin | base64
...
以上 -pubin
表示输入的是 RSA 公钥文件,因默认输入是私钥文件。
用私钥解密:
$ echo '...' | base64 -D| openssl rsautl -decrypt -inkey private.pem
加解密文件
用公钥加密文件:
$ openssl rsautl -encrypt -inkey public.pem -pubin -in nice.txt -out nice.dat
用私钥解密文件:
$ openssl rsautl -decrypt -inkey private.pem -in nice.dat -out dec-nice.txt
Enter pass phrase for private.pem: