Read user input, Encrypt the data and write to file

Hi,

can some one help me how to encrypt and decrypt a file.

AIM: reade user input, encrypt it and save it to file.

while decryption read the encrypted file decrypt it and save the output in some variable.

Example: consider we have Credentials.txt file with content username: password

when user run a script, it should ask them to enter username and password in format of "username: password".

when user enters them, it should get encrypted and save to credentials.txt file.

while decryption, read the credentials.txt file decrypt it, then split the content before and after the delimiter : and store them into two different variable like username should get stored in $usr and password should store in $passwd. i will use this variable in further script

im trying from very long time to hw to achive this. i will be very thank full if some one help me.... :slight_smile:

Check this.

1 Like

I like to use openssl. Something like this should do the trick:

 #!/bin/bash
decrypt=credentials.txt
encrypt=${decrypt}.encrypted

if [[ $# -eq 0 ]] ; then 
    echo "Gimme username"
    read username
    echo "Gimme password"
    read -s password
    echo ${username}:${password} | openssl des3 -salt  -out $encrypt
    echo "File encrypted into $encrypt"
elif [[ $1 = '-d' ]] ; then
    openssl des3 -d -salt -in $encrypt -out $decrypt
    echo "File decrypted into $decrypt"
else 
    echo "Argument $1 not recognized. Either run with no argument for encryption or with '-d' for encryption" >&2
    exit 1
fi
1 Like

Thanka for your responce MIRNI... i will check your code and get back to you...

---------- Post updated at 06:37 PM ---------- Previous update was at 03:34 PM ----------

Hi Mirni tahnks fo rthe code. in encryption part it is working fine. a small modification, it should not prompt user to enter the key. is there any other way to encrypt the content without giving key and write output to file.

why im asking is while dycrypting it should not ask me to provide key. im going to sdecrypt the credentials.txt.encrypt file with another script. also can you plz give me code for encrypt and decrypt seperately.

encrypt:

 
echo ${username}:${password} | openssl  des3 -salt -pass pass:$password -out credentials.txt.enc

Decrypt:

openssl -d des3 -salt -pass pass:${password} -in credentials.txt.enc -out credentials.txt

Note that by passing the password directly as a command argument, it can be spied on.
A better way would be to use gpg and generate key.

Look at the man pages for details.

1 Like

thank you mirni, it worked perfectly. thanks for your help