Cómo utilizar OpenSSL para cifrar / descifrar archivos?


Quiero cifrar y descifrar un archivo usando una contraseña.

¿Cómo puedo usar OpenSSL para hacer eso?

Author: jww, 2013-04-17

7 answers

Esta es la respuesta principal a tu pregunta de Google: http://tombuntu.com/index.php/2007/12/12/simple-file-encryption-with-openssl /

Cifrar:

openssl aes-256-cbc -a -salt -in secrets.txt -out secrets.txt.enc

Descifrar:

openssl aes-256-cbc -d -a -in secrets.txt.enc -out secrets.txt.new

Pero esto no hace uso de la infraestructura de clave pública en absoluto, así que un poco como martillar un clavo con un destornillador: -)

 192
Author: Szocske,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-08 04:33:25

Respuesta corta:

Es probable que desee usar gpg en lugar de openssl así que vea "Notas adicionales" al final de esta respuesta. Pero para responder a la pregunta usando openssl:

Para Cifrar:

openssl enc -aes-256-cbc -in un_encrypted.data -out encrypted.data

Para Descifrar:

openssl enc -d -aes-256-cbc -in encrypted.data -out un_encrypted.data

Nota: Se le solicitará una contraseña al cifrar o descifrar.


Respuesta larga:

Su mejor fuente de información para openssl enc probablemente sería: https://www.openssl.org/docs/apps/enc.html

Línea de comandos: openssl enc toma la siguiente forma:

openssl enc -ciphername [-in filename] [-out filename] [-pass arg]
[-e] [-d] [-a/-base64] [-A] [-k password] [-kfile filename] 
[-K key] [-iv IV] [-S salt] [-salt] [-nosalt] [-z] [-md] [-p] [-P] 
[-bufsize number] [-nopad] [-debug] [-none] [-engine id]

Explicación de los parámetros más útiles con respecto a su pregunta:

-e
    Encrypt the input data: this is the default.

-d    
    Decrypt the input data.

-k <password>
    Only use this if you want to pass the password as an argument. 
    Usually you can leave this out and you will be prompted for a 
    password. The password is used to derive the actual key which 
    is used to encrypt your data. Using this parameter is typically
    not considered secure because your password appears in 
    plain-text on the command line and will likely be recorded in 
    bash history.

-kfile <filename>
    Read the password from the first line of <filename> instead of
    from the command line as above.

-a
    base64 process the data. This means that if encryption is taking 
    place the data is base64 encoded after encryption. If decryption 
    is set then the input data is base64 decoded before being 
    decrypted.
    You likely DON'T need to use this. This will likely increase the
    file size for non-text data. Only use this if you need to send 
    data in the form of text format via email etc.

-salt
    To use a salt (randomly generated) when encrypting. You always
    want to use a salt while encrypting. This parameter is actually
    redundant because a salt is used whether you use this or not 
    which is why it was not used in the "Short Answer" above!

-K key    
    The actual key to use: this must be represented as a string
    comprised only of hex digits. If only the key is specified, the
    IV must additionally be specified using the -iv option. When 
    both a key and a password are specified, the key given with the
    -K option will be used and the IV generated from the password 
    will be taken. It probably does not make much sense to specify 
    both key and password.

-iv IV
    The actual IV to use: this must be represented as a string 
    comprised only of hex digits. When only the key is specified 
    using the -K option, the IV must explicitly be defined. When a
    password is being specified using one of the other options, the 
    IV is generated from this password.

Notas adicionales:

Aunque ha preguntado específicamente sobre OpenSSL, es posible que desee considerar el uso de GPG en su lugar con el propósito de cifrado basado en este artículo OpenSSL vs GPG para cifrar copias de seguridad fuera del sitio?

Utilizar GPG para hacer lo mismo usarías los siguientes comandos:

Para Cifrar:

gpg --output encrypted.data --symmetric --cipher-algo AES256 un_encrypted.data

Para Descifrar:

gpg --output un_encrypted.data --decrypt encrypted.data

Nota: Se le solicitará una contraseña al cifrar o descifrar.

 106
Author: moo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:24

Cifrar:

openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey

Descifrar:

openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey

Para más detalles, consulte el openssl(1) docs.

 29
Author: Ken Cheung,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-04 21:13:12

Para Cifrar:

$ openssl bf < arquivo.txt > arquivo.txt.bf

Para Descifrar:

$ openssl bf -d < arquivo.txt.bf > arquivo.txt

Bf = = = Blowfish en modo CBC

 3
Author: fabio almeida,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 18:54:34

Actualizar usando una clave pública generada al azar.

Encypt:

openssl enc -aes-256-cbc -a -salt -in {raw data} -out {encrypted data} -pass file:{random key}

Descifrar:

openssl enc -d -aes-256-cbc -in {ciphered data} -out {raw data}

Tengo un tutorial completo sobre esto en http://bigthinkingapplied.com/key-based-encryption-using-openssl /

 3
Author: nneko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 19:43:56

Hay un programa de código abierto que encuentro en línea que utiliza openssl para cifrar y descifrar archivos. Lo hace con una sola contraseña. Lo bueno de este script de código abierto es que elimina el archivo original sin cifrar triturando el archivo. Pero lo peligroso es que una vez que el archivo original sin cifrar se ha ido usted tiene que asegurarse de recordar su contraseña de lo contrario no hay otra manera de descifrar su archivo.

Aquí el enlace en el que está github

Https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py

 2
Author: Michael linkston,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-01 16:06:17

Tenga en cuenta que la CLI de OpenSSL utiliza un algoritmo débil no estándar para convertir la frase de contraseña en una clave, y la instalación de GPG resulta en varios archivos agregados a su directorio personal y un proceso en segundo plano gpg-agent en ejecución. Si desea la máxima portabilidad y control con las herramientas existentes, puede usar PHP o Python para acceder a las API de nivel inferior y pasar directamente una clave AES completa y IV.

Ejemplo de invocación de PHP a través de Bash:

IV='c2FtcGxlLWFlcy1pdjEyMw=='
KEY='Twsn8eh2w2HbVCF5zKArlY+Mv5ZwVyaGlk5QkeoSlmc='
INPUT=123456789023456

ENCRYPTED=$(php -r "print(openssl_encrypt('$INPUT','aes-256-ctr',base64_decode('$KEY'),OPENSSL_ZERO_PADDING,base64_decode('$IV')));")
echo '$ENCRYPTED='$ENCRYPTED
DECRYPTED=$(php -r "print(openssl_decrypt('$ENCRYPTED','aes-256-ctr',base64_decode('$KEY'),OPENSSL_ZERO_PADDING,base64_decode('$IV')));")
echo '$DECRYPTED='$DECRYPTED

Esto produce:

$ENCRYPTED=nzRi252dayEsGXZOTPXW
$DECRYPTED=123456789023456

También podrías use la función openssl_pbkdf2 de PHP para convertir una frase de contraseña a una clave de forma segura.

 1
Author: zeroimpl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-08 02:22:10