您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

322 行
9.6 KiB

  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Commandline scripts.
  15. These scripts are called by the executables defined in setup.py.
  16. """
  17. import abc
  18. import sys
  19. import typing
  20. import optparse
  21. import rsa
  22. import rsa.key
  23. import rsa.pkcs1
  24. HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys())
  25. Indexable = typing.Union[typing.Tuple, typing.List[str]]
  26. def keygen() -> None:
  27. """Key generator."""
  28. # Parse the CLI options
  29. parser = optparse.OptionParser(
  30. usage="usage: %prog [options] keysize",
  31. description='Generates a new RSA key pair of "keysize" bits.',
  32. )
  33. parser.add_option(
  34. "--pubout",
  35. type="string",
  36. help="Output filename for the public key. The public key is "
  37. "not saved if this option is not present. You can use "
  38. "pyrsa-priv2pub to create the public key file later.",
  39. )
  40. parser.add_option(
  41. "-o",
  42. "--out",
  43. type="string",
  44. help="Output filename for the private key. The key is "
  45. "written to stdout if this option is not present.",
  46. )
  47. parser.add_option(
  48. "--form",
  49. help="key format of the private and public keys - default PEM",
  50. choices=("PEM", "DER"),
  51. default="PEM",
  52. )
  53. (cli, cli_args) = parser.parse_args(sys.argv[1:])
  54. if len(cli_args) != 1:
  55. parser.print_help()
  56. raise SystemExit(1)
  57. try:
  58. keysize = int(cli_args[0])
  59. except ValueError as ex:
  60. parser.print_help()
  61. print("Not a valid number: %s" % cli_args[0], file=sys.stderr)
  62. raise SystemExit(1) from ex
  63. print("Generating %i-bit key" % keysize, file=sys.stderr)
  64. (pub_key, priv_key) = rsa.newkeys(keysize)
  65. # Save public key
  66. if cli.pubout:
  67. print("Writing public key to %s" % cli.pubout, file=sys.stderr)
  68. data = pub_key.save_pkcs1(format=cli.form)
  69. with open(cli.pubout, "wb") as outfile:
  70. outfile.write(data)
  71. # Save private key
  72. data = priv_key.save_pkcs1(format=cli.form)
  73. if cli.out:
  74. print("Writing private key to %s" % cli.out, file=sys.stderr)
  75. with open(cli.out, "wb") as outfile:
  76. outfile.write(data)
  77. else:
  78. print("Writing private key to stdout", file=sys.stderr)
  79. sys.stdout.buffer.write(data)
  80. class CryptoOperation(metaclass=abc.ABCMeta):
  81. """CLI callable that operates with input, output, and a key."""
  82. keyname = "public" # or 'private'
  83. usage = "usage: %%prog [options] %(keyname)s_key"
  84. description = ""
  85. operation = "decrypt"
  86. operation_past = "decrypted"
  87. operation_progressive = "decrypting"
  88. input_help = "Name of the file to %(operation)s. Reads from stdin if " "not specified."
  89. output_help = (
  90. "Name of the file to write the %(operation_past)s file "
  91. "to. Written to stdout if this option is not present."
  92. )
  93. expected_cli_args = 1
  94. has_output = True
  95. key_class = rsa.PublicKey # type: typing.Type[rsa.key.AbstractKey]
  96. def __init__(self) -> None:
  97. self.usage = self.usage % self.__class__.__dict__
  98. self.input_help = self.input_help % self.__class__.__dict__
  99. self.output_help = self.output_help % self.__class__.__dict__
  100. @abc.abstractmethod
  101. def perform_operation(
  102. self, indata: bytes, key: rsa.key.AbstractKey, cli_args: Indexable
  103. ) -> typing.Any:
  104. """Performs the program's operation.
  105. Implement in a subclass.
  106. :returns: the data to write to the output.
  107. """
  108. def __call__(self) -> None:
  109. """Runs the program."""
  110. (cli, cli_args) = self.parse_cli()
  111. key = self.read_key(cli_args[0], cli.keyform)
  112. indata = self.read_infile(cli.input)
  113. print(self.operation_progressive.title(), file=sys.stderr)
  114. outdata = self.perform_operation(indata, key, cli_args)
  115. if self.has_output:
  116. self.write_outfile(outdata, cli.output)
  117. def parse_cli(self) -> typing.Tuple[optparse.Values, typing.List[str]]:
  118. """Parse the CLI options
  119. :returns: (cli_opts, cli_args)
  120. """
  121. parser = optparse.OptionParser(usage=self.usage, description=self.description)
  122. parser.add_option("-i", "--input", type="string", help=self.input_help)
  123. if self.has_output:
  124. parser.add_option("-o", "--output", type="string", help=self.output_help)
  125. parser.add_option(
  126. "--keyform",
  127. help="Key format of the %s key - default PEM" % self.keyname,
  128. choices=("PEM", "DER"),
  129. default="PEM",
  130. )
  131. (cli, cli_args) = parser.parse_args(sys.argv[1:])
  132. if len(cli_args) != self.expected_cli_args:
  133. parser.print_help()
  134. raise SystemExit(1)
  135. return cli, cli_args
  136. def read_key(self, filename: str, keyform: str) -> rsa.key.AbstractKey:
  137. """Reads a public or private key."""
  138. print("Reading %s key from %s" % (self.keyname, filename), file=sys.stderr)
  139. with open(filename, "rb") as keyfile:
  140. keydata = keyfile.read()
  141. return self.key_class.load_pkcs1(keydata, keyform)
  142. def read_infile(self, inname: str) -> bytes:
  143. """Read the input file"""
  144. if inname:
  145. print("Reading input from %s" % inname, file=sys.stderr)
  146. with open(inname, "rb") as infile:
  147. return infile.read()
  148. print("Reading input from stdin", file=sys.stderr)
  149. return sys.stdin.buffer.read()
  150. def write_outfile(self, outdata: bytes, outname: str) -> None:
  151. """Write the output file"""
  152. if outname:
  153. print("Writing output to %s" % outname, file=sys.stderr)
  154. with open(outname, "wb") as outfile:
  155. outfile.write(outdata)
  156. else:
  157. print("Writing output to stdout", file=sys.stderr)
  158. sys.stdout.buffer.write(outdata)
  159. class EncryptOperation(CryptoOperation):
  160. """Encrypts a file."""
  161. keyname = "public"
  162. description = (
  163. "Encrypts a file. The file must be shorter than the key " "length in order to be encrypted."
  164. )
  165. operation = "encrypt"
  166. operation_past = "encrypted"
  167. operation_progressive = "encrypting"
  168. def perform_operation(
  169. self, indata: bytes, pub_key: rsa.key.AbstractKey, cli_args: Indexable = ()
  170. ) -> bytes:
  171. """Encrypts files."""
  172. assert isinstance(pub_key, rsa.key.PublicKey)
  173. return rsa.encrypt(indata, pub_key)
  174. class DecryptOperation(CryptoOperation):
  175. """Decrypts a file."""
  176. keyname = "private"
  177. description = (
  178. "Decrypts a file. The original file must be shorter than "
  179. "the key length in order to have been encrypted."
  180. )
  181. operation = "decrypt"
  182. operation_past = "decrypted"
  183. operation_progressive = "decrypting"
  184. key_class = rsa.PrivateKey
  185. def perform_operation(
  186. self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable = ()
  187. ) -> bytes:
  188. """Decrypts files."""
  189. assert isinstance(priv_key, rsa.key.PrivateKey)
  190. return rsa.decrypt(indata, priv_key)
  191. class SignOperation(CryptoOperation):
  192. """Signs a file."""
  193. keyname = "private"
  194. usage = "usage: %%prog [options] private_key hash_method"
  195. description = (
  196. "Signs a file, outputs the signature. Choose the hash "
  197. "method from %s" % ", ".join(HASH_METHODS)
  198. )
  199. operation = "sign"
  200. operation_past = "signature"
  201. operation_progressive = "Signing"
  202. key_class = rsa.PrivateKey
  203. expected_cli_args = 2
  204. output_help = (
  205. "Name of the file to write the signature to. Written "
  206. "to stdout if this option is not present."
  207. )
  208. def perform_operation(
  209. self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable
  210. ) -> bytes:
  211. """Signs files."""
  212. assert isinstance(priv_key, rsa.key.PrivateKey)
  213. hash_method = cli_args[1]
  214. if hash_method not in HASH_METHODS:
  215. raise SystemExit("Invalid hash method, choose one of %s" % ", ".join(HASH_METHODS))
  216. return rsa.sign(indata, priv_key, hash_method)
  217. class VerifyOperation(CryptoOperation):
  218. """Verify a signature."""
  219. keyname = "public"
  220. usage = "usage: %%prog [options] public_key signature_file"
  221. description = (
  222. "Verifies a signature, exits with status 0 upon success, "
  223. "prints an error message and exits with status 1 upon error."
  224. )
  225. operation = "verify"
  226. operation_past = "verified"
  227. operation_progressive = "Verifying"
  228. key_class = rsa.PublicKey
  229. expected_cli_args = 2
  230. has_output = False
  231. def perform_operation(
  232. self, indata: bytes, pub_key: rsa.key.AbstractKey, cli_args: Indexable
  233. ) -> None:
  234. """Verifies files."""
  235. assert isinstance(pub_key, rsa.key.PublicKey)
  236. signature_file = cli_args[1]
  237. with open(signature_file, "rb") as sigfile:
  238. signature = sigfile.read()
  239. try:
  240. rsa.verify(indata, signature, pub_key)
  241. except rsa.VerificationError as ex:
  242. raise SystemExit("Verification failed.") from ex
  243. print("Verification OK", file=sys.stderr)
  244. encrypt = EncryptOperation()
  245. decrypt = DecryptOperation()
  246. sign = SignOperation()
  247. verify = VerifyOperation()