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))
... | 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... | 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_co... | 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... | 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:
... | 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)
... | 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":
... | 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)
... | 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]
... | 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 =... | 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)
... | 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
>>>... | 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__)
... | 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):
...... | 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 adm... | 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:
... | 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 trigg... | 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 ... | 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... | 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')
el... | 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
... | 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... | 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.__bytear... | 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.na... | 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 I... | 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', CompressionAlgor... | 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, `... | 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
... | 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``.
... | 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()
... | 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:`... | 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 ... | 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
... | 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 = Pub... | 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 ... | 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... | 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... | 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 u... | 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()
privke... | 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... | 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... | 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... | 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 argumen... | 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)
... | 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.CanonicalDocu... | 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.PG... | 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
# - i... | 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 unl... | 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 = Rev... | 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
... | 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 ... | 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(... | 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: :... | 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)
... | 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 appropr... | 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:
... | 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 :p... | 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)... | 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``, ``... | 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... | 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... | 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 Non... | 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 'su... | 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
... | 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:
# inde... | 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 he... | 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
... | 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 t... | 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 = Armor... | 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``... | 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))
... | 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:`~pg... | 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... | 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... | 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)
sel... | 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)
s... | 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... | 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 ze... | 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 Symmetr... | 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:... | :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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.