1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4from __future__ import absolute_import, division, unicode_literals
5
6# Copyright (C) 2018 Ben McGinnes <ben@gnupg.org>
7#
8# This program is free software; you can redistribute it and/or modify it under
9# the terms of the GNU General Public License as published by the Free Software
10# Foundation; either version 2 of the License, or (at your option) any later
11# version.
12#
13# This program is free software; you can redistribute it and/or modify it under
14# the terms of the GNU Lesser General Public License as published by the Free
15# Software Foundation; either version 2.1 of the License, or (at your option)
16# any later version.
17#
18# This program is distributed in the hope that it will be useful, but WITHOUT
19# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20# FOR A PARTICULAR PURPOSE.  See the GNU General Public License and the GNU
21# Lesser General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License and the GNU
24# Lesser General Public along with this program; if not, see
25# <https://www.gnu.org/licenses/>.
26
27import gpg
28import sys
29
30"""
31Signs a file with a specified key.  If entering both the key and the filename
32on the command line, the key must be entered first.
33
34Will produce both an ASCII armoured and GPG binary format copy of the signed
35file.
36"""
37
38if len(sys.argv) > 3:
39    logrus = sys.argv[1]
40    filename = " ".join(sys.argv[2:])
41elif len(sys.argv) == 3:
42    logrus = sys.argv[1]
43    filename = sys.argv[2]
44elif len(sys.argv) == 2:
45    logrus = sys.argv[1]
46    filename = input("Enter the path and filename to sign: ")
47else:
48    logrus = input("Enter the fingerprint or key ID to sign with: ")
49    filename = input("Enter the path and filename to sign: ")
50
51with open(filename, "rb") as f:
52    text = f.read()
53
54key = list(gpg.Context().keylist(pattern=logrus))
55
56with gpg.Context(armor=True, signers=key) as ca:
57    signed_data, result = ca.sign(text, mode=gpg.constants.sig.mode.NORMAL)
58    with open("{0}.asc".format(filename), "wb") as fa:
59        fa.write(signed_data)
60
61with gpg.Context(signers=key) as cg:
62    signed_data, result = cg.sign(text, mode=gpg.constants.sig.mode.NORMAL)
63    with open("{0}.gpg".format(filename), "wb") as fg:
64        fg.write(signed_data)
65