Skip to content

Instantly share code, notes, and snippets.

@stliu
Created April 24, 2014 03:28
Show Gist options
  • Save stliu/11240500 to your computer and use it in GitHub Desktop.
Save stliu/11240500 to your computer and use it in GitHub Desktop.
GPG

GPG

GPG 主要有两个作用, 签名和加密, 具体信息参见这里

签名

签名主要是为了确定对方是谁, 例如, A 给 B发送了一个电子邮件, 或者文件, 那么B怎么知道这个确实是A发出来的, 而不是别人冒名顶替呢, 还有, 这个信息是否在发送的中间被别人修改过呢?

这时候, A可以在发送文件的时候, 对这个文件使用GPG做一个签名

gpg -a -b message.txt
-a 表示输出文本文件格式。
-b 表示以生成独立的签名文件的方式进行签名。

这时候, 会有一个 message.txt.asc 的文件升成出来, A需要把 message.txt 和 message.txt.asc 都发给B, 注意, 这个.asc的文件是通过使用A的public key 和文件内容计算出来的, 所以文件内容如果被修改了的话, 通过这个asc文件也是能校验出来的

B在接到这两个文件之后, 首先验证签名文件 message.txt.asc

gpg --verify message.txt.asc

可以看到类似如下的信息

➜  ~  gpg2 --verify content.txt.asc 
gpg: Signature made Thu Apr 17 10:28:02 2014 CST using RSA key ID EB8968F3 的人签名的了
gpg: Good signature from "Shaozhuang Liu <stliu@apache.org>"
gpg:                 aka "[jpeg image of size 67184]"
gpg:                 aka "Shaozhuang Liu <stliu@easemob.com>"
gpg:                 aka "Strong Liu (my hibernate alias) <stliu@hibernate.org>"
gpg:                 aka "Shaozhuang Liu <rain2sunny@gmail.com>"
gpg:                 aka "Shaozhuang Liu <shaozhuang.liu@gmail.com>"    

注意其中的 gpg: Good signature from "Shaozhuang Liu <stliu@apache.org>" 字样, 这表示, 这个文件是ID 为 EB8968F3 的人发出来的, 并且没有被修改过

如果我们改动一下 message.txt 中的内容,再重新执行上面的校验命令的话, 就可以看到下面的结果

➜  ~  gpg2 --verify content.txt.asc
gpg: Signature made Thu Apr 17 10:28:02 2014 CST using RSA key ID EB8968F3
gpg: BAD signature from "Shaozhuang Liu <stliu@apache.org>"

如果不想单独生成一个签名文件, 还可以把签名信息直接加入到源文件当中去

gpg -a --clearsign content.txt

跟前面方法不同的地方是用参数 –clearsign 替代了参数 -b。参数 clearsign表示将签名和原信息合并在一起,并生成一个新文件 content.txt.asc。

文件的接收方收到这个文件之后, 还可以使用同样的方法进行校验

gpg2 --verify content.txt.asc

使用如下命令可以把原始信息提取出来:

gpg2 --output content.original.txt -d content.txt.asc

加密

gpg -a --output message-ciper.txt -r C1E8F16E -e message.txt
  • -a 表示输出文本文件格式。
  • –output 指定输出(即加密后)的文件名。
  • -r 指定信息的接收者(recipient)公钥的uid,可以是名字也可以是email地址。
  • -e 表示这次要执行的是加密(encrypt)操作

解密

gpg --output message-plain.txt -d message-ciper.txt    
  • –output 指定输出(即解密后)的文件名。
  • -d 表示这次要执行的是解密(decrypt)操作。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment