linux使用ecryptfs加密文件

(1) 安装
Ubuntu安装ecryptfs:

sudo apt-get install ecryptfs-utils

Centos安装

sudo yum install ecryptfs-utils

为了稳妥起见,安装程序包后,装入eCryptFS内核模块是个好的做法:

sudo modprobe ecryptfs

(2)创建加密目录并挂载
假设你加密后存储的文件目录是~/data_secret,而解密后使用的目录是~/data。先创建好这两个目录,然后把加密目录挂载到解密目录:

user@localhost:~$ sudo mount -t ecryptfs ~/data_secret ~/data
[sudo] password for user:(管理员密码)
Passphrase:(加密密码,一定要记住)
Select cipher:
1) aes: blocksize = 16; min keysize = 16; max keysize = 32 (loaded)
2) blowfish: blocksize = 16; min keysize = 16; max keysize = 56 (not loaded)
3) des3_ede: blocksize = 8; min keysize = 24; max keysize = 24 (not loaded)
4) cast6: blocksize = 16; min keysize = 16; max keysize = 32 (not loaded)
5) cast5: blocksize = 8; min keysize = 5; max keysize = 16 (not loaded)
Selection [aes]:
Select key bytes:
1) 16
2) 32
3) 24
Selection [16]:
Enable plaintext passthrough (y/n) [n]:
Enable filename encryption (y/n) [n]:y(允许文件名加密)
Filename Encryption Key (FNEK) Signature [aaaa222233331234(记住,以后会用到)]:
Attempting to mount with the following options:
  ecryptfs_unlink_sigs
  ecryptfs_fnek_sig=aaaa222233331234
  ecryptfs_key_bytes=16
  ecryptfs_cipher=aes
  ecryptfs_sig=aaaa222233331234
WARNING: Based on the contents of [/root/.ecryptfs/sig-cache.txt],
it looks like you have never mounted with this key
before. This could mean that you have typed your
passphrase wrong.

Would you like to proceed with the mount (yes/no)? :yes(第一次使用的密码会有这个提示,输入yes继续)
Would you like to append sig [aaaa222233331234] to
[/root/.ecryptfs/sig-cache.txt]
in order to avoid this warning in the future (yes/no)? :yes(记住这个密码标识,以后不再提示)
Successfully appended new sig to user sig cache file
Mounted eCryptfs

(3)文件操作
加密目录~/data_secret被解密并挂载到~/data,我们可以在~/data下进行普通文件操作:

user@localhost:~/data$ echo "test" > test
user@localhost:~/data$ ls
test
user@localhost:~/data$ cat test
test

(4) 卸载加密目录
使用命令卸载加密目录:

sudo umount ~/data

卸载后~/data为空,而 ~/data_secret则显示乱码(对应加密后的test文件):

user@localhost:~$ ls data
user@localhost:~$ ls data_secret/
ECRYPTFS_FNEK_ENCRYPTED.FWb9phlX-ctK-UTNypKqMObbsrr32asfab1dl2LDDBryfZQ7xaRV.R0dJBavE--
user@localhost:~$ cat data_secret/FWb9phlX-ctK-UTNypKqMObbsrr32asfab1dl2LDDBryfZQ7xaRV.R0dJBavE--(一堆乱码)

(5)快速挂载
以后每次开机后访问加密数据前都需要重新挂载,你可以使用sudo mount -t ecryptfs ~/data_secret ~/data命令来挂载,但每次都要手工输入一堆选项也挺烦人的。为了以后方便挂载,在~/.bashrc中加入别名:

alias mount_data="sudo mount -t ecryptfs $HOME/data_secret $HOME/data -o ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_enable_filename_crypto=y,ecryptfs_passthrough=n,ecryptfs_fnek_sig=aaaa222233331234(需从前面记录)"

以后每次使用前只需要执行mount_data即可:

user@localhost:~$ mount_data
[sudo] password for user:(管理员密码)
Passphrase:(加密密码)
Attempting to mount with the following options:
ecryptfs_unlink_sigs
ecryptfs_fnek_sig=aaaa222233331234
ecryptfs_key_bytes=16
ecryptfs_cipher=aes
ecryptfs_sig=aaaa222233331234
Mounted eCryptfs
user@localhost:~$ cat data/test
test

(6) 重装系统或移动数据
你只需要记住加密密码和ecryptfs_fnek_sig参数,则即使你要重装系统或移动数据,也可以用同样的命令对数据进行解密并挂载。

添加新评论