code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
it = iter(items) return itertools.zip_longest(*[it] * n, fillvalue=fillvalue)
def n_at_a_time( items: List[int], n: int, fillvalue: str ) -> Iterator[Tuple[Union[int, str]]]
Returns an iterator which groups n items at a time. Any final partial tuple will be padded with the fillvalue >>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X')) [(1, 2), (3, 4), (5, 'X')]
3.198594
5.671699
0.563957
# Use mode = "rb" to read binary file with open(binary_file, "rb") as bin_file: encoded_string = base64.b64encode(bin_file.read()) return encoded_string.decode()
def binary2base64(binary_file: str) -> str
Convert a binary file (OGG, executable, etc.) to a printable string.
3.185989
2.821481
1.12919
if isinstance(fname_or_instance, Image.Image): return fname_or_instance return Image.open(fname_or_instance)
def open_image(fname_or_instance: Union[str, IO[bytes]])
Opens a Image and returns it. :param fname_or_instance: Can either be the location of the image as a string or the Image.Image instance itself.
2.804083
2.973296
0.943089
from zlib import compress from base64 import b64encode if secret_file != None: with open(secret_file, "r") as f: secret_message = f.read() try: text = compress(b64encode(bytes(secret_message, "utf-8"))) except: text = compress(b64encode(secret_message)) img = tools.open_image(input_image_file) if img_format is None: img_format = img.format if "exif" in img.info: exif_dict = piexif.load(img.info["exif"]) else: exif_dict = {} exif_dict["0th"] = {} exif_dict["0th"][piexif.ImageIFD.ImageDescription] = text exif_bytes = piexif.dump(exif_dict) img.save(img_enc, format=img_format, exif=exif_bytes) img.close() return img
def hide( input_image_file, img_enc, secret_message=None, secret_file=None, img_format=None, )
Hide a message (string) in an image.
1.947387
1.883972
1.03366
from base64 import b64decode from zlib import decompress img = tools.open_image(input_image_file) try: if img.format in ["JPEG", "TIFF"]: if "exif" in img.info: exif_dict = piexif.load(img.info.get("exif", b"")) description_key = piexif.ImageIFD.ImageDescription encoded_message = exif_dict["0th"][description_key] else: encoded_message = b"" else: raise ValueError("Given file is neither JPEG nor TIFF.") finally: img.close() return b64decode(decompress(encoded_message))
def reveal(input_image_file)
Find a message in an image.
2.960129
2.884624
1.026175
encoded = img.copy() width, height = img.size colours_counter = Counter() # type: Counter[int] for row in range(height): for col in range(width): r, g, b = img.getpixel((col, row)) colours_counter[r] += 1 most_common = colours_counter.most_common(10) dict_colours = OrderedDict(sorted(list(colours_counter.items()), key=lambda t: t[1])) colours = 0 # type: float for colour in list(dict_colours.keys()): colours += colour colours = colours / len(dict_colours) #return colours.most_common(10) return list(dict_colours.keys())[:30], most_common
def steganalyse(img)
Steganlysis of the LSB technique.
3.078322
3.047593
1.010083
d = {} # type: Dict[int, List[int]] for i in itertools.count(2): if i in d: for j in d[i]: d[i + j] = d.get(i + j, []) + [j] del d[i] else: d[i * i] = [i] yield i
def eratosthenes() -> Iterator[int]
Generate the prime numbers with the sieve of Eratosthenes. https://oeis.org/A000040
2.067405
2.121757
0.974383
p1 = 3 for p2 in eratosthenes(): for n in range(p1 + 1, p2): yield n p1 = p2
def composite() -> Iterator[int]
Generate the composite numbers using the sieve of Eratosthenes. https://oeis.org/A002808
4.255944
3.589336
1.185719
for m in composite(): for a in range(2, m): if pow(a, m, m) != a: break else: yield m
def carmichael() -> Iterator[int]
Composite numbers n such that a^(n-1) == 1 (mod n) for every a coprime to n. https://oeis.org/A002997
4.706091
4.077295
1.154219
if m == 0: return n + 1 elif n == 0: return ackermann(m - 1, 1) else: return ackermann(m - 1, ackermann(m, n - 1))
def ackermann_naive(m: int, n: int) -> int
Ackermann number.
1.652188
1.449711
1.139667
while m >= 4: if n == 0: n = 1 else: n = ackermann(m, n - 1) m -= 1 if m == 3: return (1 << n + 3) - 3 elif m == 2: return (n << 1) + 3 elif m == 1: return n + 2 else: return n + 1
def ackermann(m: int, n: int) -> int
Ackermann number.
2.80791
2.532943
1.108556
a, b = 1, 2 while True: yield a a, b = b, a + b
def fibonacci() -> Iterator[int]
Generate the sequence of Fibonacci. https://oeis.org/A000045
2.092752
2.34773
0.891394
y = 1 while True: adder = max(1, math.pow(10, int(math.log10(y)))) yield int(y) y = y + int(adder)
def log_gen() -> Iterator[int]
Logarithmic generator.
4.576678
4.239638
1.079497
message_length = len(message) assert message_length != 0, "message message_length is zero" assert message_length < 255, "message is too long" img = tools.open_image(input_image) # Use a copy of image to hide the text in encoded = img.copy() width, height = img.size index = 0 for row in range(height): for col in range(width): (r, g, b) = img.getpixel((col, row)) # first value is message_length of message if row == 0 and col == 0 and index < message_length: asc = message_length elif index <= message_length: c = message[index - 1] asc = ord(c) else: asc = r encoded.putpixel((col, row), (asc, g, b)) index += 1 img.close() return encoded
def hide(input_image: Union[str, IO[bytes]], message: str)
Hide a message (string) in an image. Use the red portion of a pixel (r, g, b) tuple to hide the message string characters as ASCII values. The red value of the first pixel is used for message_length of the string.
3.307871
2.965627
1.115404
img = tools.open_image(input_image) width, height = img.size message = "" index = 0 for row in range(height): for col in range(width): r, g, b = img.getpixel((col, row)) # First pixel r value is length of message if row == 0 and col == 0: message_length = r elif index <= message_length: message += chr(r) index += 1 img.close() return message
def reveal(input_image: Union[str, IO[bytes]])
Find a message in an image. Check the red portion of an pixel (r, g, b) tuple for hidden message characters (ASCII values). The red value of the first pixel is used for message_length of string.
3.326051
2.754706
1.207407
message_length = len(message) assert message_length != 0, "message length is zero" img = tools.open_image(input_image) if img.mode not in ["RGB", "RGBA"]: if not auto_convert_rgb: print( "The mode of the image is not RGB. Mode is {}".format(img.mode) ) answer = input("Convert the image to RGB ? [Y / n]\n") or "Y" if answer.lower() == "n": raise Exception("Not a RGB image.") img = img.convert("RGB") encoded = img.copy() width, height = img.size index = 0 message = str(message_length) + ":" + str(message) message_bits = "".join(tools.a2bits_list(message, encoding)) message_bits += "0" * ((3 - (len(message_bits) % 3)) % 3) npixels = width * height len_message_bits = len(message_bits) if len_message_bits > npixels * 3: raise Exception( "The message you want to hide is too long: {}".format( message_length ) ) for row in range(height): for col in range(width): if index + 3 <= len_message_bits: # Get the colour component. pixel = img.getpixel((col, row)) r = pixel[0] g = pixel[1] b = pixel[2] # Change the Least Significant Bit of each colour component. r = tools.setlsb(r, message_bits[index]) g = tools.setlsb(g, message_bits[index + 1]) b = tools.setlsb(b, message_bits[index + 2]) # Save the new pixel if img.mode == "RGBA": encoded.putpixel((col, row), (r, g, b, pixel[3])) else: encoded.putpixel((col, row), (r, g, b)) index += 3 else: img.close() return encoded
def hide( input_image: Union[str, IO[bytes]], message: str, encoding: str = "UTF-8", auto_convert_rgb: bool = False, )
Hide a message (string) in an image with the LSB (Least Significant Bit) technique.
2.646155
2.602111
1.016926
img = tools.open_image(input_image) width, height = img.size buff, count = 0, 0 bitab = [] limit = None for row in range(height): for col in range(width): # pixel = [r, g, b] or [r,g,b,a] pixel = img.getpixel((col, row)) if img.mode == "RGBA": pixel = pixel[:3] # ignore the alpha for color in pixel: buff += (color & 1) << (tools.ENCODINGS[encoding] - 1 - count) count += 1 if count == tools.ENCODINGS[encoding]: bitab.append(chr(buff)) buff, count = 0, 0 if bitab[-1] == ":" and limit is None: try: limit = int("".join(bitab[:-1])) except: pass if len(bitab) - len(str(limit)) - 1 == limit: img.close() return "".join(bitab)[len(str(limit)) + 1 :]
def reveal(input_image: Union[str, IO[bytes]], encoding="UTF-8")
Find a message in an image (with the LSB technique).
3.4677
3.30776
1.048353
message_length = len(message) assert message_length != 0, "message length is zero" img = tools.open_image(input_image) if img.mode not in ["RGB", "RGBA"]: if not auto_convert_rgb: print( "The mode of the image is not RGB. Mode is {}".format(img.mode) ) answer = input("Convert the image to RGB ? [Y / n]\n") or "Y" if answer.lower() == "n": raise Exception("Not a RGB image.") img = img.convert("RGB") img_list = list(img.getdata()) width, height = img.size index = 0 message = str(message_length) + ":" + str(message) message_bits = "".join(tools.a2bits_list(message, encoding)) message_bits += "0" * ((3 - (len(message_bits) % 3)) % 3) npixels = width * height len_message_bits = len(message_bits) if len_message_bits > npixels * 3: raise Exception( "The message you want to hide is too long: {}".format( message_length ) ) while shift != 0: next(generator) shift -= 1 while index + 3 <= len_message_bits: generated_number = next(generator) r, g, b, *a = img_list[generated_number] # Change the Least Significant Bit of each colour component. r = tools.setlsb(r, message_bits[index]) g = tools.setlsb(g, message_bits[index + 1]) b = tools.setlsb(b, message_bits[index + 2]) # Save the new pixel if img.mode == "RGBA": img_list[generated_number] = (r, g, b, a[0]) else: img_list[generated_number] = (r, g, b) index += 3 # create empty new image of appropriate format encoded = Image.new("RGB", (img.size)) # insert saved data into the image encoded.putdata(img_list) return encoded
def hide( input_image: Union[str, IO[bytes]], message: str, generator: Iterator[int], shift: int = 0, encoding: str = "UTF-8", auto_convert_rgb: bool = False, )
Hide a message (string) in an image with the LSB (Least Significant Bit) technique.
2.974666
2.923356
1.017552
img = tools.open_image(input_image) img_list = list(img.getdata()) width, height = img.size buff, count = 0, 0 bitab = [] limit = None while shift != 0: next(generator) shift -= 1 while True: generated_number = next(generator) # color = [r, g, b] for color in img_list[generated_number]: buff += (color & 1) << (tools.ENCODINGS[encoding] - 1 - count) count += 1 if count == tools.ENCODINGS[encoding]: bitab.append(chr(buff)) buff, count = 0, 0 if bitab[-1] == ":" and limit == None: if "".join(bitab[:-1]).isdigit(): limit = int("".join(bitab[:-1])) else: raise IndexError("Impossible to detect message.") if len(bitab) - len(str(limit)) - 1 == limit: return "".join(bitab)[len(str(limit)) + 1 :]
def reveal( input_image: Union[str, IO[bytes]], generator: Iterator[int], shift: int = 0, encoding: str = "UTF-8", )
Find a message in an image (with the LSB technique).
3.859612
3.575716
1.079396
encoded = img.copy() width, height = img.size bits = "" for row in range(height): for col in range(width): r, g, b = img.getpixel((col, row)) if r % 2 == 0: r = 0 else: r = 255 if g % 2 == 0: g = 0 else: g = 255 if b % 2 == 0: b = 0 else: b = 255 encoded.putpixel((col, row), (r, g , b)) return encoded
def steganalyse(img)
Steganlysis of the LSB technique.
1.782213
1.74716
1.020063
if hasattr(obj, '_concurrencymeta'): return mark_safe("{0},{1}".format(unlocalize(obj.pk), get_revision_of_object(obj))) else: return mark_safe(unlocalize(obj.pk))
def identity(obj)
returns a string representing "<pk>,<version>" of the passed object
8.148697
5.958123
1.367662
def outer(oldfun): def inner(*args, **kwargs): msg = "%s is deprecated" % oldfun.__name__ if version is not None: msg += "will be removed in version %s;" % version if replacement is not None: msg += "; use %s instead" % (replacement) warnings.warn(msg, DeprecationWarning, stacklevel=2) if callable(replacement): return replacement(*args, **kwargs) else: return oldfun(*args, **kwargs) return inner return outer
def deprecated(replacement=None, version=None)
A decorator which can be used to mark functions as deprecated. replacement is a callable that will be called with the same args as the decorated function. >>> import pytest >>> @deprecated() ... def foo1(x): ... return x ... >>> pytest.warns(DeprecationWarning, foo1, 1) 1 >>> def newfun(x): ... return 0 ... >>> @deprecated(newfun, '1.1') ... def foo2(x): ... return x ... >>> pytest.warns(DeprecationWarning, foo2, 1) 0 >>>
2.403991
2.871141
0.837294
if inspect.isclass(o): target = o elif callable(o): target = o else: target = o.__class__ try: return target.__qualname__ except AttributeError: # pragma: no cover return target.__name__
def get_classname(o)
Returns the classname of an object r a class :param o: :return:
2.838211
3.17844
0.892957
parts = [] # if inspect.ismethod(o): # try: # cls = o.im_class # except AttributeError: # # Python 3 eliminates im_class, substitutes __module__ and # # __qualname__ to provide similar information. # parts = (o.__module__, o.__qualname__) # else: # parts = (fqn(cls), get_classname(o)) if hasattr(o, '__module__'): parts.append(o.__module__) parts.append(get_classname(o)) elif inspect.ismodule(o): return o.__name__ if not parts: raise ValueError("Invalid argument `%s`" % o) return ".".join(parts)
def fqn(o)
Returns the fully qualified class name of an object or a class :param o: object or class :return: class name >>> import concurrency.fields >>> fqn('str') Traceback (most recent call last): ... ValueError: Invalid argument `str` >>> class A(object): ... def method(self): ... pass >>> str(fqn(A)) 'concurrency.utils.A' >>> str(fqn(A())) 'concurrency.utils.A' >>> str(fqn(concurrency.fields)) 'concurrency.fields' >>> str(fqn(A.method)) 'concurrency.utils.A.method'
3.432356
3.415642
1.004893
result = list() for el in iterable: if hasattr(el, "__iter__") and not isinstance(el, str): result.extend(flatten(el)) else: result.append(el) return list(result)
def flatten(iterable)
flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see: :ref:`typeiter`) :return: list Examples: >>> from adminactions.utils import flatten >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, (8,9,10)]) [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]
2.30756
2.843785
0.81144
if setting.startswith(self.prefix): self._set_attr(setting, value)
def _handler(self, sender, setting, value, **kwargs)
handler for ``setting_changed`` signal. @see :ref:`django:setting-changed`_
6.363263
8.989625
0.707845
revision_field = get_version_fieldname(obj) version = get_revision_of_object(obj) return not obj.__class__.objects.filter(**{obj._meta.pk.name: obj.pk, revision_field: version}).exists()
def is_changed(obj)
returns True if `obj` is changed or deleted on the database :param obj: :return:
4.738718
4.878729
0.971302
version_field = get_version_fieldname(model_instance) kwargs = {'pk': model_instance.pk, version_field: version} return model_instance.__class__.objects.get(**kwargs)
def get_version(model_instance, version)
try go load from the database one object with specific version :param model_instance: instance in memory :param version: version number :return:
2.93906
3.671593
0.800487
try: template = loader.get_template(template_name) except TemplateDoesNotExist: # pragma: no cover template = Template( '<h1>Conflict</h1>' '<p>The request was unsuccessful due to a conflict. ' 'The object changed during the transaction.</p>') try: saved = target.__class__._default_manager.get(pk=target.pk) except target.__class__.DoesNotExist: # pragma: no cover saved = None ctx = {'target': target, 'saved': saved, 'request_path': request.path} return ConflictResponse(template.render(ctx))
def conflict(request, target=None, template_name='409.html')
409 error handler. :param request: Request :param template_name: `409.html` :param target: The model to save
3.057348
3.259256
0.938051
subparsers = parser.add_subparsers(help='sub-command help', dest='command') add_parser = partial(_add_subparser, subparsers, parser) add_parser('list', help="list concurrency triggers") add_parser('drop', help="drop concurrency triggers") add_parser('create', help="create concurrency triggers") parser.add_argument('-d', '--database', action='store', dest='database', default=None, help='limit to this database') parser.add_argument('-t', '--trigger', action='store', dest='trigger', default=None, help='limit to this trigger name')
def add_arguments(self, parser)
Entry point for subclassed commands to add custom arguments.
2.870112
2.806354
1.022719
if self.check_concurrent_action: return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text("%s,%s" % (obj.pk, get_revision_of_object(obj)))) else: # pragma: no cover return super(ConcurrencyActionMixin, self).action_checkbox(obj)
def action_checkbox(self, obj)
A list_display column containing a checkbox widget.
7.686283
7.181798
1.070245
action_index = int(request.POST.get('index', 0)) except ValueError: # pragma: no cover action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({'action': data.getlist('action')[action_index]}) except IndexError: # pragma: no cover # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data['action'] func, name, description = self.get_actions(request)[action] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. if action_form.cleaned_data['select_across']: selected = ALL else: selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected: return None revision_field = self.model._concurrencymeta.field if self.check_concurrent_action: self.delete_selected_confirmation_template = self.get_confirmation_template() # If select_across we have to avoid the use of concurrency if selected is not ALL: filters = [] for x in selected: try: pk, version = x.split(",") except ValueError: # pragma: no cover raise ImproperlyConfigured('`ConcurrencyActionMixin` error.' 'A tuple with `primary_key, version_number` ' 'expected: `%s` found' % x) filters.append(Q(**{'pk': pk, revision_field.attname: version})) queryset = queryset.filter(reduce(operator.or_, filters)) if len(selected) != queryset.count(): messages.error(request, 'One or more record were updated. ' '(Probably by other user) ' 'The execution was aborted.') return HttpResponseRedirect(".") else: messages.warning(request, 'Selecting all records, you will avoid the concurrency check') response = func(self, request, queryset) # Actions may return an HttpResponse, which will be used as the # response from the POST. If not, we'll be a good little HTTP # citizen and redirect back to the changelist page. if isinstance(response, HttpResponse): return response else: return HttpResponseRedirect(".")
def response_action(self, request, queryset): # noqa # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try
Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise.
4.48867
4.46636
1.004995
if self.is_bound: form = ConcurrentManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError('ManagementForm data is missing or has been tampered with') else: form = ConcurrentManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MAX_NUM_FORM_COUNT: self.max_num}, versions=[(form.instance.pk, get_revision_of_object(form.instance)) for form in self.initial_forms]) return form
def _management_form(self)
Returns the ManagementForm instance for this FormSet.
3.971045
3.285402
1.208694
if self.pkalg == PubKeyAlgorithm.RSAEncryptOrSign: # pad up ct with null bytes if necessary ct = self.ct.me_mod_n.to_mpibytes()[2:] ct = b'\x00' * ((pk.keymaterial.__privkey__().key_size // 8) - len(ct)) + ct decrypter = pk.keymaterial.__privkey__().decrypt decargs = (ct, padding.PKCS1v15(),) elif self.pkalg == PubKeyAlgorithm.ECDH: decrypter = pk decargs = () else: raise NotImplementedError(self.pkalg) m = bytearray(self.ct.decrypt(decrypter, *decargs)) symalg = SymmetricKeyAlgorithm(m[0]) del m[0] symkey = m[:symalg.key_size // 8] del m[:symalg.key_size // 8] checksum = self.bytes_to_int(m[:2]) del m[:2] if not sum(symkey) % 65536 == checksum: # pragma: no cover raise PGPDecryptionError("{:s} decryption failed".format(self.pkalg.name)) return (symalg, symkey)
def decrypt_sk(self, pk)
The value "m" in the above formulas is derived from the session key as follows. First, the session key is prefixed with a one-octet algorithm identifier that specifies the symmetric encryption algorithm used to encrypt the following Symmetrically Encrypted Data Packet. Then a two-octet checksum is appended, which is equal to the sum of the preceding session key octets, not including the algorithm identifier, modulo 65536. This value is then encoded as described in PKCS#1 block encoding EME-PKCS1-v1_5 in Section 7.2.1 of [RFC3447] to form the "m" value used in the formulas above. See Section 13.1 of this document for notes on OpenPGP's use of PKCS#1.
5.244931
4.90923
1.068382
if 'PreferredSymmetricAlgorithms' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_PreferredSymmetricAlgorithms'])).flags return []
def cipherprefs(self)
A ``list`` of preferred symmetric algorithms specified in this signature, if any. Otherwise, an empty ``list``.
15.040955
9.922097
1.515905
if 'PreferredCompressionAlgorithms' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_PreferredCompressionAlgorithms'])).flags return []
def compprefs(self)
A ``list`` of preferred compression algorithms specified in this signature, if any. Otherwise, an empty ``list``.
18.077747
9.576556
1.887709
if 'SignatureExpirationTime' in self._signature.subpackets: expd = next(iter(self._signature.subpackets['SignatureExpirationTime'])).expires return self.created + expd return None
def expires_at(self)
A :py:obj:`~datetime.datetime` of when this signature expires, if a signature expiration date is specified. Otherwise, ``None``
11.241933
9.907758
1.13466
if 'ExportableCertification' in self._signature.subpackets: return bool(next(iter(self._signature.subpackets['ExportableCertification']))) return True
def exportable(self)
``False`` if this signature is marked as being not exportable. Otherwise, ``True``.
9.458079
7.951941
1.189405
if 'Features' in self._signature.subpackets: return next(iter(self._signature.subpackets['Features'])).flags return set()
def features(self)
A ``set`` of implementation features specified in this signature, if any. Otherwise, an empty ``set``.
11.0809
7.173638
1.544669
if 'PreferredHashAlgorithms' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_PreferredHashAlgorithms'])).flags return []
def hashprefs(self)
A ``list`` of preferred hash algorithms specified in this signature, if any. Otherwise, an empty ``list``.
17.674337
10.68213
1.654571
expires_at = self.expires_at if expires_at is not None and expires_at != self.created: return expires_at < datetime.utcnow() return False
def is_expired(self)
``True`` if the signature has an expiration date, and is expired. Otherwise, ``False``
3.738897
3.796057
0.984942
if 'KeyFlags' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_KeyFlags'])).flags return set()
def key_flags(self)
A ``set`` of :py:obj:`~constants.KeyFlags` specified in this signature, if any. Otherwise, an empty ``set``.
11.98043
8.569075
1.398101
if 'PreferredKeyServer' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_PreferredKeyServer'])).uri return ''
def keyserver(self)
The preferred key server specified in this signature, if any. Otherwise, an empty ``str``.
13.535634
9.665716
1.400376
if 'KeyServerPreferences' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_KeyServerPreferences'])).flags return []
def keyserverprefs(self)
A ``list`` of :py:obj:`~constants.KeyServerPreferences` in this signature, if any. Otherwise, an empty ``list``.
12.967335
8.36969
1.549321
return dict((nd.name, nd.value) for nd in self._signature.subpackets['NotationData'])
def notation(self)
A ``dict`` of notation data in this signature, if any. Otherwise, an empty ``dict``.
20.700495
12.36648
1.67392
if 'Policy' in self._signature.subpackets: return next(iter(self._signature.subpackets['Policy'])).uri return ''
def policy_uri(self)
The policy URI specified in this signature, if any. Otherwise, an empty ``str``.
7.953433
5.097101
1.560383
if 'Revocable' in self._signature.subpackets: return bool(next(iter(self._signature.subpackets['Revocable']))) return True
def revocable(self)
``False`` if this signature is marked as being not revocable. Otherwise, ``True``.
6.693233
6.259713
1.069256
_data = bytearray() if isinstance(subject, six.string_types): subject = subject.encode('charmap') if self.type == SignatureType.BinaryDocument: if isinstance(subject, (SKEData, IntegrityProtectedSKEData)): _data += subject.__bytearray__() else: _data += bytearray(subject) if self.type == SignatureType.CanonicalDocument: _data += re.subn(br'\r?\n', b'\r\n', subject)[0] if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert, SignatureType.Positive_Cert, SignatureType.CertRevocation, SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}: _s = b'' if isinstance(subject, PGPUID): _s = subject._parent.hashdata elif isinstance(subject, PGPKey) and not subject.is_primary: _s = subject._parent.hashdata elif isinstance(subject, PGPKey) and subject.is_primary: _s = subject.hashdata if len(_s) > 0: _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s if self.type in {SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}: if subject.is_primary: _s = subject.subkeys[self.signer].hashdata else: _s = subject.hashdata _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s if self.type in {SignatureType.KeyRevocation, SignatureType.SubkeyRevocation, SignatureType.DirectlyOnKey}: if self.type == SignatureType.SubkeyRevocation: # hash the primary key first if this is a Subkey Revocation signature _s = subject.parent.hashdata _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s _s = subject.hashdata _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert, SignatureType.Positive_Cert, SignatureType.CertRevocation}: _s = subject.hashdata if subject.is_uid: _data += b'\xb4' else: _data += b'\xd1' _data += self.int_to_bytes(len(_s), 4) + _s # if this is a new signature, do update_hlen if 0 in list(self._signature.signature): self._signature.update_hlen() hcontext = bytearray() hcontext.append(self._signature.header.version if not self.embedded else self._signature._sig.header.version) hcontext.append(self.type) hcontext.append(self.key_algorithm) hcontext.append(self.hash_algorithm) hcontext += self._signature.subpackets.__hashbytearray__() hlen = len(hcontext) _data += hcontext _data += b'\x04\xff' _data += self.int_to_bytes(hlen, 4) return bytes(_data)
def hashdata(self, subject)
All signatures are formed by producing a hash over the signature data, and then using the resulting hash in the signature algorithm.
3.056235
3.045735
1.003448
return self._uid.image.image if isinstance(self._uid, UserAttribute) else None
def image(self)
If this is a User Attribute, this will be the stored image. If this is not a User Attribute, this will be ``None``.
19.418535
7.784427
2.494536
return bool(next(iter(self.selfsig._signature.subpackets['h_PrimaryUserID']), False))
def is_primary(self)
If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, Faqlse.
87.716049
40.953419
2.141849
if self.parent is not None: return next((sig for sig in reversed(self._signatures) if sig.signer == self.parent.fingerprint.keyid), None)
def selfsig(self)
This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``.
8.529452
6.693453
1.274298
uid = PGPUID() if isinstance(pn, bytearray): uid._uid = UserAttribute() uid._uid.image.image = pn uid._uid.image.iencoding = ImageEncoding.encodingof(pn) uid._uid.update_hlen() else: uid._uid = UserID() uid._uid.name = pn uid._uid.comment = comment uid._uid.email = email uid._uid.update_hlen() return uid
def new(cls, pn, comment="", email="")
Create a new User ID or photo. :param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo. Otherwise, it will be used as the name field for a User ID. :type pn: ``bytearray``, ``str``, ``unicode`` :param comment: The comment field for a User ID. Ignored if this is a photo. :type comment: ``str``, ``unicode`` :param email: The email address field for a User ID. Ignored if this is a photo. :type email: ``str``, ``unicode`` :returns: :py:obj:`PGPUID`
6.060973
4.807449
1.260746
return set(m.encrypter for m in self._sessionkeys if isinstance(m, PKESessionKey))
def encrypters(self)
A ``set`` containing all key ids (if any) to which this message was encrypted.
17.105993
13.402735
1.276306
if self.type == 'cleartext': return self.bytes_to_text(self._message) if self.type == 'literal': return self._message.contents if self.type == 'encrypted': return self._message
def message(self)
The message contents
5.044326
4.64895
1.085046
# TODO: have 'codecs' above (in :type encoding:) link to python documentation page on codecs cleartext = kwargs.pop('cleartext', False) format = kwargs.pop('format', None) sensitive = kwargs.pop('sensitive', False) compression = kwargs.pop('compression', CompressionAlgorithm.ZIP) file = kwargs.pop('file', False) charset = kwargs.pop('encoding', None) filename = '' mtime = datetime.utcnow() msg = PGPMessage() if charset: msg.charset = charset # if format in 'tu' and isinstance(message, (six.binary_type, bytearray)): # # if message format is text or unicode and we got binary data, we'll need to transcode it to UTF-8 # message = if file and os.path.isfile(message): filename = message message = bytearray(os.path.getsize(filename)) mtime = datetime.utcfromtimestamp(os.path.getmtime(filename)) with open(filename, 'rb') as mf: mf.readinto(message) # if format is None, we can try to detect it if format is None: if isinstance(message, six.text_type): # message is definitely UTF-8 already format = 'u' elif cls.is_ascii(message): # message is probably text format = 't' else: # message is probably binary format = 'b' # if message is a binary type and we're building a textual message, we need to transcode the bytes to UTF-8 if isinstance(message, (six.binary_type, bytearray)) and (cleartext or format in 'tu'): message = message.decode(charset or 'utf-8') if cleartext: msg |= message else: # load literal data lit = LiteralData() lit._contents = bytearray(msg.text_to_bytes(message)) lit.filename = '_CONSOLE' if sensitive else os.path.basename(filename) lit.mtime = mtime lit.format = format # if cls.is_ascii(message): # lit.format = 't' lit.update_hlen() msg |= lit msg._compression = compression return msg
def new(cls, message, **kwargs)
Create a new PGPMessage object. :param message: The message to be stored. :type message: ``str``, ``unicode``, ``bytes``, ``bytearray`` :returns: :py:obj:`PGPMessage` The following optional keyword arguments can be used with :py:meth:`PGPMessage.new`: :keyword file: if True, ``message`` should be a path to a file. The contents of that file will be read and used as the contents of the message. :type file: ``bool`` :keyword cleartext: if True, the message will be cleartext with inline signatures. :type cleartext: ``bool`` :keyword sensitive: if True, the filename will be set to '_CONSOLE' to signal other OpenPGP clients to treat this message as being 'for your eyes only'. Ignored if cleartext is True. :type sensitive: ``bool`` :keyword format: Set the message format identifier. Ignored if cleartext is True. :type format: ``str`` :keyword compression: Set the compression algorithm for the new message. Defaults to :py:obj:`CompressionAlgorithm.ZIP`. Ignored if cleartext is True. :keyword encoding: Set the Charset header for the message. :type encoding: ``str`` representing a valid codec in codecs
4.712579
4.040741
1.166266
cipher_algo = prefs.pop('cipher', SymmetricKeyAlgorithm.AES256) hash_algo = prefs.pop('hash', HashAlgorithm.SHA256) # set up a new SKESessionKeyV4 skesk = SKESessionKeyV4() skesk.s2k.usage = 255 skesk.s2k.specifier = 3 skesk.s2k.halg = hash_algo skesk.s2k.encalg = cipher_algo skesk.s2k.count = skesk.s2k.halg.tuned_count if sessionkey is None: sessionkey = cipher_algo.gen_key() skesk.encrypt_sk(passphrase, sessionkey) del passphrase msg = PGPMessage() | skesk if not self.is_encrypted: skedata = IntegrityProtectedSKEDataV1() skedata.encrypt(sessionkey, cipher_algo, self.__bytes__()) msg |= skedata else: msg |= self return msg
def encrypt(self, passphrase, sessionkey=None, **prefs)
Encrypt the contents of this message using a passphrase. :param passphrase: The passphrase to use for encrypting this message. :type passphrase: ``str``, ``unicode``, ``bytes`` :optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``. If ``None``, a session key of the appropriate length will be generated randomly. .. warning:: Care should be taken when making use of this option! Session keys *absolutely need* to be unpredictable! Use the ``gen_key()`` method on the desired :py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key! :type sessionkey: ``bytes``, ``str`` :raises: :py:exc:`~errors.PGPEncryptionError` :returns: A new :py:obj:`PGPMessage` containing the encrypted contents of this message.
5.064483
4.895318
1.034557
if not self.is_encrypted: raise PGPError("This message is not encrypted!") for skesk in iter(sk for sk in self._sessionkeys if isinstance(sk, SKESessionKey)): try: symalg, key = skesk.decrypt_sk(passphrase) decmsg = PGPMessage() decmsg.parse(self.message.decrypt(key, symalg)) except (TypeError, ValueError, NotImplementedError, PGPDecryptionError): continue else: del passphrase break else: raise PGPDecryptionError("Decryption failed") return decmsg
def decrypt(self, passphrase)
Attempt to decrypt this message using a passphrase. :param passphrase: The passphrase to use to attempt to decrypt this message. :type passphrase: ``str``, ``unicode``, ``bytes`` :raises: :py:exc:`~errors.PGPDecryptionError` if decryption failed for any reason. :returns: A new :py:obj:`PGPMessage` containing the decrypted contents of this message
5.633212
5.927131
0.950411
try: expires = min(sig.key_expiration for sig in itertools.chain(iter(uid.selfsig for uid in self.userids), self.self_signatures) if sig.key_expiration is not None) except ValueError: return None else: return (self.created + expires)
def expires_at(self)
A :py:obj:`~datetime.datetime` object of when this key is to be considered expired, if any. Otherwise, ``None``
8.964972
8.407871
1.066259
expires = self.expires_at if expires is not None: return expires <= datetime.utcnow() return False
def is_expired(self)
``True`` if this key is expired, otherwise ``False``
4.814137
4.527405
1.063333
return isinstance(self._key, Primary) and not isinstance(self._key, Sub)
def is_primary(self)
``True`` if this is a primary key; ``False`` if this is a subkey
13.975923
9.884757
1.413886
return isinstance(self._key, Public) and not isinstance(self._key, Private)
def is_public(self)
``True`` if this is a public key, otherwise ``False``
9.633815
8.044993
1.197492
if self.is_public: return True if not self.is_protected: return True return self._key.unlocked
def is_unlocked(self)
``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``
7.935221
5.347828
1.483821
if self.key_algorithm in {PubKeyAlgorithm.ECDSA, PubKeyAlgorithm.ECDH}: return self._key.keymaterial.oid return next(iter(self._key.keymaterial)).bit_length()
def key_size(self)
*new in 0.4.1* The size pertaining to this key. ``int`` for non-EC key algorithms; :py:obj:`constants.EllipticCurveOID` for EC keys.
8.308076
7.086829
1.172326
if not self.is_public: if self._sibling is None or isinstance(self._sibling, weakref.ref): # create a new key shell pub = PGPKey() pub.ascii_headers = self.ascii_headers.copy() # get the public half of the primary key pub._key = self._key.pubkey() # get the public half of each subkey for skid, subkey in self.subkeys.items(): pub |= subkey.pubkey # copy user ids and user attributes for uid in self._uids: pub |= copy.copy(uid) # copy signatures that weren't copied with uids for sig in self._signatures: if sig.parent is None: pub |= copy.copy(sig) # keep connect the two halves using a weak reference self._sibling = weakref.ref(pub) pub._sibling = weakref.ref(self) return self._sibling() return None
def pubkey(self)
If the :py:obj:`PGPKey` object is a private key, this method returns a corresponding public key object with all the trimmings. Otherwise, returns ``None``
5.636539
5.272158
1.069114
# new private key shell first key = PGPKey() if key_algorithm in {PubKeyAlgorithm.RSAEncrypt, PubKeyAlgorithm.RSASign}: # pragma: no cover warnings.warn('{:s} is deprecated - generating key using RSAEncryptOrSign'.format(key_algorithm.name)) key_algorithm = PubKeyAlgorithm.RSAEncryptOrSign # generate some key data to match key_algorithm and key_size key._key = PrivKeyV4.new(key_algorithm, key_size) return key
def new(cls, key_algorithm, key_size)
Generate a new PGP key :param key_algorithm: Key algorithm to use. :type key_algorithm: A :py:obj:`~constants.PubKeyAlgorithm` :param key_size: Key size in bits, unless `key_algorithm` is :py:obj:`~constants.PubKeyAlgorithm.ECDSA` or :py:obj:`~constants.PubKeyAlgorithm.ECDH`, in which case it should be the Curve OID to use. :type key_size: ``int`` or :py:obj:`~constants.EllipticCurveOID` :return: A newly generated :py:obj:`PGPKey`
8.134716
8.098919
1.00442
##TODO: specify strong defaults for enc_alg and hash_alg if self.is_public: # we can't protect public keys because only private key material is ever protected warnings.warn("Public keys cannot be passphrase-protected", stacklevel=2) return if self.is_protected and not self.is_unlocked: # we can't protect a key that is already protected unless it is unlocked first warnings.warn("This key is already protected with a passphrase - " "please unlock it before attempting to specify a new passphrase", stacklevel=2) return for sk in itertools.chain([self], self.subkeys.values()): sk._key.protect(passphrase, enc_alg, hash_alg) del passphrase
def protect(self, passphrase, enc_alg, hash_alg)
Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before a new passphrase can be specified. Has no effect on public keys. :param passphrase: A passphrase to protect the key with :type passphrase: ``str``, ``unicode`` :param enc_alg: Symmetric encryption algorithm to use to protect the key :type enc_alg: :py:obj:`~constants.SymmetricKeyAlgorithm` :param hash_alg: Hash algorithm to use in the String-to-Key specifier :type hash_alg: :py:obj:`~constants.HashAlgorithm`
5.486936
5.30071
1.035132
if self.is_public: # we can't unprotect public keys because only private key material is ever protected warnings.warn("Public keys cannot be passphrase-protected", stacklevel=3) yield self return if not self.is_protected: # we can't unprotect private keys that are not protected, because there is no ciphertext to decrypt warnings.warn("This key is not protected with a passphrase", stacklevel=3) yield self return try: for sk in itertools.chain([self], self.subkeys.values()): sk._key.unprotect(passphrase) del passphrase yield self finally: # clean up here by deleting the previously decrypted secret key material for sk in itertools.chain([self], self.subkeys.values()): sk._key.keymaterial.clear()
def unlock(self, passphrase)
Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both private and passphrase-protected. When the context managed block is exited, the unprotected private key material is removed. Example:: privkey = PGPKey() privkey.parse(keytext) assert privkey.is_protected assert privkey.is_unlocked is False # privkey.sign("some text") <- this would raise an exception with privkey.unlock("TheCorrectPassphrase"): # privkey is now unlocked assert privkey.is_unlocked # so you can do things with it sig = privkey.sign("some text") # privkey is no longer unlocked assert privkey.is_unlocked is False Emits a :py:obj:`~warnings.UserWarning` if the key is public or not passphrase protected. :param str passphrase: The passphrase to be used to unlock this key. :raises: :py:exc:`~pgpy.errors.PGPDecryptionError` if the passphrase is incorrect
5.593434
5.07853
1.101388
uid._parent = self if selfsign: uid |= self.certify(uid, SignatureType.Positive_Cert, **prefs) self |= uid
def add_uid(self, uid, selfsign=True, **prefs)
Add a User ID to this key. :param uid: The user id to add :type uid: :py:obj:`~pgpy.PGPUID` :param selfsign: Whether or not to self-sign the user id before adding it :type selfsign: ``bool`` Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`. Any such keyword arguments are ignored if selfsign is ``False``
20.059992
18.232386
1.10024
if self.is_primary: return next((u for u in self._uids if search in filter(lambda a: a is not None, (u.name, u.comment, u.email))), None) return self.parent.get_uid(search)
def get_uid(self, search)
Find and return a User ID that matches the search string given. :param search: A text string to match name, comment, or email address against :type search: ``str``, ``unicode`` :return: The first matching :py:obj:`~pgpy.PGPUID`, or ``None`` if no matches were found.
4.930096
4.208429
1.171481
u = self.get_uid(search) if u is None: raise KeyError("uid '{:s}' not found".format(search)) u._parent = None self._uids.remove(u)
def del_uid(self, search)
Find and remove a user id that matches the search string given. This method does not modify the corresponding :py:obj:`~pgpy.PGPUID` object; it only removes it from the list of user ids on the key. :param search: A text string to match name, comment, or email address against :type search: ``str``, ``unicode``
3.687864
4.521945
0.815548
if self.is_public: raise PGPError("Cannot add a subkey to a public key. Add the subkey to the private component first!") if key.is_public: raise PGPError("Cannot add a public key as a subkey to this key") if key.is_primary: if len(key._children) > 0: raise PGPError("Cannot add a key that already has subkeys as a subkey!") # convert key into a subkey npk = PrivSubKeyV4() npk.pkalg = key._key.pkalg npk.created = key._key.created npk.keymaterial = key._key.keymaterial key._key = npk key._key.update_hlen() self._children[key.fingerprint.keyid] = key key._parent = self ##TODO: skip this step if the key already has a subkey binding signature bsig = self.bind(key, **prefs) key |= bsig
def add_subkey(self, key, **prefs)
Add a key as a subkey to this key. :param key: A private :py:obj:`~pgpy.PGPKey` that does not have any subkeys of its own :keyword usage: A ``set`` of key usage flags, as :py:obj:`~constants.KeyFlags` for the subkey to be added. :type usage: ``set`` Other valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`
5.464118
5.280661
1.034741
user = prefs.pop('user', None) uid = None if user is not None: uid = self.get_uid(user) else: uid = next(iter(self.userids), None) if uid is None and self.parent is not None: uid = next(iter(self.parent.userids), None) if sig.hash_algorithm is None: sig._signature.halg = uid.selfsig.hashprefs[0] if uid is not None and sig.hash_algorithm not in uid.selfsig.hashprefs: warnings.warn("Selected hash algorithm not in key preferences", stacklevel=4) # signature options that can be applied at any level expires = prefs.pop('expires', None) notation = prefs.pop('notation', None) revocable = prefs.pop('revocable', True) policy_uri = prefs.pop('policy_uri', None) if expires is not None: # expires should be a timedelta, so if it's a datetime, turn it into a timedelta if isinstance(expires, datetime): expires = expires - self.created sig._signature.subpackets.addnew('SignatureExpirationTime', hashed=True, expires=expires) if revocable is False: sig._signature.subpackets.addnew('Revocable', hashed=True, bflag=revocable) if notation is not None: for name, value in notation.items(): # mark all notations as human readable unless value is a bytearray flags = NotationDataFlags.HumanReadable if isinstance(value, bytearray): flags = 0x00 sig._signature.subpackets.addnew('NotationData', hashed=True, flags=flags, name=name, value=value) if policy_uri is not None: sig._signature.subpackets.addnew('Policy', hashed=True, uri=policy_uri) if user is not None and uid is not None: signers_uid = "{:s}".format(uid) sig._signature.subpackets.addnew('SignersUserID', hashed=True, userid=signers_uid) # handle an edge case for timestamp signatures vs standalone signatures if sig.type == SignatureType.Timestamp and len(sig._signature.subpackets._hashed_sp) > 1: sig._signature.sigtype = SignatureType.Standalone sigdata = sig.hashdata(subject) h2 = sig.hash_algorithm.hasher h2.update(sigdata) sig._signature.hash2 = bytearray(h2.digest()[:2]) _sig = self._key.sign(sigdata, getattr(hashes, sig.hash_algorithm.name)()) if _sig is NotImplemented: raise NotImplementedError(self.key_algorithm) sig._signature.signature.from_signer(_sig) sig._signature.update_hlen() return sig
def _sign(self, subject, sig, **prefs)
The actual signing magic happens here. :param subject: The subject to sign :param sig: The :py:obj:`PGPSignature` object the new signature is to be encapsulated within :returns: ``sig``, after the signature is added to it.
4.156353
4.121315
1.008501
sig_type = SignatureType.BinaryDocument hash_algo = prefs.pop('hash', None) if subject is None: sig_type = SignatureType.Timestamp if isinstance(subject, PGPMessage): if subject.type == 'cleartext': sig_type = SignatureType.CanonicalDocument subject = subject.message sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid) return self._sign(subject, sig, **prefs)
def sign(self, subject, **prefs)
Sign text, a message, or a timestamp using this key. :param subject: The text to be signed :type subject: ``str``, :py:obj:`~pgpy.PGPMessage`, ``None`` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public :returns: :py:obj:`PGPSignature` The following optional keyword arguments can be used with :py:meth:`PGPKey.sign`, as well as :py:meth:`PGPKey.certify`, :py:meth:`PGPKey.revoke`, and :py:meth:`PGPKey.bind`: :keyword expires: Set an expiration date for this signature :type expires: :py:obj:`~datetime.datetime`, :py:obj:`~datetime.timedelta` :keyword notation: Add arbitrary notation data to this signature. :type notation: ``dict`` :keyword policy_uri: Add a URI to the signature that should describe the policy under which the signature was issued. :type policy_uri: ``str`` :keyword revocable: If ``False``, this signature will be marked non-revocable :type revocable: ``bool`` :keyword user: Specify which User ID to use when creating this signature. Also adds a "Signer's User ID" to the signature. :type user: ``str``
4.905303
5.21023
0.941475
hash_algo = prefs.pop('hash', None) if isinstance(target, PGPUID): sig_type = SignatureType.CertRevocation elif isinstance(target, PGPKey): ##TODO: check to make sure that the key that is being revoked: # - is this key # - is one of this key's subkeys # - specifies this key as its revocation key if target.is_primary: sig_type = SignatureType.KeyRevocation else: sig_type = SignatureType.SubkeyRevocation else: # pragma: no cover raise TypeError sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid) # signature options that only make sense when revoking reason = prefs.pop('reason', RevocationReason.NotSpecified) comment = prefs.pop('comment', "") sig._signature.subpackets.addnew('ReasonForRevocation', hashed=True, code=reason, string=comment) return self._sign(target, sig, **prefs)
def revoke(self, target, **prefs)
Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far. :param target: The key to revoke :type target: :py:obj:`PGPKey`, :py:obj:`PGPUID` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public :returns: :py:obj:`PGPSignature` In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional keyword arguments can be used with :py:meth:`PGPKey.revoke`. :keyword reason: Defaults to :py:obj:`constants.RevocationReason.NotSpecified` :type reason: One of :py:obj:`constants.RevocationReason`. :keyword comment: Defaults to an empty string. :type comment: ``str``
5.687945
5.315193
1.070129
hash_algo = prefs.pop('hash', None) sig = PGPSignature.new(SignatureType.DirectlyOnKey, self.key_algorithm, hash_algo, self.fingerprint.keyid) # signature options that only make sense when adding a revocation key sensitive = prefs.pop('sensitive', False) keyclass = RevocationKeyClass.Normal | (RevocationKeyClass.Sensitive if sensitive else 0x00) sig._signature.subpackets.addnew('RevocationKey', hashed=True, algorithm=revoker.key_algorithm, fingerprint=revoker.fingerprint, keyclass=keyclass) # revocation keys should really not be revocable themselves prefs['revocable'] = False return self._sign(self, sig, **prefs)
def revoker(self, revoker, **prefs)
Generate a signature that specifies another key as being valid for revoking this key. :param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key. :type revoker: :py:obj:`PGPKey` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public :returns: :py:obj:`PGPSignature` In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional keyword arguments can be used with :py:meth:`PGPKey.revoker`. :keyword sensitive: If ``True``, this sets the sensitive flag on the RevocationKey subpacket. Currently, this has no other effect. :type sensitive: ``bool``
7.447409
7.554368
0.985841
hash_algo = prefs.pop('hash', None) if self.is_primary and not key.is_primary: sig_type = SignatureType.Subkey_Binding elif key.is_primary and not self.is_primary: sig_type = SignatureType.PrimaryKey_Binding else: # pragma: no cover raise PGPError sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid) if sig_type == SignatureType.Subkey_Binding: # signature options that only make sense in subkey binding signatures usage = prefs.pop('usage', None) if usage is not None: sig._signature.subpackets.addnew('KeyFlags', hashed=True, flags=usage) # if possible, have the subkey create a primary key binding signature if key.key_algorithm.can_sign: subkeyid = key.fingerprint.keyid esig = None if not key.is_public: esig = key.bind(self) elif subkeyid in self.subkeys: # pragma: no cover esig = self.subkeys[subkeyid].bind(self) if esig is not None: sig._signature.subpackets.addnew('EmbeddedSignature', hashed=False, _sig=esig._signature) return self._sign(key, sig, **prefs)
def bind(self, key, **prefs)
Bind a subkey to this key. Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPkey.certify`
4.258503
4.072633
1.045639
sspairs = [] # some type checking if not isinstance(subject, (type(None), PGPMessage, PGPKey, PGPUID, PGPSignature, six.string_types, bytes, bytearray)): raise TypeError("Unexpected subject value: {:s}".format(str(type(subject)))) if not isinstance(signature, (type(None), PGPSignature)): raise TypeError("Unexpected signature value: {:s}".format(str(type(signature)))) def _filter_sigs(sigs): _ids = {self.fingerprint.keyid} | set(self.subkeys) return [ sig for sig in sigs if sig.signer in _ids ] # collect signature(s) if signature is None: if isinstance(subject, PGPMessage): sspairs += [ (sig, subject.message) for sig in _filter_sigs(subject.signatures) ] if isinstance(subject, (PGPUID, PGPKey)): sspairs += [ (sig, subject) for sig in _filter_sigs(subject.__sig__) ] if isinstance(subject, PGPKey): # user ids sspairs += [ (sig, uid) for uid in subject.userids for sig in _filter_sigs(uid.__sig__) ] # user attributes sspairs += [ (sig, ua) for ua in subject.userattributes for sig in _filter_sigs(ua.__sig__) ] # subkey binding signatures sspairs += [ (sig, subkey) for subkey in subject.subkeys.values() for sig in _filter_sigs(subkey.__sig__) ] elif signature.signer in {self.fingerprint.keyid} | set(self.subkeys): sspairs += [(signature, subject)] if len(sspairs) == 0: raise PGPError("No signatures to verify") # finally, start verifying signatures sigv = SignatureVerification() for sig, subj in sspairs: if self.fingerprint.keyid != sig.signer and sig.signer in self.subkeys: warnings.warn("Signature was signed with this key's subkey: {:s}. " "Verifying with subkey...".format(sig.signer), stacklevel=2) sigv &= self.subkeys[sig.signer].verify(subj, sig) else: verified = self._key.verify(sig.hashdata(subj), sig.__sig__, getattr(hashes, sig.hash_algorithm.name)()) if verified is NotImplemented: raise NotImplementedError(sig.key_algorithm) sigv.add_sigsubj(sig, self.fingerprint.keyid, subj, verified) return sigv
def verify(self, subject, signature=None)
Verify a subject with a signature using this key. :param subject: The subject to verify :type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID` :param signature: If the signature is detached, it should be specified here. :type signature: :py:obj:`PGPSignature` :returns: :py:obj:`~pgpy.types.SignatureVerification`
3.059341
2.938252
1.041211
user = prefs.pop('user', None) uid = None if user is not None: uid = self.get_uid(user) else: uid = next(iter(self.userids), None) if uid is None and self.parent is not None: uid = next(iter(self.parent.userids), None) cipher_algo = prefs.pop('cipher', uid.selfsig.cipherprefs[0]) if cipher_algo not in uid.selfsig.cipherprefs: warnings.warn("Selected symmetric algorithm not in key preferences", stacklevel=3) if message.is_compressed and message._compression not in uid.selfsig.compprefs: warnings.warn("Selected compression algorithm not in key preferences", stacklevel=3) if sessionkey is None: sessionkey = cipher_algo.gen_key() # set up a new PKESessionKeyV3 pkesk = PKESessionKeyV3() pkesk.encrypter = bytearray(binascii.unhexlify(self.fingerprint.keyid.encode('latin-1'))) pkesk.pkalg = self.key_algorithm # pkesk.encrypt_sk(self.__key__, cipher_algo, sessionkey) pkesk.encrypt_sk(self._key, cipher_algo, sessionkey) if message.is_encrypted: # pragma: no cover _m = message else: _m = PGPMessage() skedata = IntegrityProtectedSKEDataV1() skedata.encrypt(sessionkey, cipher_algo, message.__bytes__()) _m |= skedata _m |= pkesk return _m
def encrypt(self, message, sessionkey=None, **prefs)
Encrypt a PGPMessage using this key. :param message: The message to encrypt. :type message: :py:obj:`PGPMessage` :optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``. If ``None``, a session key of the appropriate length will be generated randomly. .. warning:: Care should be taken when making use of this option! Session keys *absolutely need* to be unpredictable! Use the ``gen_key()`` method on the desired :py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key! :type sessionkey: ``bytes``, ``str`` :raises: :py:exc:`~errors.PGPEncryptionError` if encryption failed for any reason. :returns: A new :py:obj:`PGPMessage` with the encrypted contents of ``message`` The following optional keyword arguments can be used with :py:meth:`PGPKey.encrypt`: :keyword cipher: Specifies the symmetric block cipher to use when encrypting the message. :type cipher: :py:obj:`~constants.SymmetricKeyAlgorithm` :keyword user: Specifies the User ID to use as the recipient for this encryption operation, for the purposes of preference defaults and selection validation. :type user: ``str``, ``unicode``
4.764626
4.279542
1.113349
if not message.is_encrypted: warnings.warn("This message is not encrypted", stacklevel=3) return message if self.fingerprint.keyid not in message.encrypters: sks = set(self.subkeys) mis = set(message.encrypters) if sks & mis: skid = list(sks & mis)[0] warnings.warn("Message was encrypted with this key's subkey: {:s}. " "Decrypting with that...".format(skid), stacklevel=2) return self.subkeys[skid].decrypt(message) raise PGPError("Cannot decrypt the provided message with this key") pkesk = next(pk for pk in message._sessionkeys if pk.pkalg == self.key_algorithm and pk.encrypter == self.fingerprint.keyid) alg, key = pkesk.decrypt_sk(self._key) # now that we have the symmetric cipher used and the key, we can decrypt the actual message decmsg = PGPMessage() decmsg.parse(message.message.decrypt(key, alg)) return decmsg
def decrypt(self, message)
Decrypt a PGPMessage using this key. :param message: An encrypted :py:obj:`PGPMessage` :raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked. :raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason. :returns: A new :py:obj:`PGPMessage` with the decrypted contents of ``message``.
5.26761
4.995846
1.054398
def _preiter(first, iterable): yield first for item in iterable: yield item loaded = set() for key in iter(item for ilist in iter(ilist if isinstance(ilist, (tuple, list)) else [ilist] for ilist in args) for item in ilist): if os.path.isfile(key): _key, keys = PGPKey.from_file(key) else: _key, keys = PGPKey.from_blob(key) for ik in _preiter(_key, keys.values()): self._add_key(ik) loaded |= {ik.fingerprint} | {isk.fingerprint for isk in ik.subkeys.values()} return list(loaded)
def load(self, *args)
Load all keys provided into this keyring object. :param \*args: Each arg in ``args`` can be any of the formats supported by :py:meth:`PGPKey.from_path` and :py:meth:`PGPKey.from_blob`, or a ``list`` or ``tuple`` of these. :type \*args: ``list``, ``tuple``, ``str``, ``unicode``, ``bytes``, ``bytearray`` :returns: a ``set`` containing the unique fingerprints of all of the keys that were loaded during this operation.
5.659553
4.606062
1.228718
if isinstance(identifier, PGPMessage): for issuer in identifier.issuers: if issuer in self: identifier = issuer break if isinstance(identifier, PGPSignature): identifier = identifier.signer yield self._get_key(identifier)
def key(self, identifier)
A context-manager method. Yields the first :py:obj:`PGPKey` object that matches the provided identifier. :param identifier: The identifier to use to select a loaded key. :type identifier: :py:exc:`PGPMessage`, :py:exc:`PGPSignature`, ``str`` :raises: :py:exc:`KeyError` if there is no loaded key that satisfies the identifier.
5.613978
4.192415
1.33908
return {pk.fingerprint for pk in self._keys.values() if pk.is_primary in [True if keytype in ['primary', 'any'] else None, False if keytype in ['sub', 'any'] else None] if pk.is_public in [True if keyhalf in ['public', 'any'] else None, False if keyhalf in ['private', 'any'] else None]}
def fingerprints(self, keyhalf='any', keytype='any')
List loaded fingerprints with some optional filtering. :param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the the other type will not be included in the results. :param str keytype: Can be 'any', 'primary', or 'sub'. If 'primary' or 'sub', the fingerprints of keys of the the other type will not be included in the results. :returns: a ``set`` of fingerprints of keys matching the filters specified.
3.369635
2.946246
1.143704
assert isinstance(key, PGPKey) pkid = id(key) if pkid in self._keys: # remove references [ kd.remove(pkid) for kd in [self._pubkeys, self._privkeys] if pkid in kd ] # remove the key self._keys.pop(pkid) # remove aliases for m, a in [ (m, a) for m in self._aliases for a, p in m.items() if p == pkid ]: m.pop(a) # do a re-sort of this alias if it was not unique if a in self: self._sort_alias(a) # if key is a primary key, unload its subkeys as well if key.is_primary: [ self.unload(sk) for sk in key.subkeys.values() ]
def unload(self, key)
Unload a loaded key and its subkeys. The easiest way to do this is to select a key using :py:meth:`PGPKeyring.key` first:: with keyring.key("DSA von TestKey") as key: keyring.unload(key) :param key: The key to unload. :type key: :py:obj:`PGPKey`
4.144287
4.135407
1.002147
self._lenfmt = ((packet[0] & 0x40) >> 6) self.tag = packet[0] if self._lenfmt == 0: self.llen = (packet[0] & 0x03) del packet[0] if (self._lenfmt == 0 and self.llen > 0) or self._lenfmt == 1: self.length = packet else: # indeterminate packet length self.length = len(packet)
def parse(self, packet)
There are two formats for headers old style --------- Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length. If the header length is 1 octet (length_type == 3), then there is no Length field. new style --------- New style headers can be 2, 3, or 6 octets long and are also composed of a Tag and a Length. Packet Tag ---------- The packet tag is the first byte, comprising the following fields: +-------------+----------+---------------+---+---+---+---+----------+----------+ | byte | 1 | +-------------+----------+---------------+---+---+---+---+----------+----------+ | bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | +-------------+----------+---------------+---+---+---+---+----------+----------+ | old-style | always 1 | packet format | packet tag | length type | | description | | 0 = old-style | | 0 = 1 octet | | | | 1 = new-style | | 1 = 2 octets | | | | | | 2 = 5 octets | | | | | | 3 = no length field | +-------------+ + +---------------+---------------------+ | new-style | | | packet tag | | description | | | | +-------------+----------+---------------+-------------------------------------+ :param packet: raw packet bytes
3.98081
3.78234
1.052473
for field in self.__privfields__: delattr(self, field) setattr(self, field, MPI(0))
def clear(self)
delete and re-initialize all private components to zero
12.037214
9.156766
1.31457
# *args should be: # - m # _m, = args # m may need to be PKCS5-padded padder = PKCS7(64).padder() m = padder.update(_m) + padder.finalize() km = pk.keymaterial ct = cls() # generate ephemeral key pair, then store it in ct v = ec.generate_private_key(km.oid.curve(), default_backend()) ct.vX = MPI(v.public_key().public_numbers().x) ct.vY = MPI(v.public_key().public_numbers().y) # compute the shared point S s = v.exchange(ec.ECDH(), km.__pubkey__()) # derive the wrapping key z = km.kdf.derive_key(s, km.oid, PubKeyAlgorithm.ECDH, pk.fingerprint) # compute C ct.c = aes_key_wrap(z, m, default_backend()) return ct
def encrypt(cls, pk, *args)
For convenience, the synopsis of the encoding method is given below; however, this section, [NIST-SP800-56A], and [RFC3394] are the normative sources of the definition. Obtain the authenticated recipient public key R Generate an ephemeral key pair {v, V=vG} Compute the shared point S = vR; m = symm_alg_ID || session key || checksum || pkcs5_padding; curve_OID_len = (byte)len(curve_OID); Param = curve_OID_len || curve_OID || public_key_alg_ID || 03 || 01 || KDF_hash_ID || KEK_alg_ID for AESKeyWrap || "Anonymous Sender " || recipient_fingerprint; Z_len = the key size for the KEK_alg_ID used with AESKeyWrap Compute Z = KDF( S, Z_len, Param ); Compute C = AESKeyWrap( Z, m ) as per [RFC3394] VB = convert point V to the octet string Output (MPI(VB) || len(C) || C). The decryption is the inverse of the method given. Note that the recipient obtains the shared secret by calculating
6.50784
6.023502
1.080408
if isinstance(text, (bytes, bytearray)): # pragma: no cover text = text.decode('latin-1') return Armorable.__armor_regex.search(text) is not None
def is_armor(text)
Whether the ``text`` provided is an ASCII-armored PGP block. :param text: A possible ASCII-armored PGP block. :raises: :py:exc:`TypeError` if ``text`` is not a ``str``, ``bytes``, or ``bytearray`` :returns: Whether the text is ASCII-armored.
5.519901
4.924986
1.120795
m = {'magic': None, 'headers': None, 'body': bytearray(), 'crc': None} if not Armorable.is_ascii(text): m['body'] = bytearray(text) return m if isinstance(text, (bytes, bytearray)): # pragma: no cover text = text.decode('latin-1') m = Armorable.__armor_regex.search(text) if m is None: # pragma: no cover raise ValueError("Expected: ASCII-armored PGP data") m = m.groupdict() if m['hashes'] is not None: m['hashes'] = m['hashes'].split(',') if m['headers'] is not None: m['headers'] = collections.OrderedDict(re.findall('^(?P<key>.+): (?P<value>.+)$\n?', m['headers'], flags=re.MULTILINE)) if m['body'] is not None: try: m['body'] = bytearray(base64.b64decode(m['body'].encode())) except (binascii.Error, TypeError) as ex: six.raise_from(PGPError, ex) six.raise_from(PGPError(str(ex)), ex) if m['crc'] is not None: m['crc'] = Header.bytes_to_int(base64.b64decode(m['crc'].encode())) if Armorable.crc24(m['body']) != m['crc']: warnings.warn('Incorrect crc24', stacklevel=3) return m
def ascii_unarmor(text)
Takes an ASCII-armored PGP block and returns the decoded byte value. :param text: An ASCII-armored PGP block, to un-armor. :raises: :py:exc:`ValueError` if ``text`` did not contain an ASCII-armored PGP block. :raises: :py:exc:`TypeError` if ``text`` is not a ``str``, ``bytes``, or ``bytearray`` :returns: A ``dict`` containing information from ``text``, including the de-armored data. It can contain the following keys: ``magic``, ``headers``, ``hashes``, ``cleartext``, ``body``, ``crc``.
3.091776
2.639164
1.171498
# save the original type of b without having to copy any data _b = b.__class__() if order != 'little': b = reversed(b) if not isinstance(_b, bytearray): b = six.iterbytes(b) return sum(c << (i * 8) for i, c in enumerate(b)) return int.from_bytes(b, order)
def bytes_to_int(b, order='big'): # pragma: no cover if six.PY2
convert bytes to integer
6.173201
5.802232
1.063936
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1))) return bytes(bytearray((i >> c) & 0xff for c in r)) return i.to_bytes(blen, order)
def int_to_bytes(i, minlen=1, order='big'): # pragma: no cover blen = max(minlen, PGPObject.int_byte_len(i), 1) if six.PY2
convert integer to bytes
4.894176
4.220881
1.159515
for s in [ i for i in self._subjects if i.verified ]: yield s
def good_signatures(self)
A generator yielding namedtuples of all signatures that were successfully verified in the operation that returned this instance. The namedtuple has the following attributes: ``sigsubj.verified`` - ``bool`` of whether the signature verified successfully or not. ``sigsubj.by`` - the :py:obj:`~pgpy.PGPKey` that was used in this verify operation. ``sigsubj.signature`` - the :py:obj:`~pgpy.PGPSignature` that was verified. ``sigsubj.subject`` - the subject that was verified using the signature.
16.300217
20.621063
0.790464
yield s
def bad_signatures(self): # pragma: no cover for s in [ i for i in self._subjects if not i.verified ]
A generator yielding namedtuples of all signatures that were not verified in the operation that returned this instance. The namedtuple has the following attributes: ``sigsubj.verified`` - ``bool`` of whether the signature verified successfully or not. ``sigsubj.by`` - the :py:obj:`~pgpy.PGPKey` that was used in this verify operation. ``sigsubj.signature`` - the :py:obj:`~pgpy.PGPSignature` that was verified. ``sigsubj.subject`` - the subject that was verified using the signature.
22,702.9375
17,307.660156
1.311728
self.resort(unsorted)
def check(self): # pragma: no cover for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1]))
re-sort any items in self that are not sorted
34.748737
20.487276
1.696113
sd = singledispatch(meth) def wrapper(obj, *args, **kwargs): return sd.dispatch(args[0].__class__)(obj, *args, **kwargs) wrapper.register = sd.register wrapper.dispatch = sd.dispatch wrapper.registry = sd.registry wrapper._clear_cache = sd._clear_cache functools.update_wrapper(wrapper, meth) return wrapper
def sdmethod(meth)
This is a hack to monkey patch sdproperty to work as expected with instance methods.
2.449498
2.342897
1.0455
def initialize_key(self, key): self.k = key self.n = 0 if self.has_key(): self.cipher.initialize(key)
:param key: Key to set within CipherState
null
null
null
def encrypt_with_ad(self, ad: bytes, plaintext: bytes) -> bytes: if self.n == MAX_NONCE: raise NoiseMaxNonceError('Nonce has depleted!') if not self.has_key(): return plaintext ciphertext = self.cipher.encrypt(self.k, self.n, ad, plaintext) self.n = self.n + 1 return ciphertext
If k is non-empty returns ENCRYPT(k, n++, ad, plaintext). Otherwise returns plaintext. :param ad: bytes sequence :param plaintext: bytes sequence :return: ciphertext bytes sequence
null
null
null
def decrypt_with_ad(self, ad: bytes, ciphertext: bytes) -> bytes: if self.n == MAX_NONCE: raise NoiseMaxNonceError('Nonce has depleted!') if not self.has_key(): return ciphertext plaintext = self.cipher.decrypt(self.k, self.n, ad, ciphertext) self.n = self.n + 1 return plaintext
If k is non-empty returns DECRYPT(k, n++, ad, ciphertext). Otherwise returns ciphertext. If an authentication failure occurs in DECRYPT() then n is not incremented and an error is signaled to the caller. :param ad: bytes sequence :param ciphertext: bytes sequence :return: plaintext bytes sequence
null
null
null
def initialize_symmetric(cls, noise_protocol: 'NoiseProtocol') -> 'SymmetricState': # Create SymmetricState instance = cls() instance.noise_protocol = noise_protocol # If protocol_name is less than or equal to HASHLEN bytes in length, sets h equal to protocol_name with zero # bytes appended to make HASHLEN bytes. Otherwise sets h = HASH(protocol_name). if len(noise_protocol.name) <= noise_protocol.hash_fn.hashlen: instance.h = noise_protocol.name.ljust(noise_protocol.hash_fn.hashlen, b'\0') else: instance.h = noise_protocol.hash_fn.hash(noise_protocol.name) # Sets ck = h. instance.ck = instance.h # Calls InitializeKey(empty). instance.cipher_state = CipherState(noise_protocol) instance.cipher_state.initialize_key(Empty()) noise_protocol.cipher_state_handshake = instance.cipher_state return instance
Instead of taking protocol_name as an argument, we take full NoiseProtocol object, that way we have access to protocol name and crypto functions Comments below are mostly copied from specification. :param noise_protocol: a valid NoiseProtocol instance :return: initialised SymmetricState instance
null
null
null
def mix_key(self, input_key_material: bytes): # Sets ck, temp_k = HKDF(ck, input_key_material, 2). self.ck, temp_k = self.noise_protocol.hkdf(self.ck, input_key_material, 2) # If HASHLEN is 64, then truncates temp_k to 32 bytes. if self.noise_protocol.hash_fn.hashlen == 64: temp_k = temp_k[:32] # Calls InitializeKey(temp_k). self.cipher_state.initialize_key(temp_k)
:param input_key_material: :return:
null
null
null
def mix_hash(self, data: bytes): self.h = self.noise_protocol.hash_fn.hash(self.h + data)
Sets h = HASH(h + data). :param data: bytes sequence
null
null
null