在Linux系统中,使用OpenSSL加密文件有多种方法。以下是两种常用的方法:
enc
命令进行对称加密生成密钥:
openssl enc -aes-256-cbc -a -salt -out encrypted_file.enc -pass pass:your_password input_file
-aes-256-cbc
:指定使用AES-256-CBC加密算法。-a
:以ASCII格式输出密钥和IV(初始化向量)。-salt
:为加密添加盐值,增加安全性。-out encrypted_file.enc
:指定输出加密文件的名称。-pass pass:your_password
:设置加密密码。input_file
:要加密的文件。解密文件:
openssl enc -d -aes-256-cbc -a -in encrypted_file.enc -out decrypted_file -pass pass:your_password
-d
:表示解密操作。-in encrypted_file.enc
:指定要解密的文件。-out decrypted_file
:指定输出解密文件的名称。-pass pass:your_password
:设置解密密码。pkeyutl
命令进行非对称加密生成密钥对:
openssl genpkey -algorithm RSA -out rsa_key.pem -aes256
-algorithm RSA
:指定生成RSA密钥对。-out rsa_key.pem
:指定输出密钥文件的名称。-aes256
:为私钥设置AES-256加密。提取公钥:
openssl rsa -pubout -in rsa_key.pem -out rsa_pubkey.pem
-pubout
:表示提取公钥。-in rsa_key.pem
:指定输入私钥文件。-out rsa_pubkey.pem
:指定输出公钥文件的名称。使用公钥加密文件:
openssl pkeyutl -encrypt -in input_file -out encrypted_file.enc -pubin -inkey rsa_pubkey.pem
-encrypt
:表示加密操作。-in input_file
:指定要加密的文件。-out encrypted_file.enc
:指定输出加密文件的名称。-pubin
:表示使用公钥进行加密。-inkey rsa_pubkey.pem
:指定输入公钥文件。使用私钥解密文件:
openssl pkeyutl -decrypt -in encrypted_file.enc -out decrypted_file -inkey rsa_key.pem
-decrypt
:表示解密操作。-in encrypted_file.enc
:指定要解密的文件。-out decrypted_file
:指定输出解密文件的名称。-inkey rsa_key.pem
:指定输入私钥文件。请注意,使用非对称加密时,公钥可以公开,而私钥必须严格保密。对称加密则使用相同的密钥进行加密和解密,因此需要妥善保管密钥。