Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt and decrypt a string/text in shell (linux environment)

Tags:

linux

I have a string, which is actually password. I want to encrypt the string and want to store the encrypted result in a parameter file. Next during execution of a script that encrypted string will be picked up and in run time that will be decrypt. So I want to know how to encrypt and decrypt a string/text in linux environment?

like image 359
Koushik Chandra Avatar asked Nov 15 '15 09:11

Koushik Chandra


People also ask

How do I encrypt and decrypt in Linux?

In order to decrypt an encrypted file on Linux, you have to use the “gpg” command with the “-d” option for “decrypt” and specify the “. gpg” file that you want to decrypt. Again, you will be probably be prompted with a window (or directly in the terminal) for the passphrase.


2 Answers

This isn't quite what was being asked for here but it shows a simple way to do this without a password prompt

Using:

openssl version
LibreSSL 2.8.3

encode.sh

#!/usr/bin/env bash

echo $1 | openssl aes-256-cbc -a -salt -pass pass:somepassword

decode.sh

#!/usr/bin/env bash

echo $1 | openssl aes-256-cbc -d -a -pass pass:somepassword

make files executable

chmod +x encode.sh decode.sh

encode example

./encode.sh "this is my test string"
# => U2FsdGVkX18fjSHGEzTXU08q+GG2I4xrV+GGtfDLg+T3vxpllUc/IHnRWLgoUl9q

decode example

./decode.sh U2FsdGVkX18fjSHGEzTXU08q+GG2I4xrV+GGtfDLg+T3vxpllUc/IHnRWLgoUl9q
# => this is my test string
like image 98
casonadams Avatar answered Oct 20 '22 17:10

casonadams


openssl can do it better.

encode:

$ secret=$(echo "this is a secret." | openssl enc -e -des3 -base64 -pass pass:mypasswd -pbkdf2)

decode:

$ echo "${secret}" | openssl enc -d -des3 -base64 -pass pass:mypasswd -pbkdf2

tips:

  • you can remove arg -pass and intput password according to the prompt.
like image 42
zhanw15 Avatar answered Oct 20 '22 16:10

zhanw15