# How to encrypt/decrypt a file with a passphrase | key-file

## Why we need to encrypt file

File encryption is important for several reasons:

* Protection against loss or theft: If a device such as a laptop or mobile device is lost or stolen, file encryption protects against the threat of someone being able to read sensitive data off of the device.
    
* Data Protection: Encryption helps protect your sensitive data from unauthorized access.
    
* Ransomware Protection: Encrypting your files is a critical part of your defense against cybercriminal attacks, including ransomware.
    
* Secure file sharing: Encryption enables secure file sharing. When you transfer files between devices or over the Internet, encryption ensures that your files remain secure in transit.
    

When a file is encrypted, anyone without the correct decryption key won't be able to read anything substantial,they can only see scrambled nonsense.

## How to encrypt/decrypt a file with a passphrase | key-file

We will use a simple, modern and secure file encryption tool called `age`.

> [https://github.com/FiloSottile/age](https://github.com/FiloSottile/age)

### Encrypt/Decrypt a File with a Passphrase

First let's encrypt a file

```bash
age -p -o yourfile.age yourfile
# You will see hints that let you enter the same passphrase twice,such as 'hello-age':
# Enter passphrase (leave empty to autogenerate a secure one):
# Confirm passphrase:
```

Do you see the encrypted file `yourfile.age`?

Now let's decrypt it

```bash
age -d -o yourfile2 yourfile.age
# You will see hints to enter passphrase:
# Enter passphrase:
```

You should see the decrypted file `yourfile2`, check to see if it is the same as `yourfile`.

### Encrypt/Decrypt a File with a key-file

First let's create the key file:

```bash
age-keygen -o key-private.txt
# This will create the key-private.txt and print out the public key
# Public key: age1v3uzdzzwfzlrh5yg7445lgr4d2xcux0jfh3drvsx8jrqtfmjavhqc845g5

age-keygen -y -o key-public.txt key-private.txt
# This will create the key-public.txt
```

Let's encrypt a file

```bash
age -R key-public.txt -o yourfile3.age yourfile
```

Do you see the encrypted file yourfile3.age?

Now let's decrypt the file

```bash
age -d -i key-private.txt -o yourfile4 yourfile3.age
```

You should see the decrypted file `yourfile4`, check to see if it is the same as `yourfile`.

> ### Why not 7Z/Zip?
> 
> They don't support encryption with key-file(asymmetric encryption).
> 
> ### Why not GPG(GNU Privacy Guard)?
> 
> It's too complex for normal users.
