id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,900
|
Yubico/python-pyhsm
|
pyhsm/val/validation_server.py
|
ValOathDb.get
|
def get(self, key):
""" Fetch entry from database. """
c = self.conn.cursor()
for row in c.execute("SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?", (key,)):
return ValOathEntry(row)
raise Exception("OATH token for '%s' not found in database (%s)" % (key, self.filename))
|
python
|
def get(self, key):
""" Fetch entry from database. """
c = self.conn.cursor()
for row in c.execute("SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?", (key,)):
return ValOathEntry(row)
raise Exception("OATH token for '%s' not found in database (%s)" % (key, self.filename))
|
[
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"for",
"row",
"in",
"c",
".",
"execute",
"(",
"\"SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?\"",
",",
"(",
"key",
",",
")",
")",
":",
"return",
"ValOathEntry",
"(",
"row",
")",
"raise",
"Exception",
"(",
"\"OATH token for '%s' not found in database (%s)\"",
"%",
"(",
"key",
",",
"self",
".",
"filename",
")",
")"
] |
Fetch entry from database.
|
[
"Fetch",
"entry",
"from",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L479-L484
|
8,901
|
Yubico/python-pyhsm
|
pyhsm/val/validation_server.py
|
ValOathDb.update_oath_hotp_c
|
def update_oath_hotp_c(self, entry, new_c):
"""
Update the OATH-HOTP counter value for `entry' in the database.
Use SQL statement to ensure we only ever increase the counter.
"""
key = entry.data["key"]
c = self.conn.cursor()
c.execute("UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c",
(new_c, key, new_c,))
self.conn.commit()
return c.rowcount == 1
|
python
|
def update_oath_hotp_c(self, entry, new_c):
"""
Update the OATH-HOTP counter value for `entry' in the database.
Use SQL statement to ensure we only ever increase the counter.
"""
key = entry.data["key"]
c = self.conn.cursor()
c.execute("UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c",
(new_c, key, new_c,))
self.conn.commit()
return c.rowcount == 1
|
[
"def",
"update_oath_hotp_c",
"(",
"self",
",",
"entry",
",",
"new_c",
")",
":",
"key",
"=",
"entry",
".",
"data",
"[",
"\"key\"",
"]",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c\"",
",",
"(",
"new_c",
",",
"key",
",",
"new_c",
",",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"c",
".",
"rowcount",
"==",
"1"
] |
Update the OATH-HOTP counter value for `entry' in the database.
Use SQL statement to ensure we only ever increase the counter.
|
[
"Update",
"the",
"OATH",
"-",
"HOTP",
"counter",
"value",
"for",
"entry",
"in",
"the",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L486-L497
|
8,902
|
Yubico/python-pyhsm
|
examples/yhsm-password-auth.py
|
generate_aead
|
def generate_aead(hsm, args, password):
"""
Generate an AEAD using the YubiHSM.
"""
try:
pw = password.ljust(args.min_len, chr(0x0))
return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw)
except pyhsm.exception.YHSM_CommandFailed, e:
if e.status_str == 'YHSM_FUNCTION_DISABLED':
print "ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE." % (args.key_handle)
return None
else:
print "ERROR: %s" % (e.reason)
|
python
|
def generate_aead(hsm, args, password):
"""
Generate an AEAD using the YubiHSM.
"""
try:
pw = password.ljust(args.min_len, chr(0x0))
return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw)
except pyhsm.exception.YHSM_CommandFailed, e:
if e.status_str == 'YHSM_FUNCTION_DISABLED':
print "ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE." % (args.key_handle)
return None
else:
print "ERROR: %s" % (e.reason)
|
[
"def",
"generate_aead",
"(",
"hsm",
",",
"args",
",",
"password",
")",
":",
"try",
":",
"pw",
"=",
"password",
".",
"ljust",
"(",
"args",
".",
"min_len",
",",
"chr",
"(",
"0x0",
")",
")",
"return",
"hsm",
".",
"generate_aead_simple",
"(",
"args",
".",
"nonce",
".",
"decode",
"(",
"'hex'",
")",
",",
"args",
".",
"key_handle",
",",
"pw",
")",
"except",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
",",
"e",
":",
"if",
"e",
".",
"status_str",
"==",
"'YHSM_FUNCTION_DISABLED'",
":",
"print",
"\"ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE.\"",
"%",
"(",
"args",
".",
"key_handle",
")",
"return",
"None",
"else",
":",
"print",
"\"ERROR: %s\"",
"%",
"(",
"e",
".",
"reason",
")"
] |
Generate an AEAD using the YubiHSM.
|
[
"Generate",
"an",
"AEAD",
"using",
"the",
"YubiHSM",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/examples/yhsm-password-auth.py#L108-L120
|
8,903
|
Yubico/python-pyhsm
|
pyhsm/tools/decrypt_aead.py
|
aead_filename
|
def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id,
and create any missing directorys.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id)
|
python
|
def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id,
and create any missing directorys.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id)
|
[
"def",
"aead_filename",
"(",
"aead_dir",
",",
"key_handle",
",",
"public_id",
")",
":",
"parts",
"=",
"[",
"aead_dir",
",",
"key_handle",
"]",
"+",
"pyhsm",
".",
"util",
".",
"group",
"(",
"public_id",
",",
"2",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"public_id",
")"
] |
Return the filename of the AEAD for this public_id,
and create any missing directorys.
|
[
"Return",
"the",
"filename",
"of",
"the",
"AEAD",
"for",
"this",
"public_id",
"and",
"create",
"any",
"missing",
"directorys",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L234-L245
|
8,904
|
Yubico/python-pyhsm
|
pyhsm/tools/decrypt_aead.py
|
safe_process_files
|
def safe_process_files(path, files, args, state):
"""
Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going.
"""
for fn in files:
full_fn = os.path.join(path, fn)
try:
if not process_file(path, fn, args, state):
return False
except Exception, e:
sys.stderr.write("error: %s\n%s\n" % (os.path.join(path, fn), traceback.format_exc()))
state.log_failed(full_fn)
if state.should_quit():
return False
return True
|
python
|
def safe_process_files(path, files, args, state):
"""
Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going.
"""
for fn in files:
full_fn = os.path.join(path, fn)
try:
if not process_file(path, fn, args, state):
return False
except Exception, e:
sys.stderr.write("error: %s\n%s\n" % (os.path.join(path, fn), traceback.format_exc()))
state.log_failed(full_fn)
if state.should_quit():
return False
return True
|
[
"def",
"safe_process_files",
"(",
"path",
",",
"files",
",",
"args",
",",
"state",
")",
":",
"for",
"fn",
"in",
"files",
":",
"full_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fn",
")",
"try",
":",
"if",
"not",
"process_file",
"(",
"path",
",",
"fn",
",",
"args",
",",
"state",
")",
":",
"return",
"False",
"except",
"Exception",
",",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error: %s\\n%s\\n\"",
"%",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fn",
")",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
")",
"state",
".",
"log_failed",
"(",
"full_fn",
")",
"if",
"state",
".",
"should_quit",
"(",
")",
":",
"return",
"False",
"return",
"True"
] |
Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going.
|
[
"Process",
"a",
"number",
"of",
"files",
"in",
"a",
"directory",
".",
"Catches",
"any",
"exception",
"from",
"the",
"processing",
"and",
"checks",
"if",
"we",
"should",
"fail",
"directly",
"or",
"keep",
"going",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L247-L262
|
8,905
|
Yubico/python-pyhsm
|
pyhsm/tools/decrypt_aead.py
|
walk_dir
|
def walk_dir(path, args, state):
"""
Check all files in `path' to see if there is any requests that
we should send out on the bus.
"""
if args.debug:
sys.stderr.write("Walking %s\n" % path)
for root, _dirs, files in os.walk(path):
if not safe_process_files(root, files, args, state):
return False
if state.should_quit():
return False
return True
|
python
|
def walk_dir(path, args, state):
"""
Check all files in `path' to see if there is any requests that
we should send out on the bus.
"""
if args.debug:
sys.stderr.write("Walking %s\n" % path)
for root, _dirs, files in os.walk(path):
if not safe_process_files(root, files, args, state):
return False
if state.should_quit():
return False
return True
|
[
"def",
"walk_dir",
"(",
"path",
",",
"args",
",",
"state",
")",
":",
"if",
"args",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Walking %s\\n\"",
"%",
"path",
")",
"for",
"root",
",",
"_dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
"not",
"safe_process_files",
"(",
"root",
",",
"files",
",",
"args",
",",
"state",
")",
":",
"return",
"False",
"if",
"state",
".",
"should_quit",
"(",
")",
":",
"return",
"False",
"return",
"True"
] |
Check all files in `path' to see if there is any requests that
we should send out on the bus.
|
[
"Check",
"all",
"files",
"in",
"path",
"to",
"see",
"if",
"there",
"is",
"any",
"requests",
"that",
"we",
"should",
"send",
"out",
"on",
"the",
"bus",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L264-L277
|
8,906
|
Yubico/python-pyhsm
|
pyhsm/tools/decrypt_aead.py
|
main
|
def main():
""" Main function when running as a program. """
global args
args = parse_args()
if not args:
return 1
state = MyState(args)
for path in args.paths:
if os.path.isdir(path):
walk_dir(path, args, state)
else:
safe_process_files(os.path.dirname(path), [os.path.basename(path)], args, state)
if state.should_quit():
break
if state.failed_files:
sys.stderr.write("error: %i/%i AEADs failed\n" % (len(state.failed_files), state.file_count))
return 1
if args.debug:
sys.stderr.write("Successfully processed %i AEADs\n" % (state.file_count))
|
python
|
def main():
""" Main function when running as a program. """
global args
args = parse_args()
if not args:
return 1
state = MyState(args)
for path in args.paths:
if os.path.isdir(path):
walk_dir(path, args, state)
else:
safe_process_files(os.path.dirname(path), [os.path.basename(path)], args, state)
if state.should_quit():
break
if state.failed_files:
sys.stderr.write("error: %i/%i AEADs failed\n" % (len(state.failed_files), state.file_count))
return 1
if args.debug:
sys.stderr.write("Successfully processed %i AEADs\n" % (state.file_count))
|
[
"def",
"main",
"(",
")",
":",
"global",
"args",
"args",
"=",
"parse_args",
"(",
")",
"if",
"not",
"args",
":",
"return",
"1",
"state",
"=",
"MyState",
"(",
"args",
")",
"for",
"path",
"in",
"args",
".",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"walk_dir",
"(",
"path",
",",
"args",
",",
"state",
")",
"else",
":",
"safe_process_files",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"]",
",",
"args",
",",
"state",
")",
"if",
"state",
".",
"should_quit",
"(",
")",
":",
"break",
"if",
"state",
".",
"failed_files",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error: %i/%i AEADs failed\\n\"",
"%",
"(",
"len",
"(",
"state",
".",
"failed_files",
")",
",",
"state",
".",
"file_count",
")",
")",
"return",
"1",
"if",
"args",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Successfully processed %i AEADs\\n\"",
"%",
"(",
"state",
".",
"file_count",
")",
")"
] |
Main function when running as a program.
|
[
"Main",
"function",
"when",
"running",
"as",
"a",
"program",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L279-L300
|
8,907
|
Yubico/python-pyhsm
|
pyhsm/oath_hotp.py
|
search_for_oath_code
|
def search_for_oath_code(hsm, key_handle, nonce, aead, counter, user_code, look_ahead=1):
"""
Try to validate an OATH HOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns next counter value on successful auth, and None otherwise.
"""
key_handle = pyhsm.util.input_validate_key_handle(key_handle)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = False)
aead = pyhsm.util.input_validate_aead(aead)
counter = pyhsm.util.input_validate_int(counter, 'counter')
user_code = pyhsm.util.input_validate_int(user_code, 'user_code')
hsm.load_temp_key(nonce, key_handle, aead)
# User might have produced codes never sent to us, so we support trying look_ahead
# codes to see if we find the user's current code.
for j in xrange(look_ahead):
this_counter = counter + j
secret = struct.pack("> Q", this_counter)
hmac_result = hsm.hmac_sha1(pyhsm.defines.YSM_TEMP_KEY_HANDLE, secret).get_hash()
this_code = truncate(hmac_result)
if this_code == user_code:
return this_counter + 1
return None
|
python
|
def search_for_oath_code(hsm, key_handle, nonce, aead, counter, user_code, look_ahead=1):
"""
Try to validate an OATH HOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns next counter value on successful auth, and None otherwise.
"""
key_handle = pyhsm.util.input_validate_key_handle(key_handle)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = False)
aead = pyhsm.util.input_validate_aead(aead)
counter = pyhsm.util.input_validate_int(counter, 'counter')
user_code = pyhsm.util.input_validate_int(user_code, 'user_code')
hsm.load_temp_key(nonce, key_handle, aead)
# User might have produced codes never sent to us, so we support trying look_ahead
# codes to see if we find the user's current code.
for j in xrange(look_ahead):
this_counter = counter + j
secret = struct.pack("> Q", this_counter)
hmac_result = hsm.hmac_sha1(pyhsm.defines.YSM_TEMP_KEY_HANDLE, secret).get_hash()
this_code = truncate(hmac_result)
if this_code == user_code:
return this_counter + 1
return None
|
[
"def",
"search_for_oath_code",
"(",
"hsm",
",",
"key_handle",
",",
"nonce",
",",
"aead",
",",
"counter",
",",
"user_code",
",",
"look_ahead",
"=",
"1",
")",
":",
"key_handle",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_key_handle",
"(",
"key_handle",
")",
"nonce",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_nonce",
"(",
"nonce",
",",
"pad",
"=",
"False",
")",
"aead",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_aead",
"(",
"aead",
")",
"counter",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_int",
"(",
"counter",
",",
"'counter'",
")",
"user_code",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_int",
"(",
"user_code",
",",
"'user_code'",
")",
"hsm",
".",
"load_temp_key",
"(",
"nonce",
",",
"key_handle",
",",
"aead",
")",
"# User might have produced codes never sent to us, so we support trying look_ahead",
"# codes to see if we find the user's current code.",
"for",
"j",
"in",
"xrange",
"(",
"look_ahead",
")",
":",
"this_counter",
"=",
"counter",
"+",
"j",
"secret",
"=",
"struct",
".",
"pack",
"(",
"\"> Q\"",
",",
"this_counter",
")",
"hmac_result",
"=",
"hsm",
".",
"hmac_sha1",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_TEMP_KEY_HANDLE",
",",
"secret",
")",
".",
"get_hash",
"(",
")",
"this_code",
"=",
"truncate",
"(",
"hmac_result",
")",
"if",
"this_code",
"==",
"user_code",
":",
"return",
"this_counter",
"+",
"1",
"return",
"None"
] |
Try to validate an OATH HOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns next counter value on successful auth, and None otherwise.
|
[
"Try",
"to",
"validate",
"an",
"OATH",
"HOTP",
"OTP",
"generated",
"by",
"a",
"token",
"whose",
"secret",
"key",
"is",
"available",
"to",
"the",
"YubiHSM",
"through",
"the",
"AEAD",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_hotp.py#L20-L44
|
8,908
|
Yubico/python-pyhsm
|
pyhsm/oath_hotp.py
|
truncate
|
def truncate(hmac_result, length=6):
""" Perform the truncating. """
assert(len(hmac_result) == 20)
offset = ord(hmac_result[19]) & 0xf
bin_code = (ord(hmac_result[offset]) & 0x7f) << 24 \
| (ord(hmac_result[offset+1]) & 0xff) << 16 \
| (ord(hmac_result[offset+2]) & 0xff) << 8 \
| (ord(hmac_result[offset+3]) & 0xff)
return bin_code % (10 ** length)
|
python
|
def truncate(hmac_result, length=6):
""" Perform the truncating. """
assert(len(hmac_result) == 20)
offset = ord(hmac_result[19]) & 0xf
bin_code = (ord(hmac_result[offset]) & 0x7f) << 24 \
| (ord(hmac_result[offset+1]) & 0xff) << 16 \
| (ord(hmac_result[offset+2]) & 0xff) << 8 \
| (ord(hmac_result[offset+3]) & 0xff)
return bin_code % (10 ** length)
|
[
"def",
"truncate",
"(",
"hmac_result",
",",
"length",
"=",
"6",
")",
":",
"assert",
"(",
"len",
"(",
"hmac_result",
")",
"==",
"20",
")",
"offset",
"=",
"ord",
"(",
"hmac_result",
"[",
"19",
"]",
")",
"&",
"0xf",
"bin_code",
"=",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"]",
")",
"&",
"0x7f",
")",
"<<",
"24",
"|",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"+",
"1",
"]",
")",
"&",
"0xff",
")",
"<<",
"16",
"|",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"+",
"2",
"]",
")",
"&",
"0xff",
")",
"<<",
"8",
"|",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"+",
"3",
"]",
")",
"&",
"0xff",
")",
"return",
"bin_code",
"%",
"(",
"10",
"**",
"length",
")"
] |
Perform the truncating.
|
[
"Perform",
"the",
"truncating",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_hotp.py#L46-L54
|
8,909
|
Yubico/python-pyhsm
|
pyhsm/stick.py
|
YHSM_Stick.flush
|
def flush(self):
"""
Flush input buffers.
"""
if self.debug:
sys.stderr.write("%s: FLUSH INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
self.ser.flushInput()
|
python
|
def flush(self):
"""
Flush input buffers.
"""
if self.debug:
sys.stderr.write("%s: FLUSH INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
self.ser.flushInput()
|
[
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s: FLUSH INPUT (%i bytes waiting)\\n\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"ser",
".",
"inWaiting",
"(",
")",
")",
")",
"self",
".",
"ser",
".",
"flushInput",
"(",
")"
] |
Flush input buffers.
|
[
"Flush",
"input",
"buffers",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/stick.py#L91-L100
|
8,910
|
Yubico/python-pyhsm
|
pyhsm/stick.py
|
YHSM_Stick.drain
|
def drain(self):
""" Drain input. """
if self.debug:
sys.stderr.write("%s: DRAIN INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
old_timeout = self.ser.timeout
self.ser.timeout = 0.1
data = self.ser.read(1)
while len(data):
if self.debug:
sys.stderr.write("%s: DRAINED 0x%x (%c)\n" %(self.__class__.__name__, ord(data[0]), data[0]))
data = self.ser.read(1)
self.ser.timeout = old_timeout
return True
|
python
|
def drain(self):
""" Drain input. """
if self.debug:
sys.stderr.write("%s: DRAIN INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
old_timeout = self.ser.timeout
self.ser.timeout = 0.1
data = self.ser.read(1)
while len(data):
if self.debug:
sys.stderr.write("%s: DRAINED 0x%x (%c)\n" %(self.__class__.__name__, ord(data[0]), data[0]))
data = self.ser.read(1)
self.ser.timeout = old_timeout
return True
|
[
"def",
"drain",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s: DRAIN INPUT (%i bytes waiting)\\n\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"ser",
".",
"inWaiting",
"(",
")",
")",
")",
"old_timeout",
"=",
"self",
".",
"ser",
".",
"timeout",
"self",
".",
"ser",
".",
"timeout",
"=",
"0.1",
"data",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"1",
")",
"while",
"len",
"(",
"data",
")",
":",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s: DRAINED 0x%x (%c)\\n\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"ord",
"(",
"data",
"[",
"0",
"]",
")",
",",
"data",
"[",
"0",
"]",
")",
")",
"data",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"1",
")",
"self",
".",
"ser",
".",
"timeout",
"=",
"old_timeout",
"return",
"True"
] |
Drain input.
|
[
"Drain",
"input",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/stick.py#L102-L117
|
8,911
|
Yubico/python-pyhsm
|
pyhsm/ksm/db_import.py
|
extract_keyhandle
|
def extract_keyhandle(path, filepath):
"""extract keyhandle value from the path"""
keyhandle = filepath.lstrip(path)
keyhandle = keyhandle.split("/")
return keyhandle[0]
|
python
|
def extract_keyhandle(path, filepath):
"""extract keyhandle value from the path"""
keyhandle = filepath.lstrip(path)
keyhandle = keyhandle.split("/")
return keyhandle[0]
|
[
"def",
"extract_keyhandle",
"(",
"path",
",",
"filepath",
")",
":",
"keyhandle",
"=",
"filepath",
".",
"lstrip",
"(",
"path",
")",
"keyhandle",
"=",
"keyhandle",
".",
"split",
"(",
"\"/\"",
")",
"return",
"keyhandle",
"[",
"0",
"]"
] |
extract keyhandle value from the path
|
[
"extract",
"keyhandle",
"value",
"from",
"the",
"path"
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/db_import.py#L19-L24
|
8,912
|
Yubico/python-pyhsm
|
pyhsm/ksm/db_import.py
|
insert_query
|
def insert_query(connection, publicId, aead, keyhandle, aeadobj):
"""this functions read the response fields and creates sql query. then
inserts everything inside the database"""
# turn the keyhandle into an integer
keyhandle = key_handle_to_int(keyhandle)
if not keyhandle == aead.key_handle:
print("WARNING: keyhandle does not match aead.key_handle")
return None
# creates the query object
try:
sql = aeadobj.insert().values(public_id=publicId, keyhandle=aead.key_handle, nonce=aead.nonce, aead=aead.data)
# insert the query
result = connection.execute(sql)
return result
except sqlalchemy.exc.IntegrityError:
pass
return None
|
python
|
def insert_query(connection, publicId, aead, keyhandle, aeadobj):
"""this functions read the response fields and creates sql query. then
inserts everything inside the database"""
# turn the keyhandle into an integer
keyhandle = key_handle_to_int(keyhandle)
if not keyhandle == aead.key_handle:
print("WARNING: keyhandle does not match aead.key_handle")
return None
# creates the query object
try:
sql = aeadobj.insert().values(public_id=publicId, keyhandle=aead.key_handle, nonce=aead.nonce, aead=aead.data)
# insert the query
result = connection.execute(sql)
return result
except sqlalchemy.exc.IntegrityError:
pass
return None
|
[
"def",
"insert_query",
"(",
"connection",
",",
"publicId",
",",
"aead",
",",
"keyhandle",
",",
"aeadobj",
")",
":",
"# turn the keyhandle into an integer",
"keyhandle",
"=",
"key_handle_to_int",
"(",
"keyhandle",
")",
"if",
"not",
"keyhandle",
"==",
"aead",
".",
"key_handle",
":",
"print",
"(",
"\"WARNING: keyhandle does not match aead.key_handle\"",
")",
"return",
"None",
"# creates the query object",
"try",
":",
"sql",
"=",
"aeadobj",
".",
"insert",
"(",
")",
".",
"values",
"(",
"public_id",
"=",
"publicId",
",",
"keyhandle",
"=",
"aead",
".",
"key_handle",
",",
"nonce",
"=",
"aead",
".",
"nonce",
",",
"aead",
"=",
"aead",
".",
"data",
")",
"# insert the query",
"result",
"=",
"connection",
".",
"execute",
"(",
"sql",
")",
"return",
"result",
"except",
"sqlalchemy",
".",
"exc",
".",
"IntegrityError",
":",
"pass",
"return",
"None"
] |
this functions read the response fields and creates sql query. then
inserts everything inside the database
|
[
"this",
"functions",
"read",
"the",
"response",
"fields",
"and",
"creates",
"sql",
"query",
".",
"then",
"inserts",
"everything",
"inside",
"the",
"database"
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/db_import.py#L27-L45
|
8,913
|
Yubico/python-pyhsm
|
pyhsm/ksm/import_keys.py
|
import_keys
|
def import_keys(hsm, args):
"""
The main stdin iteration loop.
"""
res = True
# ykksm 1
#123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,
for line in sys.stdin:
if line[0] == '#':
continue
l = line.split(',')
modhex_id = l[1]
uid = l[2].decode('hex')
key = l[3].decode('hex')
if modhex_id and uid and key:
public_id = pyhsm.yubikey.modhex_decode(modhex_id)
padded_id = modhex_id.rjust(args.public_id_chars, 'c')
if int(public_id, 16) == 0:
print "WARNING: Skipping import of key with public ID: %s" % (padded_id)
print "This public ID is unsupported by the YubiHSM.\n"
continue
if args.verbose:
print " %s" % (padded_id)
secret = pyhsm.aead_cmd.YHSM_YubiKeySecret(key, uid)
hsm.load_secret(secret)
for kh in args.key_handles.keys():
if(args.random_nonce):
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
if args.internal_db:
if not store_in_internal_db(
args, hsm, modhex_id, public_id, kh, aead):
res = False
continue
filename = output_filename(
args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
if res:
print "\nDone\n"
else:
print "\nDone (one or more entries rejected)"
return res
|
python
|
def import_keys(hsm, args):
"""
The main stdin iteration loop.
"""
res = True
# ykksm 1
#123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,
for line in sys.stdin:
if line[0] == '#':
continue
l = line.split(',')
modhex_id = l[1]
uid = l[2].decode('hex')
key = l[3].decode('hex')
if modhex_id and uid and key:
public_id = pyhsm.yubikey.modhex_decode(modhex_id)
padded_id = modhex_id.rjust(args.public_id_chars, 'c')
if int(public_id, 16) == 0:
print "WARNING: Skipping import of key with public ID: %s" % (padded_id)
print "This public ID is unsupported by the YubiHSM.\n"
continue
if args.verbose:
print " %s" % (padded_id)
secret = pyhsm.aead_cmd.YHSM_YubiKeySecret(key, uid)
hsm.load_secret(secret)
for kh in args.key_handles.keys():
if(args.random_nonce):
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
if args.internal_db:
if not store_in_internal_db(
args, hsm, modhex_id, public_id, kh, aead):
res = False
continue
filename = output_filename(
args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
if res:
print "\nDone\n"
else:
print "\nDone (one or more entries rejected)"
return res
|
[
"def",
"import_keys",
"(",
"hsm",
",",
"args",
")",
":",
"res",
"=",
"True",
"# ykksm 1",
"#123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,",
"for",
"line",
"in",
"sys",
".",
"stdin",
":",
"if",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"l",
"=",
"line",
".",
"split",
"(",
"','",
")",
"modhex_id",
"=",
"l",
"[",
"1",
"]",
"uid",
"=",
"l",
"[",
"2",
"]",
".",
"decode",
"(",
"'hex'",
")",
"key",
"=",
"l",
"[",
"3",
"]",
".",
"decode",
"(",
"'hex'",
")",
"if",
"modhex_id",
"and",
"uid",
"and",
"key",
":",
"public_id",
"=",
"pyhsm",
".",
"yubikey",
".",
"modhex_decode",
"(",
"modhex_id",
")",
"padded_id",
"=",
"modhex_id",
".",
"rjust",
"(",
"args",
".",
"public_id_chars",
",",
"'c'",
")",
"if",
"int",
"(",
"public_id",
",",
"16",
")",
"==",
"0",
":",
"print",
"\"WARNING: Skipping import of key with public ID: %s\"",
"%",
"(",
"padded_id",
")",
"print",
"\"This public ID is unsupported by the YubiHSM.\\n\"",
"continue",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %s\"",
"%",
"(",
"padded_id",
")",
"secret",
"=",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
"(",
"key",
",",
"uid",
")",
"hsm",
".",
"load_secret",
"(",
"secret",
")",
"for",
"kh",
"in",
"args",
".",
"key_handles",
".",
"keys",
"(",
")",
":",
"if",
"(",
"args",
".",
"random_nonce",
")",
":",
"nonce",
"=",
"\"\"",
"else",
":",
"nonce",
"=",
"public_id",
".",
"decode",
"(",
"'hex'",
")",
"aead",
"=",
"hsm",
".",
"generate_aead",
"(",
"nonce",
",",
"kh",
")",
"if",
"args",
".",
"internal_db",
":",
"if",
"not",
"store_in_internal_db",
"(",
"args",
",",
"hsm",
",",
"modhex_id",
",",
"public_id",
",",
"kh",
",",
"aead",
")",
":",
"res",
"=",
"False",
"continue",
"filename",
"=",
"output_filename",
"(",
"args",
".",
"output_dir",
",",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"padded_id",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %4s, %i bytes (%s) -> %s\"",
"%",
"(",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"len",
"(",
"aead",
".",
"data",
")",
",",
"shorten_aead",
"(",
"aead",
")",
",",
"filename",
")",
"aead",
".",
"save",
"(",
"filename",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\"\"",
"if",
"res",
":",
"print",
"\"\\nDone\\n\"",
"else",
":",
"print",
"\"\\nDone (one or more entries rejected)\"",
"return",
"res"
] |
The main stdin iteration loop.
|
[
"The",
"main",
"stdin",
"iteration",
"loop",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/import_keys.py#L142-L204
|
8,914
|
Yubico/python-pyhsm
|
pyhsm/ksm/import_keys.py
|
shorten_aead
|
def shorten_aead(aead):
""" Produce pretty-printable version of long AEAD. """
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (head, tail)
|
python
|
def shorten_aead(aead):
""" Produce pretty-printable version of long AEAD. """
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (head, tail)
|
[
"def",
"shorten_aead",
"(",
"aead",
")",
":",
"head",
"=",
"aead",
".",
"data",
"[",
":",
"4",
"]",
".",
"encode",
"(",
"'hex'",
")",
"tail",
"=",
"aead",
".",
"data",
"[",
"-",
"4",
":",
"]",
".",
"encode",
"(",
"'hex'",
")",
"return",
"\"%s...%s\"",
"%",
"(",
"head",
",",
"tail",
")"
] |
Produce pretty-printable version of long AEAD.
|
[
"Produce",
"pretty",
"-",
"printable",
"version",
"of",
"long",
"AEAD",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/import_keys.py#L225-L229
|
8,915
|
Yubico/python-pyhsm
|
pyhsm/ksm/import_keys.py
|
output_filename
|
def output_filename(output_dir, key_handle, public_id):
"""
Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage.
"""
parts = [output_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id)
|
python
|
def output_filename(output_dir, key_handle, public_id):
"""
Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage.
"""
parts = [output_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id)
|
[
"def",
"output_filename",
"(",
"output_dir",
",",
"key_handle",
",",
"public_id",
")",
":",
"parts",
"=",
"[",
"output_dir",
",",
"key_handle",
"]",
"+",
"pyhsm",
".",
"util",
".",
"group",
"(",
"public_id",
",",
"2",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"public_id",
")"
] |
Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage.
|
[
"Return",
"an",
"output",
"filename",
"for",
"a",
"generated",
"AEAD",
".",
"Creates",
"a",
"hashed",
"directory",
"structure",
"using",
"the",
"last",
"three",
"bytes",
"of",
"the",
"public",
"id",
"to",
"get",
"equal",
"usage",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/import_keys.py#L232-L243
|
8,916
|
Yubico/python-pyhsm
|
pyhsm/db_cmd.py
|
YHSM_Cmd_DB_YubiKey_Store.parse_result
|
def parse_result(self, data):
""" Return True if the AEAD was stored sucessfully. """
# typedef struct {
# uint8_t publicId[YSM_PUBLIC_ID_SIZE]; // Public id (nonce)
# uint32_t keyHandle; // Key handle
# YSM_STATUS status; // Validation status
# } YSM_DB_YUBIKEY_AEAD_STORE_RESP;
public_id, \
key_handle, \
self.status = struct.unpack("< %is I B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data)
pyhsm.util.validate_cmd_response_str('public_id', public_id, self.public_id)
pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)
if self.status == pyhsm.defines.YSM_STATUS_OK:
return True
else:
raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)
|
python
|
def parse_result(self, data):
""" Return True if the AEAD was stored sucessfully. """
# typedef struct {
# uint8_t publicId[YSM_PUBLIC_ID_SIZE]; // Public id (nonce)
# uint32_t keyHandle; // Key handle
# YSM_STATUS status; // Validation status
# } YSM_DB_YUBIKEY_AEAD_STORE_RESP;
public_id, \
key_handle, \
self.status = struct.unpack("< %is I B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data)
pyhsm.util.validate_cmd_response_str('public_id', public_id, self.public_id)
pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)
if self.status == pyhsm.defines.YSM_STATUS_OK:
return True
else:
raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)
|
[
"def",
"parse_result",
"(",
"self",
",",
"data",
")",
":",
"# typedef struct {",
"# uint8_t publicId[YSM_PUBLIC_ID_SIZE]; // Public id (nonce)",
"# uint32_t keyHandle; // Key handle",
"# YSM_STATUS status; // Validation status",
"# } YSM_DB_YUBIKEY_AEAD_STORE_RESP;",
"public_id",
",",
"key_handle",
",",
"self",
".",
"status",
"=",
"struct",
".",
"unpack",
"(",
"\"< %is I B\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
")",
",",
"data",
")",
"pyhsm",
".",
"util",
".",
"validate_cmd_response_str",
"(",
"'public_id'",
",",
"public_id",
",",
"self",
".",
"public_id",
")",
"pyhsm",
".",
"util",
".",
"validate_cmd_response_hex",
"(",
"'key_handle'",
",",
"key_handle",
",",
"self",
".",
"key_handle",
")",
"if",
"self",
".",
"status",
"==",
"pyhsm",
".",
"defines",
".",
"YSM_STATUS_OK",
":",
"return",
"True",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"self",
".",
"command",
")",
",",
"self",
".",
"status",
")"
] |
Return True if the AEAD was stored sucessfully.
|
[
"Return",
"True",
"if",
"the",
"AEAD",
"was",
"stored",
"sucessfully",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/db_cmd.py#L64-L81
|
8,917
|
Yubico/python-pyhsm
|
pyhsm/tools/generate_keys.py
|
gen_keys
|
def gen_keys(hsm, args):
"""
The main key generating loop.
"""
if args.verbose:
print "Generating %i keys :\n" % (args.count)
else:
print "Generating %i keys" % (args.count)
for int_id in range(args.start_id, args.start_id + args.count):
public_id = ("%x" % int_id).rjust(args.public_id_chars, '0')
padded_id = pyhsm.yubikey.modhex_encode(public_id)
if args.verbose:
print " %s" % (padded_id)
num_bytes = len(pyhsm.aead_cmd.YHSM_YubiKeySecret('a' * 16, 'b' * 6).pack())
hsm.load_random(num_bytes)
for kh in args.key_handles.keys():
if args.random_nonce:
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
filename = output_filename(args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
print "\nDone\n"
|
python
|
def gen_keys(hsm, args):
"""
The main key generating loop.
"""
if args.verbose:
print "Generating %i keys :\n" % (args.count)
else:
print "Generating %i keys" % (args.count)
for int_id in range(args.start_id, args.start_id + args.count):
public_id = ("%x" % int_id).rjust(args.public_id_chars, '0')
padded_id = pyhsm.yubikey.modhex_encode(public_id)
if args.verbose:
print " %s" % (padded_id)
num_bytes = len(pyhsm.aead_cmd.YHSM_YubiKeySecret('a' * 16, 'b' * 6).pack())
hsm.load_random(num_bytes)
for kh in args.key_handles.keys():
if args.random_nonce:
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
filename = output_filename(args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
print "\nDone\n"
|
[
"def",
"gen_keys",
"(",
"hsm",
",",
"args",
")",
":",
"if",
"args",
".",
"verbose",
":",
"print",
"\"Generating %i keys :\\n\"",
"%",
"(",
"args",
".",
"count",
")",
"else",
":",
"print",
"\"Generating %i keys\"",
"%",
"(",
"args",
".",
"count",
")",
"for",
"int_id",
"in",
"range",
"(",
"args",
".",
"start_id",
",",
"args",
".",
"start_id",
"+",
"args",
".",
"count",
")",
":",
"public_id",
"=",
"(",
"\"%x\"",
"%",
"int_id",
")",
".",
"rjust",
"(",
"args",
".",
"public_id_chars",
",",
"'0'",
")",
"padded_id",
"=",
"pyhsm",
".",
"yubikey",
".",
"modhex_encode",
"(",
"public_id",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %s\"",
"%",
"(",
"padded_id",
")",
"num_bytes",
"=",
"len",
"(",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
"(",
"'a'",
"*",
"16",
",",
"'b'",
"*",
"6",
")",
".",
"pack",
"(",
")",
")",
"hsm",
".",
"load_random",
"(",
"num_bytes",
")",
"for",
"kh",
"in",
"args",
".",
"key_handles",
".",
"keys",
"(",
")",
":",
"if",
"args",
".",
"random_nonce",
":",
"nonce",
"=",
"\"\"",
"else",
":",
"nonce",
"=",
"public_id",
".",
"decode",
"(",
"'hex'",
")",
"aead",
"=",
"hsm",
".",
"generate_aead",
"(",
"nonce",
",",
"kh",
")",
"filename",
"=",
"output_filename",
"(",
"args",
".",
"output_dir",
",",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"padded_id",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %4s, %i bytes (%s) -> %s\"",
"%",
"(",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"len",
"(",
"aead",
".",
"data",
")",
",",
"shorten_aead",
"(",
"aead",
")",
",",
"filename",
")",
"aead",
".",
"save",
"(",
"filename",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\"\"",
"print",
"\"\\nDone\\n\""
] |
The main key generating loop.
|
[
"The",
"main",
"key",
"generating",
"loop",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/generate_keys.py#L135-L171
|
8,918
|
Yubico/python-pyhsm
|
pyhsm/cmd.py
|
reset
|
def reset(stick):
"""
Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer.
"""
nulls = (pyhsm.defines.YSM_MAX_PKT_SIZE - 1) * '\x00'
res = YHSM_Cmd(stick, pyhsm.defines.YSM_NULL, payload = nulls).execute(read_response = False)
unlock = stick.acquire()
try:
stick.drain()
stick.flush()
finally:
unlock()
return res == 0
|
python
|
def reset(stick):
"""
Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer.
"""
nulls = (pyhsm.defines.YSM_MAX_PKT_SIZE - 1) * '\x00'
res = YHSM_Cmd(stick, pyhsm.defines.YSM_NULL, payload = nulls).execute(read_response = False)
unlock = stick.acquire()
try:
stick.drain()
stick.flush()
finally:
unlock()
return res == 0
|
[
"def",
"reset",
"(",
"stick",
")",
":",
"nulls",
"=",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_MAX_PKT_SIZE",
"-",
"1",
")",
"*",
"'\\x00'",
"res",
"=",
"YHSM_Cmd",
"(",
"stick",
",",
"pyhsm",
".",
"defines",
".",
"YSM_NULL",
",",
"payload",
"=",
"nulls",
")",
".",
"execute",
"(",
"read_response",
"=",
"False",
")",
"unlock",
"=",
"stick",
".",
"acquire",
"(",
")",
"try",
":",
"stick",
".",
"drain",
"(",
")",
"stick",
".",
"flush",
"(",
")",
"finally",
":",
"unlock",
"(",
")",
"return",
"res",
"==",
"0"
] |
Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer.
|
[
"Send",
"a",
"bunch",
"of",
"zero",
"-",
"bytes",
"to",
"the",
"YubiHSM",
"and",
"flush",
"the",
"input",
"buffer",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/cmd.py#L149-L161
|
8,919
|
Yubico/python-pyhsm
|
pyhsm/cmd.py
|
YHSM_Cmd.execute
|
def execute(self, read_response=True):
"""
Write command to HSM and read response.
@param read_response: Whether to expect a response or not.
@type read_response: bool
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
if self.command != pyhsm.defines.YSM_NULL:
# YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt
cmd_buf = struct.pack('BB', len(self.payload) + 1, self.command)
else:
cmd_buf = chr(self.command)
cmd_buf += self.payload
debug_info = None
unlock = self.stick.acquire()
try:
if self.stick.debug:
debug_info = "%s (payload %i/0x%x)" % (pyhsm.defines.cmd2str(self.command), \
len(self.payload), len(self.payload))
self.stick.write(cmd_buf, debug_info)
if not read_response:
return None
return self._read_response()
finally:
unlock()
|
python
|
def execute(self, read_response=True):
"""
Write command to HSM and read response.
@param read_response: Whether to expect a response or not.
@type read_response: bool
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
if self.command != pyhsm.defines.YSM_NULL:
# YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt
cmd_buf = struct.pack('BB', len(self.payload) + 1, self.command)
else:
cmd_buf = chr(self.command)
cmd_buf += self.payload
debug_info = None
unlock = self.stick.acquire()
try:
if self.stick.debug:
debug_info = "%s (payload %i/0x%x)" % (pyhsm.defines.cmd2str(self.command), \
len(self.payload), len(self.payload))
self.stick.write(cmd_buf, debug_info)
if not read_response:
return None
return self._read_response()
finally:
unlock()
|
[
"def",
"execute",
"(",
"self",
",",
"read_response",
"=",
"True",
")",
":",
"# // Up- and downlink packet",
"# typedef struct {",
"# uint8_t bcnt; // Number of bytes (cmd + payload)",
"# uint8_t cmd; // YSM_xxx command",
"# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload",
"# } YSM_PKT;",
"if",
"self",
".",
"command",
"!=",
"pyhsm",
".",
"defines",
".",
"YSM_NULL",
":",
"# YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt",
"cmd_buf",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"len",
"(",
"self",
".",
"payload",
")",
"+",
"1",
",",
"self",
".",
"command",
")",
"else",
":",
"cmd_buf",
"=",
"chr",
"(",
"self",
".",
"command",
")",
"cmd_buf",
"+=",
"self",
".",
"payload",
"debug_info",
"=",
"None",
"unlock",
"=",
"self",
".",
"stick",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"stick",
".",
"debug",
":",
"debug_info",
"=",
"\"%s (payload %i/0x%x)\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"self",
".",
"command",
")",
",",
"len",
"(",
"self",
".",
"payload",
")",
",",
"len",
"(",
"self",
".",
"payload",
")",
")",
"self",
".",
"stick",
".",
"write",
"(",
"cmd_buf",
",",
"debug_info",
")",
"if",
"not",
"read_response",
":",
"return",
"None",
"return",
"self",
".",
"_read_response",
"(",
")",
"finally",
":",
"unlock",
"(",
")"
] |
Write command to HSM and read response.
@param read_response: Whether to expect a response or not.
@type read_response: bool
|
[
"Write",
"command",
"to",
"HSM",
"and",
"read",
"response",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/cmd.py#L47-L77
|
8,920
|
Yubico/python-pyhsm
|
pyhsm/cmd.py
|
YHSM_Cmd._read_response
|
def _read_response(self):
"""
After writing a command, read response.
@returns: Result of parse_data()
@raises pyhsm.exception.YHSM_Error: On failure to read a response to the
command we sent in a timely fashion.
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
# read YSM_PKT.bcnt and YSM_PKT.cmd
res = self.stick.read(2, 'response length + response status')
if len(res) != 2:
self._handle_invalid_read_response(res, 2)
response_len, response_status = struct.unpack('BB', res)
response_len -= 1 # the status byte has been read already
debug_info = None
if response_status & pyhsm.defines.YSM_RESPONSE:
debug_info = "%s response (%i/0x%x bytes)" \
% (pyhsm.defines.cmd2str(response_status - pyhsm.defines.YSM_RESPONSE), \
response_len, response_len)
# read YSM_PKT.payload
res = self.stick.read(response_len, debug_info)
if res:
if response_status == self.command | pyhsm.defines.YSM_RESPONSE:
self.executed = True
self.response_status = response_status
return self.parse_result(res)
else:
reset(self.stick)
raise pyhsm.exception.YHSM_Error('YubiHSM responded to wrong command')
else:
raise pyhsm.exception.YHSM_Error('YubiHSM did not respond')
|
python
|
def _read_response(self):
"""
After writing a command, read response.
@returns: Result of parse_data()
@raises pyhsm.exception.YHSM_Error: On failure to read a response to the
command we sent in a timely fashion.
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
# read YSM_PKT.bcnt and YSM_PKT.cmd
res = self.stick.read(2, 'response length + response status')
if len(res) != 2:
self._handle_invalid_read_response(res, 2)
response_len, response_status = struct.unpack('BB', res)
response_len -= 1 # the status byte has been read already
debug_info = None
if response_status & pyhsm.defines.YSM_RESPONSE:
debug_info = "%s response (%i/0x%x bytes)" \
% (pyhsm.defines.cmd2str(response_status - pyhsm.defines.YSM_RESPONSE), \
response_len, response_len)
# read YSM_PKT.payload
res = self.stick.read(response_len, debug_info)
if res:
if response_status == self.command | pyhsm.defines.YSM_RESPONSE:
self.executed = True
self.response_status = response_status
return self.parse_result(res)
else:
reset(self.stick)
raise pyhsm.exception.YHSM_Error('YubiHSM responded to wrong command')
else:
raise pyhsm.exception.YHSM_Error('YubiHSM did not respond')
|
[
"def",
"_read_response",
"(",
"self",
")",
":",
"# // Up- and downlink packet",
"# typedef struct {",
"# uint8_t bcnt; // Number of bytes (cmd + payload)",
"# uint8_t cmd; // YSM_xxx command",
"# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload",
"# } YSM_PKT;",
"# read YSM_PKT.bcnt and YSM_PKT.cmd",
"res",
"=",
"self",
".",
"stick",
".",
"read",
"(",
"2",
",",
"'response length + response status'",
")",
"if",
"len",
"(",
"res",
")",
"!=",
"2",
":",
"self",
".",
"_handle_invalid_read_response",
"(",
"res",
",",
"2",
")",
"response_len",
",",
"response_status",
"=",
"struct",
".",
"unpack",
"(",
"'BB'",
",",
"res",
")",
"response_len",
"-=",
"1",
"# the status byte has been read already",
"debug_info",
"=",
"None",
"if",
"response_status",
"&",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
":",
"debug_info",
"=",
"\"%s response (%i/0x%x bytes)\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"response_status",
"-",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
")",
",",
"response_len",
",",
"response_len",
")",
"# read YSM_PKT.payload",
"res",
"=",
"self",
".",
"stick",
".",
"read",
"(",
"response_len",
",",
"debug_info",
")",
"if",
"res",
":",
"if",
"response_status",
"==",
"self",
".",
"command",
"|",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
":",
"self",
".",
"executed",
"=",
"True",
"self",
".",
"response_status",
"=",
"response_status",
"return",
"self",
".",
"parse_result",
"(",
"res",
")",
"else",
":",
"reset",
"(",
"self",
".",
"stick",
")",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"'YubiHSM responded to wrong command'",
")",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"'YubiHSM did not respond'",
")"
] |
After writing a command, read response.
@returns: Result of parse_data()
@raises pyhsm.exception.YHSM_Error: On failure to read a response to the
command we sent in a timely fashion.
|
[
"After",
"writing",
"a",
"command",
"read",
"response",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/cmd.py#L79-L117
|
8,921
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.reset
|
def reset(self, test_sync = True):
"""
Perform stream resynchronization.
@param test_sync: Verify sync with YubiHSM after reset
@type test_sync: bool
@return: True if successful
@rtype: bool
"""
pyhsm.cmd.reset(self.stick)
if test_sync:
# Now verify we are in sync
data = 'ekoeko'
echo = self.echo(data)
# XXX analyze 'echo' to see if we are in config mode, and produce a
# nice exception if we are.
return data == echo
else:
return True
|
python
|
def reset(self, test_sync = True):
"""
Perform stream resynchronization.
@param test_sync: Verify sync with YubiHSM after reset
@type test_sync: bool
@return: True if successful
@rtype: bool
"""
pyhsm.cmd.reset(self.stick)
if test_sync:
# Now verify we are in sync
data = 'ekoeko'
echo = self.echo(data)
# XXX analyze 'echo' to see if we are in config mode, and produce a
# nice exception if we are.
return data == echo
else:
return True
|
[
"def",
"reset",
"(",
"self",
",",
"test_sync",
"=",
"True",
")",
":",
"pyhsm",
".",
"cmd",
".",
"reset",
"(",
"self",
".",
"stick",
")",
"if",
"test_sync",
":",
"# Now verify we are in sync",
"data",
"=",
"'ekoeko'",
"echo",
"=",
"self",
".",
"echo",
"(",
"data",
")",
"# XXX analyze 'echo' to see if we are in config mode, and produce a",
"# nice exception if we are.",
"return",
"data",
"==",
"echo",
"else",
":",
"return",
"True"
] |
Perform stream resynchronization.
@param test_sync: Verify sync with YubiHSM after reset
@type test_sync: bool
@return: True if successful
@rtype: bool
|
[
"Perform",
"stream",
"resynchronization",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L91-L110
|
8,922
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.set_debug
|
def set_debug(self, new):
"""
Set debug mode.
@param new: new value
@type new: bool
@return: old value
@rtype: bool
"""
if type(new) is not bool:
raise pyhsm.exception.YHSM_WrongInputType(
'new', bool, type(new))
old = self.debug
self.debug = new
self.stick.set_debug(new)
return old
|
python
|
def set_debug(self, new):
"""
Set debug mode.
@param new: new value
@type new: bool
@return: old value
@rtype: bool
"""
if type(new) is not bool:
raise pyhsm.exception.YHSM_WrongInputType(
'new', bool, type(new))
old = self.debug
self.debug = new
self.stick.set_debug(new)
return old
|
[
"def",
"set_debug",
"(",
"self",
",",
"new",
")",
":",
"if",
"type",
"(",
"new",
")",
"is",
"not",
"bool",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputType",
"(",
"'new'",
",",
"bool",
",",
"type",
"(",
"new",
")",
")",
"old",
"=",
"self",
".",
"debug",
"self",
".",
"debug",
"=",
"new",
"self",
".",
"stick",
".",
"set_debug",
"(",
"new",
")",
"return",
"old"
] |
Set debug mode.
@param new: new value
@type new: bool
@return: old value
@rtype: bool
|
[
"Set",
"debug",
"mode",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L112-L128
|
8,923
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.echo
|
def echo(self, data):
"""
Echo test.
@type data: string
@return: data read from YubiHSM -- should equal `data'
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Echo}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Echo(self.stick, data).execute()
|
python
|
def echo(self, data):
"""
Echo test.
@type data: string
@return: data read from YubiHSM -- should equal `data'
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Echo}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Echo(self.stick, data).execute()
|
[
"def",
"echo",
"(",
"self",
",",
"data",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Echo",
"(",
"self",
".",
"stick",
",",
"data",
")",
".",
"execute",
"(",
")"
] |
Echo test.
@type data: string
@return: data read from YubiHSM -- should equal `data'
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Echo}
|
[
"Echo",
"test",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L155-L165
|
8,924
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.random
|
def random(self, num_bytes):
"""
Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random(self.stick, num_bytes).execute()
|
python
|
def random(self, num_bytes):
"""
Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random(self.stick, num_bytes).execute()
|
[
"def",
"random",
"(",
"self",
",",
"num_bytes",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Random",
"(",
"self",
".",
"stick",
",",
"num_bytes",
")",
".",
"execute",
"(",
")"
] |
Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random}
|
[
"Get",
"random",
"bytes",
"from",
"YubiHSM",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L177-L191
|
8,925
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.random_reseed
|
def random_reseed(self, seed):
"""
Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed(self.stick, seed).execute()
|
python
|
def random_reseed(self, seed):
"""
Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed(self.stick, seed).execute()
|
[
"def",
"random_reseed",
"(",
"self",
",",
"seed",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Random_Reseed",
"(",
"self",
".",
"stick",
",",
"seed",
")",
".",
"execute",
"(",
")"
] |
Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed}
|
[
"Provide",
"YubiHSM",
"DRBG_CTR",
"with",
"a",
"new",
"seed",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L193-L205
|
8,926
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.get_nonce
|
def get_nonce(self, increment=1):
"""
Get current nonce from YubiHSM.
Use increment 0 to just fetch the value without incrementing it.
@keyword increment: requested increment (optional)
@return: nonce value _before_ increment
@rtype: L{YHSM_NonceResponse}
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get(self.stick, increment).execute()
|
python
|
def get_nonce(self, increment=1):
"""
Get current nonce from YubiHSM.
Use increment 0 to just fetch the value without incrementing it.
@keyword increment: requested increment (optional)
@return: nonce value _before_ increment
@rtype: L{YHSM_NonceResponse}
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get(self.stick, increment).execute()
|
[
"def",
"get_nonce",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Nonce_Get",
"(",
"self",
".",
"stick",
",",
"increment",
")",
".",
"execute",
"(",
")"
] |
Get current nonce from YubiHSM.
Use increment 0 to just fetch the value without incrementing it.
@keyword increment: requested increment (optional)
@return: nonce value _before_ increment
@rtype: L{YHSM_NonceResponse}
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get}
|
[
"Get",
"current",
"nonce",
"from",
"YubiHSM",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L207-L220
|
8,927
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.load_temp_key
|
def load_temp_key(self, nonce, key_handle, aead):
"""
Load the contents of an AEAD into the phantom key handle 0xffffffff.
@param nonce: The nonce used when creating the AEAD
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type nonce: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load(self.stick, nonce, key_handle, aead).execute()
|
python
|
def load_temp_key(self, nonce, key_handle, aead):
"""
Load the contents of an AEAD into the phantom key handle 0xffffffff.
@param nonce: The nonce used when creating the AEAD
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type nonce: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load(self.stick, nonce, key_handle, aead).execute()
|
[
"def",
"load_temp_key",
"(",
"self",
",",
"nonce",
",",
"key_handle",
",",
"aead",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Temp_Key_Load",
"(",
"self",
".",
"stick",
",",
"nonce",
",",
"key_handle",
",",
"aead",
")",
".",
"execute",
"(",
")"
] |
Load the contents of an AEAD into the phantom key handle 0xffffffff.
@param nonce: The nonce used when creating the AEAD
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type nonce: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load}
|
[
"Load",
"the",
"contents",
"of",
"an",
"AEAD",
"into",
"the",
"phantom",
"key",
"handle",
"0xffffffff",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L222-L238
|
8,928
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.load_secret
|
def load_secret(self, secret):
"""
Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKey secret to load
@type secret: L{pyhsm.aead_cmd.YHSM_YubiKeySecret} or string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
if isinstance(secret, pyhsm.aead_cmd.YHSM_YubiKeySecret):
secret = secret.pack()
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, secret).execute()
|
python
|
def load_secret(self, secret):
"""
Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKey secret to load
@type secret: L{pyhsm.aead_cmd.YHSM_YubiKeySecret} or string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
if isinstance(secret, pyhsm.aead_cmd.YHSM_YubiKeySecret):
secret = secret.pack()
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, secret).execute()
|
[
"def",
"load_secret",
"(",
"self",
",",
"secret",
")",
":",
"if",
"isinstance",
"(",
"secret",
",",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
")",
":",
"secret",
"=",
"secret",
".",
"pack",
"(",
")",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
"YHSM_Cmd_Buffer_Load",
"(",
"self",
".",
"stick",
",",
"secret",
")",
".",
"execute",
"(",
")"
] |
Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKey secret to load
@type secret: L{pyhsm.aead_cmd.YHSM_YubiKeySecret} or string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
|
[
"Ask",
"YubiHSM",
"to",
"load",
"a",
"pre",
"-",
"existing",
"YubiKey",
"secret",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L294-L312
|
8,929
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.load_data
|
def load_data(self, data, offset):
"""
Ask YubiHSM to load arbitrary data into it's internal buffer, at any offset.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
Load data to offset 0 to reset the buffer.
@param data: arbitrary data to load
@type data: string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, data, offset).execute()
|
python
|
def load_data(self, data, offset):
"""
Ask YubiHSM to load arbitrary data into it's internal buffer, at any offset.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
Load data to offset 0 to reset the buffer.
@param data: arbitrary data to load
@type data: string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, data, offset).execute()
|
[
"def",
"load_data",
"(",
"self",
",",
"data",
",",
"offset",
")",
":",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
"YHSM_Cmd_Buffer_Load",
"(",
"self",
".",
"stick",
",",
"data",
",",
"offset",
")",
".",
"execute",
"(",
")"
] |
Ask YubiHSM to load arbitrary data into it's internal buffer, at any offset.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
Load data to offset 0 to reset the buffer.
@param data: arbitrary data to load
@type data: string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
|
[
"Ask",
"YubiHSM",
"to",
"load",
"arbitrary",
"data",
"into",
"it",
"s",
"internal",
"buffer",
"at",
"any",
"offset",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L314-L332
|
8,930
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.load_random
|
def load_random(self, num_bytes, offset = 0):
"""
Ask YubiHSM to generate a number of random bytes to any offset of it's internal
buffer.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param num_bytes: Number of bytes to generate
@type num_bytes: integer
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load(self.stick, num_bytes, offset).execute()
|
python
|
def load_random(self, num_bytes, offset = 0):
"""
Ask YubiHSM to generate a number of random bytes to any offset of it's internal
buffer.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param num_bytes: Number of bytes to generate
@type num_bytes: integer
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load(self.stick, num_bytes, offset).execute()
|
[
"def",
"load_random",
"(",
"self",
",",
"num_bytes",
",",
"offset",
"=",
"0",
")",
":",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
"YHSM_Cmd_Buffer_Random_Load",
"(",
"self",
".",
"stick",
",",
"num_bytes",
",",
"offset",
")",
".",
"execute",
"(",
")"
] |
Ask YubiHSM to generate a number of random bytes to any offset of it's internal
buffer.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param num_bytes: Number of bytes to generate
@type num_bytes: integer
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load}
|
[
"Ask",
"YubiHSM",
"to",
"generate",
"a",
"number",
"of",
"random",
"bytes",
"to",
"any",
"offset",
"of",
"it",
"s",
"internal",
"buffer",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L334-L351
|
8,931
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.generate_aead_random
|
def generate_aead_random(self, nonce, key_handle, num_bytes):
"""
Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator.
To generate a secret for a YubiKey, use public_id as nonce.
@param nonce: The nonce to use when creating the AEAD
@param key_handle: The key handle that can encrypt the random data into an AEAD
@param num_bytes: Number of random data bytes to put inside the AEAD
@type nonce: string
@type key_handle: integer or string
@type num_bytes: integer
@returns: The generated AEAD on success.
@rtype: L{YHSM_GeneratedAEAD}
@see: L{pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate}
"""
return pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate(self.stick, nonce, key_handle, num_bytes).execute()
|
python
|
def generate_aead_random(self, nonce, key_handle, num_bytes):
"""
Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator.
To generate a secret for a YubiKey, use public_id as nonce.
@param nonce: The nonce to use when creating the AEAD
@param key_handle: The key handle that can encrypt the random data into an AEAD
@param num_bytes: Number of random data bytes to put inside the AEAD
@type nonce: string
@type key_handle: integer or string
@type num_bytes: integer
@returns: The generated AEAD on success.
@rtype: L{YHSM_GeneratedAEAD}
@see: L{pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate}
"""
return pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate(self.stick, nonce, key_handle, num_bytes).execute()
|
[
"def",
"generate_aead_random",
"(",
"self",
",",
"nonce",
",",
"key_handle",
",",
"num_bytes",
")",
":",
"return",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_Cmd_AEAD_Random_Generate",
"(",
"self",
".",
"stick",
",",
"nonce",
",",
"key_handle",
",",
"num_bytes",
")",
".",
"execute",
"(",
")"
] |
Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator.
To generate a secret for a YubiKey, use public_id as nonce.
@param nonce: The nonce to use when creating the AEAD
@param key_handle: The key handle that can encrypt the random data into an AEAD
@param num_bytes: Number of random data bytes to put inside the AEAD
@type nonce: string
@type key_handle: integer or string
@type num_bytes: integer
@returns: The generated AEAD on success.
@rtype: L{YHSM_GeneratedAEAD}
@see: L{pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate}
|
[
"Generate",
"a",
"random",
"AEAD",
"block",
"using",
"the",
"YubiHSM",
"internal",
"DRBG_CTR",
"random",
"generator",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L372-L390
|
8,932
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.validate_aead_otp
|
def validate_aead_otp(self, public_id, otp, key_handle, aead):
"""
Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type public_id: string
@type otp: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP}
"""
if type(public_id) is not str:
assert()
if type(otp) is not str:
assert()
if type(key_handle) is not int:
assert()
if type(aead) is not str:
assert()
return pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP( \
self.stick, public_id, otp, key_handle, aead).execute()
|
python
|
def validate_aead_otp(self, public_id, otp, key_handle, aead):
"""
Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type public_id: string
@type otp: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP}
"""
if type(public_id) is not str:
assert()
if type(otp) is not str:
assert()
if type(key_handle) is not int:
assert()
if type(aead) is not str:
assert()
return pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP( \
self.stick, public_id, otp, key_handle, aead).execute()
|
[
"def",
"validate_aead_otp",
"(",
"self",
",",
"public_id",
",",
"otp",
",",
"key_handle",
",",
"aead",
")",
":",
"if",
"type",
"(",
"public_id",
")",
"is",
"not",
"str",
":",
"assert",
"(",
")",
"if",
"type",
"(",
"otp",
")",
"is",
"not",
"str",
":",
"assert",
"(",
")",
"if",
"type",
"(",
"key_handle",
")",
"is",
"not",
"int",
":",
"assert",
"(",
")",
"if",
"type",
"(",
"aead",
")",
"is",
"not",
"str",
":",
"assert",
"(",
")",
"return",
"pyhsm",
".",
"validate_cmd",
".",
"YHSM_Cmd_AEAD_Validate_OTP",
"(",
"self",
".",
"stick",
",",
"public_id",
",",
"otp",
",",
"key_handle",
",",
"aead",
")",
".",
"execute",
"(",
")"
] |
Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type public_id: string
@type otp: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP}
|
[
"Ask",
"YubiHSM",
"to",
"validate",
"a",
"YubiKey",
"OTP",
"using",
"an",
"AEAD",
"and",
"a",
"key_handle",
"to",
"decrypt",
"the",
"AEAD",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L436-L464
|
8,933
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.aes_ecb_encrypt
|
def aes_ecb_encrypt(self, key_handle, plaintext):
"""
AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Ciphertext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt( \
self.stick, key_handle, plaintext).execute()
|
python
|
def aes_ecb_encrypt(self, key_handle, plaintext):
"""
AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Ciphertext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt( \
self.stick, key_handle, plaintext).execute()
|
[
"def",
"aes_ecb_encrypt",
"(",
"self",
",",
"key_handle",
",",
"plaintext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Encrypt",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"plaintext",
")",
".",
"execute",
"(",
")"
] |
AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Ciphertext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt}
|
[
"AES",
"ECB",
"encrypt",
"using",
"a",
"key",
"handle",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L505-L522
|
8,934
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.aes_ecb_decrypt
|
def aes_ecb_decrypt(self, key_handle, ciphertext):
"""
AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
@returns: Plaintext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt( \
self.stick, key_handle, ciphertext).execute()
|
python
|
def aes_ecb_decrypt(self, key_handle, ciphertext):
"""
AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
@returns: Plaintext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt( \
self.stick, key_handle, ciphertext).execute()
|
[
"def",
"aes_ecb_decrypt",
"(",
"self",
",",
"key_handle",
",",
"ciphertext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Decrypt",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"ciphertext",
")",
".",
"execute",
"(",
")"
] |
AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
@returns: Plaintext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt}
|
[
"AES",
"ECB",
"decrypt",
"using",
"a",
"key",
"handle",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L524-L541
|
8,935
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.aes_ecb_compare
|
def aes_ecb_compare(self, key_handle, ciphertext, plaintext):
"""
AES ECB decrypt and then compare using a key handle.
The comparison is done inside the YubiHSM so the plaintext is never exposed (well,
except indirectionally when the provided plaintext does match).
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param plaintext: Data to decrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Match result
@rtype: bool
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare( \
self.stick, key_handle, ciphertext, plaintext).execute()
|
python
|
def aes_ecb_compare(self, key_handle, ciphertext, plaintext):
"""
AES ECB decrypt and then compare using a key handle.
The comparison is done inside the YubiHSM so the plaintext is never exposed (well,
except indirectionally when the provided plaintext does match).
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param plaintext: Data to decrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Match result
@rtype: bool
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare( \
self.stick, key_handle, ciphertext, plaintext).execute()
|
[
"def",
"aes_ecb_compare",
"(",
"self",
",",
"key_handle",
",",
"ciphertext",
",",
"plaintext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Compare",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"ciphertext",
",",
"plaintext",
")",
".",
"execute",
"(",
")"
] |
AES ECB decrypt and then compare using a key handle.
The comparison is done inside the YubiHSM so the plaintext is never exposed (well,
except indirectionally when the provided plaintext does match).
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param plaintext: Data to decrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Match result
@rtype: bool
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare}
|
[
"AES",
"ECB",
"decrypt",
"and",
"then",
"compare",
"using",
"a",
"key",
"handle",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L543-L563
|
8,936
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.hmac_sha1
|
def hmac_sha1(self, key_handle, data, flags = None, final = True, to_buffer = False):
"""
Have the YubiHSM generate a HMAC SHA1 of 'data' using a key handle.
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.next} to add more input (until
'final' has been set to True).
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.get_hash} to get the hash result
this far.
@param key_handle: Key handle to use when generating HMAC SHA1
@param data: what to calculate the HMAC SHA1 checksum of
@keyword flags: bit-flags, overrides 'final' and 'to_buffer'
@keyword final: True when there is no more data, False if there is more
@keyword to_buffer: Should the final result be stored in the YubiHSM internal buffer or not
@type key_handle: integer or string
@type data: string
@type flags: None or integer
@returns: HMAC-SHA1 instance
@rtype: L{YHSM_Cmd_HMAC_SHA1_Write}
@see: L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write}
"""
return pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write( \
self.stick, key_handle, data, flags = flags, final = final, to_buffer = to_buffer).execute()
|
python
|
def hmac_sha1(self, key_handle, data, flags = None, final = True, to_buffer = False):
"""
Have the YubiHSM generate a HMAC SHA1 of 'data' using a key handle.
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.next} to add more input (until
'final' has been set to True).
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.get_hash} to get the hash result
this far.
@param key_handle: Key handle to use when generating HMAC SHA1
@param data: what to calculate the HMAC SHA1 checksum of
@keyword flags: bit-flags, overrides 'final' and 'to_buffer'
@keyword final: True when there is no more data, False if there is more
@keyword to_buffer: Should the final result be stored in the YubiHSM internal buffer or not
@type key_handle: integer or string
@type data: string
@type flags: None or integer
@returns: HMAC-SHA1 instance
@rtype: L{YHSM_Cmd_HMAC_SHA1_Write}
@see: L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write}
"""
return pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write( \
self.stick, key_handle, data, flags = flags, final = final, to_buffer = to_buffer).execute()
|
[
"def",
"hmac_sha1",
"(",
"self",
",",
"key_handle",
",",
"data",
",",
"flags",
"=",
"None",
",",
"final",
"=",
"True",
",",
"to_buffer",
"=",
"False",
")",
":",
"return",
"pyhsm",
".",
"hmac_cmd",
".",
"YHSM_Cmd_HMAC_SHA1_Write",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"data",
",",
"flags",
"=",
"flags",
",",
"final",
"=",
"final",
",",
"to_buffer",
"=",
"to_buffer",
")",
".",
"execute",
"(",
")"
] |
Have the YubiHSM generate a HMAC SHA1 of 'data' using a key handle.
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.next} to add more input (until
'final' has been set to True).
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.get_hash} to get the hash result
this far.
@param key_handle: Key handle to use when generating HMAC SHA1
@param data: what to calculate the HMAC SHA1 checksum of
@keyword flags: bit-flags, overrides 'final' and 'to_buffer'
@keyword final: True when there is no more data, False if there is more
@keyword to_buffer: Should the final result be stored in the YubiHSM internal buffer or not
@type key_handle: integer or string
@type data: string
@type flags: None or integer
@returns: HMAC-SHA1 instance
@rtype: L{YHSM_Cmd_HMAC_SHA1_Write}
@see: L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write}
|
[
"Have",
"the",
"YubiHSM",
"generate",
"a",
"HMAC",
"SHA1",
"of",
"data",
"using",
"a",
"key",
"handle",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L568-L593
|
8,937
|
Yubico/python-pyhsm
|
pyhsm/base.py
|
YHSM.db_validate_yubikey_otp
|
def db_validate_yubikey_otp(self, public_id, otp):
"""
Request the YubiHSM to validate an OTP for a YubiKey stored
in the internal database.
@param public_id: The six bytes public id of the YubiKey
@param otp: The OTP from a YubiKey in binary form (16 bytes)
@type public_id: string
@type otp: string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP}
"""
return pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP( \
self.stick, public_id, otp).execute()
|
python
|
def db_validate_yubikey_otp(self, public_id, otp):
"""
Request the YubiHSM to validate an OTP for a YubiKey stored
in the internal database.
@param public_id: The six bytes public id of the YubiKey
@param otp: The OTP from a YubiKey in binary form (16 bytes)
@type public_id: string
@type otp: string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP}
"""
return pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP( \
self.stick, public_id, otp).execute()
|
[
"def",
"db_validate_yubikey_otp",
"(",
"self",
",",
"public_id",
",",
"otp",
")",
":",
"return",
"pyhsm",
".",
"db_cmd",
".",
"YHSM_Cmd_DB_Validate_OTP",
"(",
"self",
".",
"stick",
",",
"public_id",
",",
"otp",
")",
".",
"execute",
"(",
")"
] |
Request the YubiHSM to validate an OTP for a YubiKey stored
in the internal database.
@param public_id: The six bytes public id of the YubiKey
@param otp: The OTP from a YubiKey in binary form (16 bytes)
@type public_id: string
@type otp: string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP}
|
[
"Request",
"the",
"YubiHSM",
"to",
"validate",
"an",
"OTP",
"for",
"a",
"YubiKey",
"stored",
"in",
"the",
"internal",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L626-L642
|
8,938
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
aead_filename
|
def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2) + [public_id]
return os.path.join(*parts)
|
python
|
def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2) + [public_id]
return os.path.join(*parts)
|
[
"def",
"aead_filename",
"(",
"aead_dir",
",",
"key_handle",
",",
"public_id",
")",
":",
"parts",
"=",
"[",
"aead_dir",
",",
"key_handle",
"]",
"+",
"pyhsm",
".",
"util",
".",
"group",
"(",
"public_id",
",",
"2",
")",
"+",
"[",
"public_id",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")"
] |
Return the filename of the AEAD for this public_id.
|
[
"Return",
"the",
"filename",
"of",
"the",
"AEAD",
"for",
"this",
"public_id",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L249-L254
|
8,939
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
run
|
def run(hsm, aead_backend, args):
"""
Start a BaseHTTPServer.HTTPServer and serve requests forever.
"""
write_pid_file(args.pid_file)
server_address = (args.listen_addr, args.listen_port)
httpd = YHSM_KSMServer(server_address,
partial(YHSM_KSMRequestHandler, hsm, aead_backend, args))
my_log_message(args.debug or args.verbose, syslog.LOG_INFO,
"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')"
% (args.listen_addr, args.listen_port, args.serve_url, args.key_handles, args.device, args.aead_dir, args.db_url))
httpd.serve_forever()
|
python
|
def run(hsm, aead_backend, args):
"""
Start a BaseHTTPServer.HTTPServer and serve requests forever.
"""
write_pid_file(args.pid_file)
server_address = (args.listen_addr, args.listen_port)
httpd = YHSM_KSMServer(server_address,
partial(YHSM_KSMRequestHandler, hsm, aead_backend, args))
my_log_message(args.debug or args.verbose, syslog.LOG_INFO,
"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')"
% (args.listen_addr, args.listen_port, args.serve_url, args.key_handles, args.device, args.aead_dir, args.db_url))
httpd.serve_forever()
|
[
"def",
"run",
"(",
"hsm",
",",
"aead_backend",
",",
"args",
")",
":",
"write_pid_file",
"(",
"args",
".",
"pid_file",
")",
"server_address",
"=",
"(",
"args",
".",
"listen_addr",
",",
"args",
".",
"listen_port",
")",
"httpd",
"=",
"YHSM_KSMServer",
"(",
"server_address",
",",
"partial",
"(",
"YHSM_KSMRequestHandler",
",",
"hsm",
",",
"aead_backend",
",",
"args",
")",
")",
"my_log_message",
"(",
"args",
".",
"debug",
"or",
"args",
".",
"verbose",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')\"",
"%",
"(",
"args",
".",
"listen_addr",
",",
"args",
".",
"listen_port",
",",
"args",
".",
"serve_url",
",",
"args",
".",
"key_handles",
",",
"args",
".",
"device",
",",
"args",
".",
"aead_dir",
",",
"args",
".",
"db_url",
")",
")",
"httpd",
".",
"serve_forever",
"(",
")"
] |
Start a BaseHTTPServer.HTTPServer and serve requests forever.
|
[
"Start",
"a",
"BaseHTTPServer",
".",
"HTTPServer",
"and",
"serve",
"requests",
"forever",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L394-L407
|
8,940
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
my_log_message
|
def my_log_message(verbose, prio, msg):
"""
Log to syslog, and possibly also to stderr.
"""
syslog.syslog(prio, msg)
if verbose or prio == syslog.LOG_ERR:
sys.stderr.write("%s\n" % (msg))
|
python
|
def my_log_message(verbose, prio, msg):
"""
Log to syslog, and possibly also to stderr.
"""
syslog.syslog(prio, msg)
if verbose or prio == syslog.LOG_ERR:
sys.stderr.write("%s\n" % (msg))
|
[
"def",
"my_log_message",
"(",
"verbose",
",",
"prio",
",",
"msg",
")",
":",
"syslog",
".",
"syslog",
"(",
"prio",
",",
"msg",
")",
"if",
"verbose",
"or",
"prio",
"==",
"syslog",
".",
"LOG_ERR",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"(",
"msg",
")",
")"
] |
Log to syslog, and possibly also to stderr.
|
[
"Log",
"to",
"syslog",
"and",
"possibly",
"also",
"to",
"stderr",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L410-L416
|
8,941
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
YHSM_KSMRequestHandler.do_GET
|
def do_GET(self):
""" Handle a HTTP GET request. """
# Example session:
# in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0
# out : OK counter=0004 low=f585 high=3e use=03
if self.path.startswith(self.serve_url):
from_key = self.path[len(self.serve_url):]
val_res = self.decrypt_yubikey_otp(from_key)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(val_res)
self.wfile.write("\n")
elif self.stats_url and self.path == self.stats_url:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
for key in stats:
self.wfile.write("%s %d\n" % (key, stats[key]))
else:
self.log_error("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, self.serve_url))
self.send_response(403, 'Forbidden')
self.end_headers()
|
python
|
def do_GET(self):
""" Handle a HTTP GET request. """
# Example session:
# in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0
# out : OK counter=0004 low=f585 high=3e use=03
if self.path.startswith(self.serve_url):
from_key = self.path[len(self.serve_url):]
val_res = self.decrypt_yubikey_otp(from_key)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(val_res)
self.wfile.write("\n")
elif self.stats_url and self.path == self.stats_url:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
for key in stats:
self.wfile.write("%s %d\n" % (key, stats[key]))
else:
self.log_error("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, self.serve_url))
self.send_response(403, 'Forbidden')
self.end_headers()
|
[
"def",
"do_GET",
"(",
"self",
")",
":",
"# Example session:",
"# in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0",
"# out : OK counter=0004 low=f585 high=3e use=03",
"if",
"self",
".",
"path",
".",
"startswith",
"(",
"self",
".",
"serve_url",
")",
":",
"from_key",
"=",
"self",
".",
"path",
"[",
"len",
"(",
"self",
".",
"serve_url",
")",
":",
"]",
"val_res",
"=",
"self",
".",
"decrypt_yubikey_otp",
"(",
"from_key",
")",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"'Content-type'",
",",
"'text/html'",
")",
"self",
".",
"end_headers",
"(",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"val_res",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"\"\\n\"",
")",
"elif",
"self",
".",
"stats_url",
"and",
"self",
".",
"path",
"==",
"self",
".",
"stats_url",
":",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"'Content-type'",
",",
"'text/html'",
")",
"self",
".",
"end_headers",
"(",
")",
"for",
"key",
"in",
"stats",
":",
"self",
".",
"wfile",
".",
"write",
"(",
"\"%s %d\\n\"",
"%",
"(",
"key",
",",
"stats",
"[",
"key",
"]",
")",
")",
"else",
":",
"self",
".",
"log_error",
"(",
"\"Bad URL '%s' - I'm serving '%s' (responding 403)\"",
"%",
"(",
"self",
".",
"path",
",",
"self",
".",
"serve_url",
")",
")",
"self",
".",
"send_response",
"(",
"403",
",",
"'Forbidden'",
")",
"self",
".",
"end_headers",
"(",
")"
] |
Handle a HTTP GET request.
|
[
"Handle",
"a",
"HTTP",
"GET",
"request",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L92-L116
|
8,942
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
YHSM_KSMRequestHandler.decrypt_yubikey_otp
|
def decrypt_yubikey_otp(self, from_key):
"""
Try to decrypt a YubiKey OTP.
Returns a string starting with either 'OK' or 'ERR' :
'OK counter=ab12 low=dd34 high=2a use=0a'
'ERR Unknown public_id'
on YubiHSM errors (or bad OTP), only 'ERR' is returned.
"""
if not re.match(valid_input_from_key, from_key):
self.log_error("IN: %s, Invalid OTP" % (from_key))
if self.stats_url:
stats['invalid'] += 1
return "ERR Invalid OTP"
public_id, _otp = pyhsm.yubikey.split_id_otp(from_key)
try:
aead = self.aead_backend.load_aead(public_id)
except Exception as e:
self.log_error(str(e))
if self.stats_url:
stats['no_aead'] += 1
return "ERR Unknown public_id"
try:
res = pyhsm.yubikey.validate_yubikey_with_aead(
self.hsm, from_key, aead, aead.key_handle)
# XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded
# XXX fix use vs session counter confusion
val_res = "OK counter=%04x low=%04x high=%02x use=%02x" % \
(res.use_ctr, res.ts_low, res.ts_high, res.session_ctr)
if self.stats_url:
stats['ok'] += 1
except pyhsm.exception.YHSM_Error as e:
self.log_error ("IN: %s, Validate FAILED: %s" % (from_key, str(e)))
val_res = "ERR"
if self.stats_url:
stats['err'] += 1
self.log_message("SUCCESS OTP %s PT hsm %s", from_key, val_res)
return val_res
|
python
|
def decrypt_yubikey_otp(self, from_key):
"""
Try to decrypt a YubiKey OTP.
Returns a string starting with either 'OK' or 'ERR' :
'OK counter=ab12 low=dd34 high=2a use=0a'
'ERR Unknown public_id'
on YubiHSM errors (or bad OTP), only 'ERR' is returned.
"""
if not re.match(valid_input_from_key, from_key):
self.log_error("IN: %s, Invalid OTP" % (from_key))
if self.stats_url:
stats['invalid'] += 1
return "ERR Invalid OTP"
public_id, _otp = pyhsm.yubikey.split_id_otp(from_key)
try:
aead = self.aead_backend.load_aead(public_id)
except Exception as e:
self.log_error(str(e))
if self.stats_url:
stats['no_aead'] += 1
return "ERR Unknown public_id"
try:
res = pyhsm.yubikey.validate_yubikey_with_aead(
self.hsm, from_key, aead, aead.key_handle)
# XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded
# XXX fix use vs session counter confusion
val_res = "OK counter=%04x low=%04x high=%02x use=%02x" % \
(res.use_ctr, res.ts_low, res.ts_high, res.session_ctr)
if self.stats_url:
stats['ok'] += 1
except pyhsm.exception.YHSM_Error as e:
self.log_error ("IN: %s, Validate FAILED: %s" % (from_key, str(e)))
val_res = "ERR"
if self.stats_url:
stats['err'] += 1
self.log_message("SUCCESS OTP %s PT hsm %s", from_key, val_res)
return val_res
|
[
"def",
"decrypt_yubikey_otp",
"(",
"self",
",",
"from_key",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"valid_input_from_key",
",",
"from_key",
")",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, Invalid OTP\"",
"%",
"(",
"from_key",
")",
")",
"if",
"self",
".",
"stats_url",
":",
"stats",
"[",
"'invalid'",
"]",
"+=",
"1",
"return",
"\"ERR Invalid OTP\"",
"public_id",
",",
"_otp",
"=",
"pyhsm",
".",
"yubikey",
".",
"split_id_otp",
"(",
"from_key",
")",
"try",
":",
"aead",
"=",
"self",
".",
"aead_backend",
".",
"load_aead",
"(",
"public_id",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log_error",
"(",
"str",
"(",
"e",
")",
")",
"if",
"self",
".",
"stats_url",
":",
"stats",
"[",
"'no_aead'",
"]",
"+=",
"1",
"return",
"\"ERR Unknown public_id\"",
"try",
":",
"res",
"=",
"pyhsm",
".",
"yubikey",
".",
"validate_yubikey_with_aead",
"(",
"self",
".",
"hsm",
",",
"from_key",
",",
"aead",
",",
"aead",
".",
"key_handle",
")",
"# XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded",
"# XXX fix use vs session counter confusion",
"val_res",
"=",
"\"OK counter=%04x low=%04x high=%02x use=%02x\"",
"%",
"(",
"res",
".",
"use_ctr",
",",
"res",
".",
"ts_low",
",",
"res",
".",
"ts_high",
",",
"res",
".",
"session_ctr",
")",
"if",
"self",
".",
"stats_url",
":",
"stats",
"[",
"'ok'",
"]",
"+=",
"1",
"except",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"as",
"e",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, Validate FAILED: %s\"",
"%",
"(",
"from_key",
",",
"str",
"(",
"e",
")",
")",
")",
"val_res",
"=",
"\"ERR\"",
"if",
"self",
".",
"stats_url",
":",
"stats",
"[",
"'err'",
"]",
"+=",
"1",
"self",
".",
"log_message",
"(",
"\"SUCCESS OTP %s PT hsm %s\"",
",",
"from_key",
",",
"val_res",
")",
"return",
"val_res"
] |
Try to decrypt a YubiKey OTP.
Returns a string starting with either 'OK' or 'ERR' :
'OK counter=ab12 low=dd34 high=2a use=0a'
'ERR Unknown public_id'
on YubiHSM errors (or bad OTP), only 'ERR' is returned.
|
[
"Try",
"to",
"decrypt",
"a",
"YubiKey",
"OTP",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L118-L162
|
8,943
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
YHSM_KSMRequestHandler.my_address_string
|
def my_address_string(self):
""" For logging client host without resolving. """
addr = getattr(self, 'client_address', ('', None))[0]
# If listed in proxy_ips, use the X-Forwarded-For header, if present.
if addr in self.proxy_ips:
return self.headers.getheader('x-forwarded-for', addr)
return addr
|
python
|
def my_address_string(self):
""" For logging client host without resolving. """
addr = getattr(self, 'client_address', ('', None))[0]
# If listed in proxy_ips, use the X-Forwarded-For header, if present.
if addr in self.proxy_ips:
return self.headers.getheader('x-forwarded-for', addr)
return addr
|
[
"def",
"my_address_string",
"(",
"self",
")",
":",
"addr",
"=",
"getattr",
"(",
"self",
",",
"'client_address'",
",",
"(",
"''",
",",
"None",
")",
")",
"[",
"0",
"]",
"# If listed in proxy_ips, use the X-Forwarded-For header, if present.",
"if",
"addr",
"in",
"self",
".",
"proxy_ips",
":",
"return",
"self",
".",
"headers",
".",
"getheader",
"(",
"'x-forwarded-for'",
",",
"addr",
")",
"return",
"addr"
] |
For logging client host without resolving.
|
[
"For",
"logging",
"client",
"host",
"without",
"resolving",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L174-L181
|
8,944
|
Yubico/python-pyhsm
|
pyhsm/ksm/yubikey_ksm.py
|
SQLBackend.load_aead
|
def load_aead(self, public_id):
""" Loads AEAD from the specified database. """
connection = self.engine.connect()
trans = connection.begin()
try:
s = sqlalchemy.select([self.aead_table]).where(
(self.aead_table.c.public_id == public_id)
& self.aead_table.c.keyhandle.in_([kh[1] for kh in self.key_handles]))
result = connection.execute(s)
for row in result:
kh_int = row['keyhandle']
aead = pyhsm.aead_cmd.YHSM_GeneratedAEAD(None, kh_int, '')
aead.data = row['aead']
aead.nonce = row['nonce']
return aead
except Exception as e:
trans.rollback()
raise Exception("No AEAD in DB for public_id %s (%s)" % (public_id, str(e)))
finally:
connection.close()
|
python
|
def load_aead(self, public_id):
""" Loads AEAD from the specified database. """
connection = self.engine.connect()
trans = connection.begin()
try:
s = sqlalchemy.select([self.aead_table]).where(
(self.aead_table.c.public_id == public_id)
& self.aead_table.c.keyhandle.in_([kh[1] for kh in self.key_handles]))
result = connection.execute(s)
for row in result:
kh_int = row['keyhandle']
aead = pyhsm.aead_cmd.YHSM_GeneratedAEAD(None, kh_int, '')
aead.data = row['aead']
aead.nonce = row['nonce']
return aead
except Exception as e:
trans.rollback()
raise Exception("No AEAD in DB for public_id %s (%s)" % (public_id, str(e)))
finally:
connection.close()
|
[
"def",
"load_aead",
"(",
"self",
",",
"public_id",
")",
":",
"connection",
"=",
"self",
".",
"engine",
".",
"connect",
"(",
")",
"trans",
"=",
"connection",
".",
"begin",
"(",
")",
"try",
":",
"s",
"=",
"sqlalchemy",
".",
"select",
"(",
"[",
"self",
".",
"aead_table",
"]",
")",
".",
"where",
"(",
"(",
"self",
".",
"aead_table",
".",
"c",
".",
"public_id",
"==",
"public_id",
")",
"&",
"self",
".",
"aead_table",
".",
"c",
".",
"keyhandle",
".",
"in_",
"(",
"[",
"kh",
"[",
"1",
"]",
"for",
"kh",
"in",
"self",
".",
"key_handles",
"]",
")",
")",
"result",
"=",
"connection",
".",
"execute",
"(",
"s",
")",
"for",
"row",
"in",
"result",
":",
"kh_int",
"=",
"row",
"[",
"'keyhandle'",
"]",
"aead",
"=",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_GeneratedAEAD",
"(",
"None",
",",
"kh_int",
",",
"''",
")",
"aead",
".",
"data",
"=",
"row",
"[",
"'aead'",
"]",
"aead",
".",
"nonce",
"=",
"row",
"[",
"'nonce'",
"]",
"return",
"aead",
"except",
"Exception",
"as",
"e",
":",
"trans",
".",
"rollback",
"(",
")",
"raise",
"Exception",
"(",
"\"No AEAD in DB for public_id %s (%s)\"",
"%",
"(",
"public_id",
",",
"str",
"(",
"e",
")",
")",
")",
"finally",
":",
"connection",
".",
"close",
"(",
")"
] |
Loads AEAD from the specified database.
|
[
"Loads",
"AEAD",
"from",
"the",
"specified",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L215-L236
|
8,945
|
Yubico/python-pyhsm
|
pyhsm/val/init_oath_token.py
|
generate_aead
|
def generate_aead(hsm, args):
""" Protect the oath-k in an AEAD. """
key = get_oath_k(args)
# Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE
flags = struct.pack("< I", 0x10000)
hsm.load_secret(key + flags)
nonce = hsm.get_nonce().nonce
aead = hsm.generate_aead(nonce, args.key_handle)
if args.debug:
print "AEAD: %s (%s)" % (aead.data.encode('hex'), aead)
return nonce, aead
|
python
|
def generate_aead(hsm, args):
""" Protect the oath-k in an AEAD. """
key = get_oath_k(args)
# Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE
flags = struct.pack("< I", 0x10000)
hsm.load_secret(key + flags)
nonce = hsm.get_nonce().nonce
aead = hsm.generate_aead(nonce, args.key_handle)
if args.debug:
print "AEAD: %s (%s)" % (aead.data.encode('hex'), aead)
return nonce, aead
|
[
"def",
"generate_aead",
"(",
"hsm",
",",
"args",
")",
":",
"key",
"=",
"get_oath_k",
"(",
"args",
")",
"# Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE",
"flags",
"=",
"struct",
".",
"pack",
"(",
"\"< I\"",
",",
"0x10000",
")",
"hsm",
".",
"load_secret",
"(",
"key",
"+",
"flags",
")",
"nonce",
"=",
"hsm",
".",
"get_nonce",
"(",
")",
".",
"nonce",
"aead",
"=",
"hsm",
".",
"generate_aead",
"(",
"nonce",
",",
"args",
".",
"key_handle",
")",
"if",
"args",
".",
"debug",
":",
"print",
"\"AEAD: %s (%s)\"",
"%",
"(",
"aead",
".",
"data",
".",
"encode",
"(",
"'hex'",
")",
",",
"aead",
")",
"return",
"nonce",
",",
"aead"
] |
Protect the oath-k in an AEAD.
|
[
"Protect",
"the",
"oath",
"-",
"k",
"in",
"an",
"AEAD",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L105-L115
|
8,946
|
Yubico/python-pyhsm
|
pyhsm/val/init_oath_token.py
|
store_oath_entry
|
def store_oath_entry(args, nonce, aead, oath_c):
""" Store the AEAD in the database. """
data = {"key": args.uid,
"aead": aead.data.encode('hex'),
"nonce": nonce.encode('hex'),
"key_handle": args.key_handle,
"oath_C": oath_c,
"oath_T": None,
}
entry = ValOathEntry(data)
db = ValOathDb(args.db_file)
try:
if args.force:
db.delete(entry)
db.add(entry)
except sqlite3.IntegrityError, e:
sys.stderr.write("ERROR: %s\n" % (e))
return False
return True
|
python
|
def store_oath_entry(args, nonce, aead, oath_c):
""" Store the AEAD in the database. """
data = {"key": args.uid,
"aead": aead.data.encode('hex'),
"nonce": nonce.encode('hex'),
"key_handle": args.key_handle,
"oath_C": oath_c,
"oath_T": None,
}
entry = ValOathEntry(data)
db = ValOathDb(args.db_file)
try:
if args.force:
db.delete(entry)
db.add(entry)
except sqlite3.IntegrityError, e:
sys.stderr.write("ERROR: %s\n" % (e))
return False
return True
|
[
"def",
"store_oath_entry",
"(",
"args",
",",
"nonce",
",",
"aead",
",",
"oath_c",
")",
":",
"data",
"=",
"{",
"\"key\"",
":",
"args",
".",
"uid",
",",
"\"aead\"",
":",
"aead",
".",
"data",
".",
"encode",
"(",
"'hex'",
")",
",",
"\"nonce\"",
":",
"nonce",
".",
"encode",
"(",
"'hex'",
")",
",",
"\"key_handle\"",
":",
"args",
".",
"key_handle",
",",
"\"oath_C\"",
":",
"oath_c",
",",
"\"oath_T\"",
":",
"None",
",",
"}",
"entry",
"=",
"ValOathEntry",
"(",
"data",
")",
"db",
"=",
"ValOathDb",
"(",
"args",
".",
"db_file",
")",
"try",
":",
"if",
"args",
".",
"force",
":",
"db",
".",
"delete",
"(",
"entry",
")",
"db",
".",
"add",
"(",
"entry",
")",
"except",
"sqlite3",
".",
"IntegrityError",
",",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: %s\\n\"",
"%",
"(",
"e",
")",
")",
"return",
"False",
"return",
"True"
] |
Store the AEAD in the database.
|
[
"Store",
"the",
"AEAD",
"in",
"the",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L185-L203
|
8,947
|
Yubico/python-pyhsm
|
pyhsm/val/init_oath_token.py
|
ValOathDb.add
|
def add(self, entry):
""" Add entry to database. """
c = self.conn.cursor()
c.execute("INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)",
(entry.data["key"], \
entry.data["aead"], \
entry.data["nonce"], \
entry.data["key_handle"], \
entry.data["oath_C"], \
entry.data["oath_T"],))
self.conn.commit()
return c.rowcount == 1
|
python
|
def add(self, entry):
""" Add entry to database. """
c = self.conn.cursor()
c.execute("INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)",
(entry.data["key"], \
entry.data["aead"], \
entry.data["nonce"], \
entry.data["key_handle"], \
entry.data["oath_C"], \
entry.data["oath_T"],))
self.conn.commit()
return c.rowcount == 1
|
[
"def",
"add",
"(",
"self",
",",
"entry",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)\"",
",",
"(",
"entry",
".",
"data",
"[",
"\"key\"",
"]",
",",
"entry",
".",
"data",
"[",
"\"aead\"",
"]",
",",
"entry",
".",
"data",
"[",
"\"nonce\"",
"]",
",",
"entry",
".",
"data",
"[",
"\"key_handle\"",
"]",
",",
"entry",
".",
"data",
"[",
"\"oath_C\"",
"]",
",",
"entry",
".",
"data",
"[",
"\"oath_T\"",
"]",
",",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"c",
".",
"rowcount",
"==",
"1"
] |
Add entry to database.
|
[
"Add",
"entry",
"to",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L161-L172
|
8,948
|
Yubico/python-pyhsm
|
pyhsm/val/init_oath_token.py
|
ValOathDb.delete
|
def delete(self, entry):
""" Delete entry from database. """
c = self.conn.cursor()
c.execute("DELETE FROM oath WHERE key = ?", (entry.data["key"],))
|
python
|
def delete(self, entry):
""" Delete entry from database. """
c = self.conn.cursor()
c.execute("DELETE FROM oath WHERE key = ?", (entry.data["key"],))
|
[
"def",
"delete",
"(",
"self",
",",
"entry",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"DELETE FROM oath WHERE key = ?\"",
",",
"(",
"entry",
".",
"data",
"[",
"\"key\"",
"]",
",",
")",
")"
] |
Delete entry from database.
|
[
"Delete",
"entry",
"from",
"database",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L174-L177
|
8,949
|
Yubico/python-pyhsm
|
pyhsm/aead_cmd.py
|
YHSM_AEAD_Cmd.parse_result
|
def parse_result(self, data):
"""
Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed.
"""
# typedef struct {
# uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs)
# uint32_t keyHandle; // Key handle
# YSM_STATUS status; // Status
# uint8_t numBytes; // Number of bytes in AEAD block
# uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block
# } YSM_AEAD_GENERATE_RESP;
nonce, \
key_handle, \
self.status, \
num_bytes = struct.unpack_from("< %is I B B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data, 0)
pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)
if self.status == pyhsm.defines.YSM_STATUS_OK:
pyhsm.util.validate_cmd_response_nonce(nonce, self.nonce)
offset = pyhsm.defines.YSM_AEAD_NONCE_SIZE + 6
aead = data[offset:offset + num_bytes]
self.response = YHSM_GeneratedAEAD(nonce, key_handle, aead)
return self.response
else:
raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)
|
python
|
def parse_result(self, data):
"""
Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed.
"""
# typedef struct {
# uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs)
# uint32_t keyHandle; // Key handle
# YSM_STATUS status; // Status
# uint8_t numBytes; // Number of bytes in AEAD block
# uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block
# } YSM_AEAD_GENERATE_RESP;
nonce, \
key_handle, \
self.status, \
num_bytes = struct.unpack_from("< %is I B B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data, 0)
pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)
if self.status == pyhsm.defines.YSM_STATUS_OK:
pyhsm.util.validate_cmd_response_nonce(nonce, self.nonce)
offset = pyhsm.defines.YSM_AEAD_NONCE_SIZE + 6
aead = data[offset:offset + num_bytes]
self.response = YHSM_GeneratedAEAD(nonce, key_handle, aead)
return self.response
else:
raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)
|
[
"def",
"parse_result",
"(",
"self",
",",
"data",
")",
":",
"# typedef struct {",
"# uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs)",
"# uint32_t keyHandle; // Key handle",
"# YSM_STATUS status; // Status",
"# uint8_t numBytes; // Number of bytes in AEAD block",
"# uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block",
"# } YSM_AEAD_GENERATE_RESP;",
"nonce",
",",
"key_handle",
",",
"self",
".",
"status",
",",
"num_bytes",
"=",
"struct",
".",
"unpack_from",
"(",
"\"< %is I B B\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
")",
",",
"data",
",",
"0",
")",
"pyhsm",
".",
"util",
".",
"validate_cmd_response_hex",
"(",
"'key_handle'",
",",
"key_handle",
",",
"self",
".",
"key_handle",
")",
"if",
"self",
".",
"status",
"==",
"pyhsm",
".",
"defines",
".",
"YSM_STATUS_OK",
":",
"pyhsm",
".",
"util",
".",
"validate_cmd_response_nonce",
"(",
"nonce",
",",
"self",
".",
"nonce",
")",
"offset",
"=",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
"+",
"6",
"aead",
"=",
"data",
"[",
"offset",
":",
"offset",
"+",
"num_bytes",
"]",
"self",
".",
"response",
"=",
"YHSM_GeneratedAEAD",
"(",
"nonce",
",",
"key_handle",
",",
"aead",
")",
"return",
"self",
".",
"response",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"self",
".",
"command",
")",
",",
"self",
".",
"status",
")"
] |
Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed.
|
[
"Returns",
"a",
"YHSM_GeneratedAEAD",
"instance",
"or",
"throws",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L58-L84
|
8,950
|
Yubico/python-pyhsm
|
pyhsm/aead_cmd.py
|
YHSM_GeneratedAEAD.save
|
def save(self, filename):
"""
Store AEAD in a file.
@param filename: File to create/overwrite
@type filename: string
"""
aead_f = open(filename, "wb")
fmt = "< B I %is %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(self.data))
version = 1
packed = struct.pack(fmt, version, self.key_handle, self.nonce, self.data)
aead_f.write(YHSM_AEAD_File_Marker + packed)
aead_f.close()
|
python
|
def save(self, filename):
"""
Store AEAD in a file.
@param filename: File to create/overwrite
@type filename: string
"""
aead_f = open(filename, "wb")
fmt = "< B I %is %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(self.data))
version = 1
packed = struct.pack(fmt, version, self.key_handle, self.nonce, self.data)
aead_f.write(YHSM_AEAD_File_Marker + packed)
aead_f.close()
|
[
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"aead_f",
"=",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"fmt",
"=",
"\"< B I %is %is\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
",",
"len",
"(",
"self",
".",
"data",
")",
")",
"version",
"=",
"1",
"packed",
"=",
"struct",
".",
"pack",
"(",
"fmt",
",",
"version",
",",
"self",
".",
"key_handle",
",",
"self",
".",
"nonce",
",",
"self",
".",
"data",
")",
"aead_f",
".",
"write",
"(",
"YHSM_AEAD_File_Marker",
"+",
"packed",
")",
"aead_f",
".",
"close",
"(",
")"
] |
Store AEAD in a file.
@param filename: File to create/overwrite
@type filename: string
|
[
"Store",
"AEAD",
"in",
"a",
"file",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L214-L226
|
8,951
|
Yubico/python-pyhsm
|
pyhsm/aead_cmd.py
|
YHSM_GeneratedAEAD.load
|
def load(self, filename):
"""
Load AEAD from a file.
@param filename: File to read AEAD from
@type filename: string
"""
aead_f = open(filename, "rb")
buf = aead_f.read(1024)
if buf.startswith(YHSM_AEAD_CRLF_File_Marker):
buf = YHSM_AEAD_File_Marker + buf[len(YHSM_AEAD_CRLF_File_Marker):]
if buf.startswith(YHSM_AEAD_File_Marker):
if buf[len(YHSM_AEAD_File_Marker)] == chr(1):
# version 1 format
fmt = "< I %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE)
self.key_handle, self.nonce = struct.unpack_from(fmt, buf, len(YHSM_AEAD_File_Marker) + 1)
self.data = buf[len(YHSM_AEAD_File_Marker) + 1 + struct.calcsize(fmt):]
else:
raise pyhsm.exception.YHSM_Error('Unknown AEAD file format')
else:
# version 0 format, just AEAD data
self.data = buf[:pyhsm.defines.YSM_MAX_KEY_SIZE + pyhsm.defines.YSM_BLOCK_SIZE]
aead_f.close()
|
python
|
def load(self, filename):
"""
Load AEAD from a file.
@param filename: File to read AEAD from
@type filename: string
"""
aead_f = open(filename, "rb")
buf = aead_f.read(1024)
if buf.startswith(YHSM_AEAD_CRLF_File_Marker):
buf = YHSM_AEAD_File_Marker + buf[len(YHSM_AEAD_CRLF_File_Marker):]
if buf.startswith(YHSM_AEAD_File_Marker):
if buf[len(YHSM_AEAD_File_Marker)] == chr(1):
# version 1 format
fmt = "< I %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE)
self.key_handle, self.nonce = struct.unpack_from(fmt, buf, len(YHSM_AEAD_File_Marker) + 1)
self.data = buf[len(YHSM_AEAD_File_Marker) + 1 + struct.calcsize(fmt):]
else:
raise pyhsm.exception.YHSM_Error('Unknown AEAD file format')
else:
# version 0 format, just AEAD data
self.data = buf[:pyhsm.defines.YSM_MAX_KEY_SIZE + pyhsm.defines.YSM_BLOCK_SIZE]
aead_f.close()
|
[
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"aead_f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"buf",
"=",
"aead_f",
".",
"read",
"(",
"1024",
")",
"if",
"buf",
".",
"startswith",
"(",
"YHSM_AEAD_CRLF_File_Marker",
")",
":",
"buf",
"=",
"YHSM_AEAD_File_Marker",
"+",
"buf",
"[",
"len",
"(",
"YHSM_AEAD_CRLF_File_Marker",
")",
":",
"]",
"if",
"buf",
".",
"startswith",
"(",
"YHSM_AEAD_File_Marker",
")",
":",
"if",
"buf",
"[",
"len",
"(",
"YHSM_AEAD_File_Marker",
")",
"]",
"==",
"chr",
"(",
"1",
")",
":",
"# version 1 format",
"fmt",
"=",
"\"< I %is\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
")",
"self",
".",
"key_handle",
",",
"self",
".",
"nonce",
"=",
"struct",
".",
"unpack_from",
"(",
"fmt",
",",
"buf",
",",
"len",
"(",
"YHSM_AEAD_File_Marker",
")",
"+",
"1",
")",
"self",
".",
"data",
"=",
"buf",
"[",
"len",
"(",
"YHSM_AEAD_File_Marker",
")",
"+",
"1",
"+",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
":",
"]",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"'Unknown AEAD file format'",
")",
"else",
":",
"# version 0 format, just AEAD data",
"self",
".",
"data",
"=",
"buf",
"[",
":",
"pyhsm",
".",
"defines",
".",
"YSM_MAX_KEY_SIZE",
"+",
"pyhsm",
".",
"defines",
".",
"YSM_BLOCK_SIZE",
"]",
"aead_f",
".",
"close",
"(",
")"
] |
Load AEAD from a file.
@param filename: File to read AEAD from
@type filename: string
|
[
"Load",
"AEAD",
"from",
"a",
"file",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L228-L250
|
8,952
|
Yubico/python-pyhsm
|
pyhsm/aead_cmd.py
|
YHSM_YubiKeySecret.pack
|
def pack(self):
""" Return key and uid packed for sending in a command to the YubiHSM. """
# # 22-bytes Yubikey secrets block
# typedef struct {
# uint8_t key[KEY_SIZE]; // AES key
# uint8_t uid[UID_SIZE]; // Unique (secret) ID
# } YUBIKEY_SECRETS;
return self.key + self.uid.ljust(pyhsm.defines.UID_SIZE, chr(0))
|
python
|
def pack(self):
""" Return key and uid packed for sending in a command to the YubiHSM. """
# # 22-bytes Yubikey secrets block
# typedef struct {
# uint8_t key[KEY_SIZE]; // AES key
# uint8_t uid[UID_SIZE]; // Unique (secret) ID
# } YUBIKEY_SECRETS;
return self.key + self.uid.ljust(pyhsm.defines.UID_SIZE, chr(0))
|
[
"def",
"pack",
"(",
"self",
")",
":",
"# # 22-bytes Yubikey secrets block",
"# typedef struct {",
"# uint8_t key[KEY_SIZE]; // AES key",
"# uint8_t uid[UID_SIZE]; // Unique (secret) ID",
"# } YUBIKEY_SECRETS;",
"return",
"self",
".",
"key",
"+",
"self",
".",
"uid",
".",
"ljust",
"(",
"pyhsm",
".",
"defines",
".",
"UID_SIZE",
",",
"chr",
"(",
"0",
")",
")"
] |
Return key and uid packed for sending in a command to the YubiHSM.
|
[
"Return",
"key",
"and",
"uid",
"packed",
"for",
"sending",
"in",
"a",
"command",
"to",
"the",
"YubiHSM",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L258-L265
|
8,953
|
Yubico/python-pyhsm
|
pyhsm/val/validate_otp.py
|
validate_otp
|
def validate_otp(hsm, args):
"""
Validate an OTP.
"""
try:
res = pyhsm.yubikey.validate_otp(hsm, args.otp)
if args.verbose:
print "OK counter=%04x low=%04x high=%02x use=%02x" % \
(res.use_ctr, res.ts_low, res.ts_high, res.session_ctr)
return 0
except pyhsm.exception.YHSM_CommandFailed, e:
if args.verbose:
print "%s" % (pyhsm.defines.status2str(e.status))
# figure out numerical response code
for r in [pyhsm.defines.YSM_OTP_INVALID, \
pyhsm.defines.YSM_OTP_REPLAY, \
pyhsm.defines.YSM_ID_NOT_FOUND]:
if e.status == r:
return r - pyhsm.defines.YSM_RESPONSE
# not found
return 0xff
|
python
|
def validate_otp(hsm, args):
"""
Validate an OTP.
"""
try:
res = pyhsm.yubikey.validate_otp(hsm, args.otp)
if args.verbose:
print "OK counter=%04x low=%04x high=%02x use=%02x" % \
(res.use_ctr, res.ts_low, res.ts_high, res.session_ctr)
return 0
except pyhsm.exception.YHSM_CommandFailed, e:
if args.verbose:
print "%s" % (pyhsm.defines.status2str(e.status))
# figure out numerical response code
for r in [pyhsm.defines.YSM_OTP_INVALID, \
pyhsm.defines.YSM_OTP_REPLAY, \
pyhsm.defines.YSM_ID_NOT_FOUND]:
if e.status == r:
return r - pyhsm.defines.YSM_RESPONSE
# not found
return 0xff
|
[
"def",
"validate_otp",
"(",
"hsm",
",",
"args",
")",
":",
"try",
":",
"res",
"=",
"pyhsm",
".",
"yubikey",
".",
"validate_otp",
"(",
"hsm",
",",
"args",
".",
"otp",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\"OK counter=%04x low=%04x high=%02x use=%02x\"",
"%",
"(",
"res",
".",
"use_ctr",
",",
"res",
".",
"ts_low",
",",
"res",
".",
"ts_high",
",",
"res",
".",
"session_ctr",
")",
"return",
"0",
"except",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
",",
"e",
":",
"if",
"args",
".",
"verbose",
":",
"print",
"\"%s\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"status2str",
"(",
"e",
".",
"status",
")",
")",
"# figure out numerical response code",
"for",
"r",
"in",
"[",
"pyhsm",
".",
"defines",
".",
"YSM_OTP_INVALID",
",",
"pyhsm",
".",
"defines",
".",
"YSM_OTP_REPLAY",
",",
"pyhsm",
".",
"defines",
".",
"YSM_ID_NOT_FOUND",
"]",
":",
"if",
"e",
".",
"status",
"==",
"r",
":",
"return",
"r",
"-",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
"# not found",
"return",
"0xff"
] |
Validate an OTP.
|
[
"Validate",
"an",
"OTP",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validate_otp.py#L61-L81
|
8,954
|
Yubico/python-pyhsm
|
pyhsm/oath_totp.py
|
search_for_oath_code
|
def search_for_oath_code(hsm, key_handle, nonce, aead, user_code, interval=30,
tolerance=0):
"""
Try to validate an OATH TOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns timecounter value on successful auth, and None otherwise.
"""
# timecounter is the lowest acceptable value based on tolerance
timecounter = timecode(datetime.datetime.now(), interval) - tolerance
return search_hotp(
hsm, key_handle, nonce, aead, timecounter, user_code, 1 + 2*tolerance)
|
python
|
def search_for_oath_code(hsm, key_handle, nonce, aead, user_code, interval=30,
tolerance=0):
"""
Try to validate an OATH TOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns timecounter value on successful auth, and None otherwise.
"""
# timecounter is the lowest acceptable value based on tolerance
timecounter = timecode(datetime.datetime.now(), interval) - tolerance
return search_hotp(
hsm, key_handle, nonce, aead, timecounter, user_code, 1 + 2*tolerance)
|
[
"def",
"search_for_oath_code",
"(",
"hsm",
",",
"key_handle",
",",
"nonce",
",",
"aead",
",",
"user_code",
",",
"interval",
"=",
"30",
",",
"tolerance",
"=",
"0",
")",
":",
"# timecounter is the lowest acceptable value based on tolerance",
"timecounter",
"=",
"timecode",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"interval",
")",
"-",
"tolerance",
"return",
"search_hotp",
"(",
"hsm",
",",
"key_handle",
",",
"nonce",
",",
"aead",
",",
"timecounter",
",",
"user_code",
",",
"1",
"+",
"2",
"*",
"tolerance",
")"
] |
Try to validate an OATH TOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns timecounter value on successful auth, and None otherwise.
|
[
"Try",
"to",
"validate",
"an",
"OATH",
"TOTP",
"OTP",
"generated",
"by",
"a",
"token",
"whose",
"secret",
"key",
"is",
"available",
"to",
"the",
"YubiHSM",
"through",
"the",
"AEAD",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_totp.py#L21-L36
|
8,955
|
Yubico/python-pyhsm
|
pyhsm/oath_totp.py
|
timecode
|
def timecode(time_now, interval):
""" make integer and divide by time interval of valid OTP """
i = time.mktime(time_now.timetuple())
return int(i / interval)
|
python
|
def timecode(time_now, interval):
""" make integer and divide by time interval of valid OTP """
i = time.mktime(time_now.timetuple())
return int(i / interval)
|
[
"def",
"timecode",
"(",
"time_now",
",",
"interval",
")",
":",
"i",
"=",
"time",
".",
"mktime",
"(",
"time_now",
".",
"timetuple",
"(",
")",
")",
"return",
"int",
"(",
"i",
"/",
"interval",
")"
] |
make integer and divide by time interval of valid OTP
|
[
"make",
"integer",
"and",
"divide",
"by",
"time",
"interval",
"of",
"valid",
"OTP"
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_totp.py#L39-L42
|
8,956
|
Yubico/python-pyhsm
|
pyhsm/soft_hsm.py
|
_xor_block
|
def _xor_block(a, b):
""" XOR two blocks of equal length. """
return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
|
python
|
def _xor_block(a, b):
""" XOR two blocks of equal length. """
return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
|
[
"def",
"_xor_block",
"(",
"a",
",",
"b",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"chr",
"(",
"ord",
"(",
"x",
")",
"^",
"ord",
"(",
"y",
")",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"a",
",",
"b",
")",
"]",
")"
] |
XOR two blocks of equal length.
|
[
"XOR",
"two",
"blocks",
"of",
"equal",
"length",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L26-L28
|
8,957
|
Yubico/python-pyhsm
|
pyhsm/soft_hsm.py
|
crc16
|
def crc16(data):
"""
Calculate an ISO13239 CRC checksum of the input buffer.
"""
m_crc = 0xffff
for this in data:
m_crc ^= ord(this)
for _ in range(8):
j = m_crc & 1
m_crc >>= 1
if j:
m_crc ^= 0x8408
return m_crc
|
python
|
def crc16(data):
"""
Calculate an ISO13239 CRC checksum of the input buffer.
"""
m_crc = 0xffff
for this in data:
m_crc ^= ord(this)
for _ in range(8):
j = m_crc & 1
m_crc >>= 1
if j:
m_crc ^= 0x8408
return m_crc
|
[
"def",
"crc16",
"(",
"data",
")",
":",
"m_crc",
"=",
"0xffff",
"for",
"this",
"in",
"data",
":",
"m_crc",
"^=",
"ord",
"(",
"this",
")",
"for",
"_",
"in",
"range",
"(",
"8",
")",
":",
"j",
"=",
"m_crc",
"&",
"1",
"m_crc",
">>=",
"1",
"if",
"j",
":",
"m_crc",
"^=",
"0x8408",
"return",
"m_crc"
] |
Calculate an ISO13239 CRC checksum of the input buffer.
|
[
"Calculate",
"an",
"ISO13239",
"CRC",
"checksum",
"of",
"the",
"input",
"buffer",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L132-L144
|
8,958
|
Yubico/python-pyhsm
|
pyhsm/soft_hsm.py
|
_cbc_mac.finalize
|
def finalize(self, block):
"""
The final step of CBC-MAC encrypts before xor.
"""
t1 = self.mac_aes.encrypt(block)
t2 = _xor_block(self.mac, t1)
self.mac = t2
|
python
|
def finalize(self, block):
"""
The final step of CBC-MAC encrypts before xor.
"""
t1 = self.mac_aes.encrypt(block)
t2 = _xor_block(self.mac, t1)
self.mac = t2
|
[
"def",
"finalize",
"(",
"self",
",",
"block",
")",
":",
"t1",
"=",
"self",
".",
"mac_aes",
".",
"encrypt",
"(",
"block",
")",
"t2",
"=",
"_xor_block",
"(",
"self",
".",
"mac",
",",
"t1",
")",
"self",
".",
"mac",
"=",
"t2"
] |
The final step of CBC-MAC encrypts before xor.
|
[
"The",
"final",
"step",
"of",
"CBC",
"-",
"MAC",
"encrypts",
"before",
"xor",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L77-L83
|
8,959
|
Yubico/python-pyhsm
|
pyhsm/yubikey.py
|
validate_otp
|
def validate_otp(hsm, from_key):
"""
Try to validate an OTP from a YubiKey using the internal database
on the YubiHSM.
`from_key' is the modhex encoded string emitted when you press the
button on your YubiKey.
Will only return on succesfull validation. All failures will result
in an L{pyhsm.exception.YHSM_CommandFailed}.
@param hsm: The YHSM instance
@param from_key: The OTP from a YubiKey (in modhex)
@type hsm: L{pyhsm.YHSM}
@type from_key: string
@returns: validation response, if successful
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP.parse_result}
"""
public_id, otp = split_id_otp(from_key)
return hsm.db_validate_yubikey_otp(modhex_decode(public_id).decode('hex'),
modhex_decode(otp).decode('hex')
)
|
python
|
def validate_otp(hsm, from_key):
"""
Try to validate an OTP from a YubiKey using the internal database
on the YubiHSM.
`from_key' is the modhex encoded string emitted when you press the
button on your YubiKey.
Will only return on succesfull validation. All failures will result
in an L{pyhsm.exception.YHSM_CommandFailed}.
@param hsm: The YHSM instance
@param from_key: The OTP from a YubiKey (in modhex)
@type hsm: L{pyhsm.YHSM}
@type from_key: string
@returns: validation response, if successful
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP.parse_result}
"""
public_id, otp = split_id_otp(from_key)
return hsm.db_validate_yubikey_otp(modhex_decode(public_id).decode('hex'),
modhex_decode(otp).decode('hex')
)
|
[
"def",
"validate_otp",
"(",
"hsm",
",",
"from_key",
")",
":",
"public_id",
",",
"otp",
"=",
"split_id_otp",
"(",
"from_key",
")",
"return",
"hsm",
".",
"db_validate_yubikey_otp",
"(",
"modhex_decode",
"(",
"public_id",
")",
".",
"decode",
"(",
"'hex'",
")",
",",
"modhex_decode",
"(",
"otp",
")",
".",
"decode",
"(",
"'hex'",
")",
")"
] |
Try to validate an OTP from a YubiKey using the internal database
on the YubiHSM.
`from_key' is the modhex encoded string emitted when you press the
button on your YubiKey.
Will only return on succesfull validation. All failures will result
in an L{pyhsm.exception.YHSM_CommandFailed}.
@param hsm: The YHSM instance
@param from_key: The OTP from a YubiKey (in modhex)
@type hsm: L{pyhsm.YHSM}
@type from_key: string
@returns: validation response, if successful
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP.parse_result}
|
[
"Try",
"to",
"validate",
"an",
"OTP",
"from",
"a",
"YubiKey",
"using",
"the",
"internal",
"database",
"on",
"the",
"YubiHSM",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L24-L48
|
8,960
|
Yubico/python-pyhsm
|
pyhsm/yubikey.py
|
validate_yubikey_with_aead
|
def validate_yubikey_with_aead(hsm, from_key, aead, key_handle):
"""
Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey's
internal secret, using the key_handle for the AEAD.
`from_key' is the modhex encoded string emitted when you press the
button on your YubiKey.
Will only return on succesfull validation. All failures will result
in an L{pyhsm.exception.YHSM_CommandFailed}.
@param hsm: The YHSM instance
@param from_key: The OTP from a YubiKey (in modhex)
@param aead: AEAD containing the cryptographic key and permission flags
@param key_handle: The key handle that can decrypt the AEAD
@type hsm: L{pyhsm.YHSM}
@type from_key: string
@type aead: L{YHSM_GeneratedAEAD} or string
@type key_handle: integer or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP.parse_result}
"""
from_key = pyhsm.util.input_validate_str(from_key, 'from_key', max_len = 48)
nonce = aead.nonce
aead = pyhsm.util.input_validate_aead(aead)
key_handle = pyhsm.util.input_validate_key_handle(key_handle)
public_id, otp = split_id_otp(from_key)
public_id = modhex_decode(public_id)
otp = modhex_decode(otp)
if not nonce:
nonce = public_id.decode('hex')
return hsm.validate_aead_otp(nonce, otp.decode('hex'),
key_handle, aead)
|
python
|
def validate_yubikey_with_aead(hsm, from_key, aead, key_handle):
"""
Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey's
internal secret, using the key_handle for the AEAD.
`from_key' is the modhex encoded string emitted when you press the
button on your YubiKey.
Will only return on succesfull validation. All failures will result
in an L{pyhsm.exception.YHSM_CommandFailed}.
@param hsm: The YHSM instance
@param from_key: The OTP from a YubiKey (in modhex)
@param aead: AEAD containing the cryptographic key and permission flags
@param key_handle: The key handle that can decrypt the AEAD
@type hsm: L{pyhsm.YHSM}
@type from_key: string
@type aead: L{YHSM_GeneratedAEAD} or string
@type key_handle: integer or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP.parse_result}
"""
from_key = pyhsm.util.input_validate_str(from_key, 'from_key', max_len = 48)
nonce = aead.nonce
aead = pyhsm.util.input_validate_aead(aead)
key_handle = pyhsm.util.input_validate_key_handle(key_handle)
public_id, otp = split_id_otp(from_key)
public_id = modhex_decode(public_id)
otp = modhex_decode(otp)
if not nonce:
nonce = public_id.decode('hex')
return hsm.validate_aead_otp(nonce, otp.decode('hex'),
key_handle, aead)
|
[
"def",
"validate_yubikey_with_aead",
"(",
"hsm",
",",
"from_key",
",",
"aead",
",",
"key_handle",
")",
":",
"from_key",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_str",
"(",
"from_key",
",",
"'from_key'",
",",
"max_len",
"=",
"48",
")",
"nonce",
"=",
"aead",
".",
"nonce",
"aead",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_aead",
"(",
"aead",
")",
"key_handle",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_key_handle",
"(",
"key_handle",
")",
"public_id",
",",
"otp",
"=",
"split_id_otp",
"(",
"from_key",
")",
"public_id",
"=",
"modhex_decode",
"(",
"public_id",
")",
"otp",
"=",
"modhex_decode",
"(",
"otp",
")",
"if",
"not",
"nonce",
":",
"nonce",
"=",
"public_id",
".",
"decode",
"(",
"'hex'",
")",
"return",
"hsm",
".",
"validate_aead_otp",
"(",
"nonce",
",",
"otp",
".",
"decode",
"(",
"'hex'",
")",
",",
"key_handle",
",",
"aead",
")"
] |
Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey's
internal secret, using the key_handle for the AEAD.
`from_key' is the modhex encoded string emitted when you press the
button on your YubiKey.
Will only return on succesfull validation. All failures will result
in an L{pyhsm.exception.YHSM_CommandFailed}.
@param hsm: The YHSM instance
@param from_key: The OTP from a YubiKey (in modhex)
@param aead: AEAD containing the cryptographic key and permission flags
@param key_handle: The key handle that can decrypt the AEAD
@type hsm: L{pyhsm.YHSM}
@type from_key: string
@type aead: L{YHSM_GeneratedAEAD} or string
@type key_handle: integer or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP.parse_result}
|
[
"Try",
"to",
"validate",
"an",
"OTP",
"from",
"a",
"YubiKey",
"using",
"the",
"AEAD",
"that",
"can",
"decrypt",
"this",
"YubiKey",
"s",
"internal",
"secret",
"using",
"the",
"key_handle",
"for",
"the",
"AEAD",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L50-L90
|
8,961
|
Yubico/python-pyhsm
|
pyhsm/yubikey.py
|
split_id_otp
|
def split_id_otp(from_key):
"""
Separate public id from OTP given a YubiKey OTP as input.
@param from_key: The OTP from a YubiKey (in modhex)
@type from_key: string
@returns: public_id and OTP
@rtype: tuple of string
"""
if len(from_key) > 32:
public_id, otp = from_key[:-32], from_key[-32:]
elif len(from_key) == 32:
public_id = ''
otp = from_key
else:
raise pyhsm.exception.YHSM_Error("Bad from_key length %i < 32 : %s" \
% (len(from_key), from_key))
return public_id, otp
|
python
|
def split_id_otp(from_key):
"""
Separate public id from OTP given a YubiKey OTP as input.
@param from_key: The OTP from a YubiKey (in modhex)
@type from_key: string
@returns: public_id and OTP
@rtype: tuple of string
"""
if len(from_key) > 32:
public_id, otp = from_key[:-32], from_key[-32:]
elif len(from_key) == 32:
public_id = ''
otp = from_key
else:
raise pyhsm.exception.YHSM_Error("Bad from_key length %i < 32 : %s" \
% (len(from_key), from_key))
return public_id, otp
|
[
"def",
"split_id_otp",
"(",
"from_key",
")",
":",
"if",
"len",
"(",
"from_key",
")",
">",
"32",
":",
"public_id",
",",
"otp",
"=",
"from_key",
"[",
":",
"-",
"32",
"]",
",",
"from_key",
"[",
"-",
"32",
":",
"]",
"elif",
"len",
"(",
"from_key",
")",
"==",
"32",
":",
"public_id",
"=",
"''",
"otp",
"=",
"from_key",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"\"Bad from_key length %i < 32 : %s\"",
"%",
"(",
"len",
"(",
"from_key",
")",
",",
"from_key",
")",
")",
"return",
"public_id",
",",
"otp"
] |
Separate public id from OTP given a YubiKey OTP as input.
@param from_key: The OTP from a YubiKey (in modhex)
@type from_key: string
@returns: public_id and OTP
@rtype: tuple of string
|
[
"Separate",
"public",
"id",
"from",
"OTP",
"given",
"a",
"YubiKey",
"OTP",
"as",
"input",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L118-L136
|
8,962
|
Yubico/python-pyhsm
|
pyhsm/tools/keystore_unlock.py
|
get_password
|
def get_password(hsm, args):
""" Get password of correct length for this YubiHSM version. """
expected_len = 32
name = 'HSM password'
if hsm.version.have_key_store_decrypt():
expected_len = 64
name = 'master key'
if args.stdin:
password = sys.stdin.readline()
while password and password[-1] == '\n':
password = password[:-1]
else:
if args.debug:
password = raw_input('Enter %s (press enter to skip) (will be echoed) : ' % (name))
else:
password = getpass.getpass('Enter %s (press enter to skip) : ' % (name))
if len(password) <= expected_len:
password = password.decode('hex')
if not password:
return None
return password
else:
sys.stderr.write("ERROR: Invalid HSM password (expected max %i chars, got %i)\n" % \
(expected_len, len(password)))
return 1
|
python
|
def get_password(hsm, args):
""" Get password of correct length for this YubiHSM version. """
expected_len = 32
name = 'HSM password'
if hsm.version.have_key_store_decrypt():
expected_len = 64
name = 'master key'
if args.stdin:
password = sys.stdin.readline()
while password and password[-1] == '\n':
password = password[:-1]
else:
if args.debug:
password = raw_input('Enter %s (press enter to skip) (will be echoed) : ' % (name))
else:
password = getpass.getpass('Enter %s (press enter to skip) : ' % (name))
if len(password) <= expected_len:
password = password.decode('hex')
if not password:
return None
return password
else:
sys.stderr.write("ERROR: Invalid HSM password (expected max %i chars, got %i)\n" % \
(expected_len, len(password)))
return 1
|
[
"def",
"get_password",
"(",
"hsm",
",",
"args",
")",
":",
"expected_len",
"=",
"32",
"name",
"=",
"'HSM password'",
"if",
"hsm",
".",
"version",
".",
"have_key_store_decrypt",
"(",
")",
":",
"expected_len",
"=",
"64",
"name",
"=",
"'master key'",
"if",
"args",
".",
"stdin",
":",
"password",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
"while",
"password",
"and",
"password",
"[",
"-",
"1",
"]",
"==",
"'\\n'",
":",
"password",
"=",
"password",
"[",
":",
"-",
"1",
"]",
"else",
":",
"if",
"args",
".",
"debug",
":",
"password",
"=",
"raw_input",
"(",
"'Enter %s (press enter to skip) (will be echoed) : '",
"%",
"(",
"name",
")",
")",
"else",
":",
"password",
"=",
"getpass",
".",
"getpass",
"(",
"'Enter %s (press enter to skip) : '",
"%",
"(",
"name",
")",
")",
"if",
"len",
"(",
"password",
")",
"<=",
"expected_len",
":",
"password",
"=",
"password",
".",
"decode",
"(",
"'hex'",
")",
"if",
"not",
"password",
":",
"return",
"None",
"return",
"password",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: Invalid HSM password (expected max %i chars, got %i)\\n\"",
"%",
"(",
"expected_len",
",",
"len",
"(",
"password",
")",
")",
")",
"return",
"1"
] |
Get password of correct length for this YubiHSM version.
|
[
"Get",
"password",
"of",
"correct",
"length",
"for",
"this",
"YubiHSM",
"version",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/keystore_unlock.py#L56-L82
|
8,963
|
Yubico/python-pyhsm
|
pyhsm/tools/keystore_unlock.py
|
get_otp
|
def get_otp(hsm, args):
""" Get OTP from YubiKey. """
if args.no_otp:
return None
if hsm.version.have_unlock():
if args.stdin:
otp = sys.stdin.readline()
while otp and otp[-1] == '\n':
otp = otp[:-1]
else:
otp = raw_input('Enter admin YubiKey OTP (press enter to skip) : ')
if len(otp) == 44:
# YubiHSM admin OTP's always have a public_id length of 6 bytes
return otp
if otp:
sys.stderr.write("ERROR: Invalid YubiKey OTP\n")
return None
|
python
|
def get_otp(hsm, args):
""" Get OTP from YubiKey. """
if args.no_otp:
return None
if hsm.version.have_unlock():
if args.stdin:
otp = sys.stdin.readline()
while otp and otp[-1] == '\n':
otp = otp[:-1]
else:
otp = raw_input('Enter admin YubiKey OTP (press enter to skip) : ')
if len(otp) == 44:
# YubiHSM admin OTP's always have a public_id length of 6 bytes
return otp
if otp:
sys.stderr.write("ERROR: Invalid YubiKey OTP\n")
return None
|
[
"def",
"get_otp",
"(",
"hsm",
",",
"args",
")",
":",
"if",
"args",
".",
"no_otp",
":",
"return",
"None",
"if",
"hsm",
".",
"version",
".",
"have_unlock",
"(",
")",
":",
"if",
"args",
".",
"stdin",
":",
"otp",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
"while",
"otp",
"and",
"otp",
"[",
"-",
"1",
"]",
"==",
"'\\n'",
":",
"otp",
"=",
"otp",
"[",
":",
"-",
"1",
"]",
"else",
":",
"otp",
"=",
"raw_input",
"(",
"'Enter admin YubiKey OTP (press enter to skip) : '",
")",
"if",
"len",
"(",
"otp",
")",
"==",
"44",
":",
"# YubiHSM admin OTP's always have a public_id length of 6 bytes",
"return",
"otp",
"if",
"otp",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: Invalid YubiKey OTP\\n\"",
")",
"return",
"None"
] |
Get OTP from YubiKey.
|
[
"Get",
"OTP",
"from",
"YubiKey",
"."
] |
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
|
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/keystore_unlock.py#L84-L100
|
8,964
|
ResidentMario/geoplot
|
geoplot/crs.py
|
Base.load
|
def load(self, df, centerings):
"""
A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures.
Parameters
----------
proj : geoplot.crs object instance
A disguised reference to ``self``.
df : GeoDataFrame
The GeoDataFrame which has been passed as input to the plotter at the top level. This data is needed to
calculate reasonable centering variables in cases in which the user does not already provide them; which is,
incidentally, the reason behind all of this funny twice-instantiation loading in the first place.
centerings: dct
A dictionary containing names and centering methods. Certain projections have certain centering parameters
whilst others lack them. For example, the geospatial projection contains both ``central_longitude`` and
``central_latitude`` instance parameter, which together control the center of the plot, while the North Pole
Stereo projection has only a ``central_longitude`` instance parameter, implying that latitude is fixed (as
indeed it is, as this projection is centered on the North Pole!).
A top-level centerings method is provided in each of the ``geoplot`` top-level plot functions; each of the
projection wrapper classes defined here in turn selects the functions from this list relevent to this
particular instance and passes them to the ``_generic_load`` method here.
We then in turn execute these functions to get defaults for our ``df`` and pass them off to our output
``cartopy.crs`` instance.
Returns
-------
crs : ``cartopy.crs`` object instance
Returns a ``cartopy.crs`` object instance whose appropriate instance variables have been set to reasonable
defaults wherever not already provided by the user.
"""
centering_variables = dict()
if not df.empty and df.geometry.notna().any():
for key, func in centerings.items():
centering_variables[key] = func(df)
return getattr(ccrs, self.__class__.__name__)(**{**centering_variables, **self.args})
|
python
|
def load(self, df, centerings):
"""
A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures.
Parameters
----------
proj : geoplot.crs object instance
A disguised reference to ``self``.
df : GeoDataFrame
The GeoDataFrame which has been passed as input to the plotter at the top level. This data is needed to
calculate reasonable centering variables in cases in which the user does not already provide them; which is,
incidentally, the reason behind all of this funny twice-instantiation loading in the first place.
centerings: dct
A dictionary containing names and centering methods. Certain projections have certain centering parameters
whilst others lack them. For example, the geospatial projection contains both ``central_longitude`` and
``central_latitude`` instance parameter, which together control the center of the plot, while the North Pole
Stereo projection has only a ``central_longitude`` instance parameter, implying that latitude is fixed (as
indeed it is, as this projection is centered on the North Pole!).
A top-level centerings method is provided in each of the ``geoplot`` top-level plot functions; each of the
projection wrapper classes defined here in turn selects the functions from this list relevent to this
particular instance and passes them to the ``_generic_load`` method here.
We then in turn execute these functions to get defaults for our ``df`` and pass them off to our output
``cartopy.crs`` instance.
Returns
-------
crs : ``cartopy.crs`` object instance
Returns a ``cartopy.crs`` object instance whose appropriate instance variables have been set to reasonable
defaults wherever not already provided by the user.
"""
centering_variables = dict()
if not df.empty and df.geometry.notna().any():
for key, func in centerings.items():
centering_variables[key] = func(df)
return getattr(ccrs, self.__class__.__name__)(**{**centering_variables, **self.args})
|
[
"def",
"load",
"(",
"self",
",",
"df",
",",
"centerings",
")",
":",
"centering_variables",
"=",
"dict",
"(",
")",
"if",
"not",
"df",
".",
"empty",
"and",
"df",
".",
"geometry",
".",
"notna",
"(",
")",
".",
"any",
"(",
")",
":",
"for",
"key",
",",
"func",
"in",
"centerings",
".",
"items",
"(",
")",
":",
"centering_variables",
"[",
"key",
"]",
"=",
"func",
"(",
"df",
")",
"return",
"getattr",
"(",
"ccrs",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"(",
"*",
"*",
"{",
"*",
"*",
"centering_variables",
",",
"*",
"*",
"self",
".",
"args",
"}",
")"
] |
A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures.
Parameters
----------
proj : geoplot.crs object instance
A disguised reference to ``self``.
df : GeoDataFrame
The GeoDataFrame which has been passed as input to the plotter at the top level. This data is needed to
calculate reasonable centering variables in cases in which the user does not already provide them; which is,
incidentally, the reason behind all of this funny twice-instantiation loading in the first place.
centerings: dct
A dictionary containing names and centering methods. Certain projections have certain centering parameters
whilst others lack them. For example, the geospatial projection contains both ``central_longitude`` and
``central_latitude`` instance parameter, which together control the center of the plot, while the North Pole
Stereo projection has only a ``central_longitude`` instance parameter, implying that latitude is fixed (as
indeed it is, as this projection is centered on the North Pole!).
A top-level centerings method is provided in each of the ``geoplot`` top-level plot functions; each of the
projection wrapper classes defined here in turn selects the functions from this list relevent to this
particular instance and passes them to the ``_generic_load`` method here.
We then in turn execute these functions to get defaults for our ``df`` and pass them off to our output
``cartopy.crs`` instance.
Returns
-------
crs : ``cartopy.crs`` object instance
Returns a ``cartopy.crs`` object instance whose appropriate instance variables have been set to reasonable
defaults wherever not already provided by the user.
|
[
"A",
"moderately",
"mind",
"-",
"bendy",
"meta",
"-",
"method",
"which",
"abstracts",
"the",
"internals",
"of",
"individual",
"projections",
"load",
"procedures",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/crs.py#L26-L62
|
8,965
|
ResidentMario/geoplot
|
geoplot/crs.py
|
Filtering.load
|
def load(self, df, centerings):
"""Call `load` method with `centerings` filtered to keys in `self.filter_`."""
return super().load(
df,
{key: value
for key, value in centerings.items()
if key in self.filter_}
)
|
python
|
def load(self, df, centerings):
"""Call `load` method with `centerings` filtered to keys in `self.filter_`."""
return super().load(
df,
{key: value
for key, value in centerings.items()
if key in self.filter_}
)
|
[
"def",
"load",
"(",
"self",
",",
"df",
",",
"centerings",
")",
":",
"return",
"super",
"(",
")",
".",
"load",
"(",
"df",
",",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"centerings",
".",
"items",
"(",
")",
"if",
"key",
"in",
"self",
".",
"filter_",
"}",
")"
] |
Call `load` method with `centerings` filtered to keys in `self.filter_`.
|
[
"Call",
"load",
"method",
"with",
"centerings",
"filtered",
"to",
"keys",
"in",
"self",
".",
"filter_",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/crs.py#L99-L106
|
8,966
|
ResidentMario/geoplot
|
geoplot/utils.py
|
gaussian_points
|
def gaussian_points(loc=(0, 0), scale=(10, 10), n=100):
"""
Generates and returns `n` normally distributed points centered at `loc` with `scale` x and y directionality.
"""
arr = np.random.normal(loc, scale, (n, 2))
return gpd.GeoSeries([shapely.geometry.Point(x, y) for (x, y) in arr])
|
python
|
def gaussian_points(loc=(0, 0), scale=(10, 10), n=100):
"""
Generates and returns `n` normally distributed points centered at `loc` with `scale` x and y directionality.
"""
arr = np.random.normal(loc, scale, (n, 2))
return gpd.GeoSeries([shapely.geometry.Point(x, y) for (x, y) in arr])
|
[
"def",
"gaussian_points",
"(",
"loc",
"=",
"(",
"0",
",",
"0",
")",
",",
"scale",
"=",
"(",
"10",
",",
"10",
")",
",",
"n",
"=",
"100",
")",
":",
"arr",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"loc",
",",
"scale",
",",
"(",
"n",
",",
"2",
")",
")",
"return",
"gpd",
".",
"GeoSeries",
"(",
"[",
"shapely",
".",
"geometry",
".",
"Point",
"(",
"x",
",",
"y",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"arr",
"]",
")"
] |
Generates and returns `n` normally distributed points centered at `loc` with `scale` x and y directionality.
|
[
"Generates",
"and",
"returns",
"n",
"normally",
"distributed",
"points",
"centered",
"at",
"loc",
"with",
"scale",
"x",
"and",
"y",
"directionality",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L14-L20
|
8,967
|
ResidentMario/geoplot
|
geoplot/utils.py
|
classify_clusters
|
def classify_clusters(points, n=10):
"""
Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.
"""
arr = [[p.x, p.y] for p in points.values]
clf = KMeans(n_clusters=n)
clf.fit(arr)
classes = clf.predict(arr)
return classes
|
python
|
def classify_clusters(points, n=10):
"""
Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.
"""
arr = [[p.x, p.y] for p in points.values]
clf = KMeans(n_clusters=n)
clf.fit(arr)
classes = clf.predict(arr)
return classes
|
[
"def",
"classify_clusters",
"(",
"points",
",",
"n",
"=",
"10",
")",
":",
"arr",
"=",
"[",
"[",
"p",
".",
"x",
",",
"p",
".",
"y",
"]",
"for",
"p",
"in",
"points",
".",
"values",
"]",
"clf",
"=",
"KMeans",
"(",
"n_clusters",
"=",
"n",
")",
"clf",
".",
"fit",
"(",
"arr",
")",
"classes",
"=",
"clf",
".",
"predict",
"(",
"arr",
")",
"return",
"classes"
] |
Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.
|
[
"Return",
"an",
"array",
"of",
"K",
"-",
"Means",
"cluster",
"classes",
"for",
"an",
"array",
"of",
"shapely",
".",
"geometry",
".",
"Point",
"objects",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L23-L31
|
8,968
|
ResidentMario/geoplot
|
geoplot/utils.py
|
gaussian_polygons
|
def gaussian_polygons(points, n=10):
"""
Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point`
objects.
"""
gdf = gpd.GeoDataFrame(data={'cluster_number': classify_clusters(points, n=n)}, geometry=points)
polygons = []
for i in range(n):
sel_points = gdf[gdf['cluster_number'] == i].geometry
polygons.append(shapely.geometry.MultiPoint([(p.x, p.y) for p in sel_points]).convex_hull)
polygons = [p for p in polygons if
(not isinstance(p, shapely.geometry.Point)) and (not isinstance(p, shapely.geometry.LineString))]
return gpd.GeoSeries(polygons)
|
python
|
def gaussian_polygons(points, n=10):
"""
Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point`
objects.
"""
gdf = gpd.GeoDataFrame(data={'cluster_number': classify_clusters(points, n=n)}, geometry=points)
polygons = []
for i in range(n):
sel_points = gdf[gdf['cluster_number'] == i].geometry
polygons.append(shapely.geometry.MultiPoint([(p.x, p.y) for p in sel_points]).convex_hull)
polygons = [p for p in polygons if
(not isinstance(p, shapely.geometry.Point)) and (not isinstance(p, shapely.geometry.LineString))]
return gpd.GeoSeries(polygons)
|
[
"def",
"gaussian_polygons",
"(",
"points",
",",
"n",
"=",
"10",
")",
":",
"gdf",
"=",
"gpd",
".",
"GeoDataFrame",
"(",
"data",
"=",
"{",
"'cluster_number'",
":",
"classify_clusters",
"(",
"points",
",",
"n",
"=",
"n",
")",
"}",
",",
"geometry",
"=",
"points",
")",
"polygons",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"sel_points",
"=",
"gdf",
"[",
"gdf",
"[",
"'cluster_number'",
"]",
"==",
"i",
"]",
".",
"geometry",
"polygons",
".",
"append",
"(",
"shapely",
".",
"geometry",
".",
"MultiPoint",
"(",
"[",
"(",
"p",
".",
"x",
",",
"p",
".",
"y",
")",
"for",
"p",
"in",
"sel_points",
"]",
")",
".",
"convex_hull",
")",
"polygons",
"=",
"[",
"p",
"for",
"p",
"in",
"polygons",
"if",
"(",
"not",
"isinstance",
"(",
"p",
",",
"shapely",
".",
"geometry",
".",
"Point",
")",
")",
"and",
"(",
"not",
"isinstance",
"(",
"p",
",",
"shapely",
".",
"geometry",
".",
"LineString",
")",
")",
"]",
"return",
"gpd",
".",
"GeoSeries",
"(",
"polygons",
")"
] |
Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point`
objects.
|
[
"Returns",
"an",
"array",
"of",
"approximately",
"n",
"shapely",
".",
"geometry",
".",
"Polygon",
"objects",
"for",
"an",
"array",
"of",
"shapely",
".",
"geometry",
".",
"Point",
"objects",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L34-L46
|
8,969
|
ResidentMario/geoplot
|
geoplot/utils.py
|
gaussian_multi_polygons
|
def gaussian_multi_polygons(points, n=10):
"""
Returns an array of approximately `n` `shapely.geometry.MultiPolygon` objects for an array of
`shapely.geometry.Point` objects.
"""
polygons = gaussian_polygons(points, n*2)
# Randomly stitch them together.
polygon_pairs = [shapely.geometry.MultiPolygon(list(pair)) for pair in np.array_split(polygons.values, n)]
return gpd.GeoSeries(polygon_pairs)
|
python
|
def gaussian_multi_polygons(points, n=10):
"""
Returns an array of approximately `n` `shapely.geometry.MultiPolygon` objects for an array of
`shapely.geometry.Point` objects.
"""
polygons = gaussian_polygons(points, n*2)
# Randomly stitch them together.
polygon_pairs = [shapely.geometry.MultiPolygon(list(pair)) for pair in np.array_split(polygons.values, n)]
return gpd.GeoSeries(polygon_pairs)
|
[
"def",
"gaussian_multi_polygons",
"(",
"points",
",",
"n",
"=",
"10",
")",
":",
"polygons",
"=",
"gaussian_polygons",
"(",
"points",
",",
"n",
"*",
"2",
")",
"# Randomly stitch them together.",
"polygon_pairs",
"=",
"[",
"shapely",
".",
"geometry",
".",
"MultiPolygon",
"(",
"list",
"(",
"pair",
")",
")",
"for",
"pair",
"in",
"np",
".",
"array_split",
"(",
"polygons",
".",
"values",
",",
"n",
")",
"]",
"return",
"gpd",
".",
"GeoSeries",
"(",
"polygon_pairs",
")"
] |
Returns an array of approximately `n` `shapely.geometry.MultiPolygon` objects for an array of
`shapely.geometry.Point` objects.
|
[
"Returns",
"an",
"array",
"of",
"approximately",
"n",
"shapely",
".",
"geometry",
".",
"MultiPolygon",
"objects",
"for",
"an",
"array",
"of",
"shapely",
".",
"geometry",
".",
"Point",
"objects",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L49-L57
|
8,970
|
ResidentMario/geoplot
|
geoplot/utils.py
|
uniform_random_global_points
|
def uniform_random_global_points(n=100):
"""
Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates
distributed equivalently across the Earth's surface.
"""
xs = np.random.uniform(-180, 180, n)
ys = np.random.uniform(-90, 90, n)
return [shapely.geometry.Point(x, y) for x, y in zip(xs, ys)]
|
python
|
def uniform_random_global_points(n=100):
"""
Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates
distributed equivalently across the Earth's surface.
"""
xs = np.random.uniform(-180, 180, n)
ys = np.random.uniform(-90, 90, n)
return [shapely.geometry.Point(x, y) for x, y in zip(xs, ys)]
|
[
"def",
"uniform_random_global_points",
"(",
"n",
"=",
"100",
")",
":",
"xs",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"180",
",",
"180",
",",
"n",
")",
"ys",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"90",
",",
"90",
",",
"n",
")",
"return",
"[",
"shapely",
".",
"geometry",
".",
"Point",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"xs",
",",
"ys",
")",
"]"
] |
Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates
distributed equivalently across the Earth's surface.
|
[
"Returns",
"an",
"array",
"of",
"n",
"uniformally",
"distributed",
"shapely",
".",
"geometry",
".",
"Point",
"objects",
".",
"Points",
"are",
"coordinates",
"distributed",
"equivalently",
"across",
"the",
"Earth",
"s",
"surface",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L60-L67
|
8,971
|
ResidentMario/geoplot
|
geoplot/utils.py
|
uniform_random_global_network
|
def uniform_random_global_network(loc=2000, scale=250, n=100):
"""
Returns an array of `n` uniformally randomly distributed `shapely.geometry.Point` objects.
"""
arr = (np.random.normal(loc, scale, n)).astype(int)
return pd.DataFrame(data={'mock_variable': arr,
'from': uniform_random_global_points(n),
'to': uniform_random_global_points(n)})
|
python
|
def uniform_random_global_network(loc=2000, scale=250, n=100):
"""
Returns an array of `n` uniformally randomly distributed `shapely.geometry.Point` objects.
"""
arr = (np.random.normal(loc, scale, n)).astype(int)
return pd.DataFrame(data={'mock_variable': arr,
'from': uniform_random_global_points(n),
'to': uniform_random_global_points(n)})
|
[
"def",
"uniform_random_global_network",
"(",
"loc",
"=",
"2000",
",",
"scale",
"=",
"250",
",",
"n",
"=",
"100",
")",
":",
"arr",
"=",
"(",
"np",
".",
"random",
".",
"normal",
"(",
"loc",
",",
"scale",
",",
"n",
")",
")",
".",
"astype",
"(",
"int",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"data",
"=",
"{",
"'mock_variable'",
":",
"arr",
",",
"'from'",
":",
"uniform_random_global_points",
"(",
"n",
")",
",",
"'to'",
":",
"uniform_random_global_points",
"(",
"n",
")",
"}",
")"
] |
Returns an array of `n` uniformally randomly distributed `shapely.geometry.Point` objects.
|
[
"Returns",
"an",
"array",
"of",
"n",
"uniformally",
"randomly",
"distributed",
"shapely",
".",
"geometry",
".",
"Point",
"objects",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L70-L77
|
8,972
|
ResidentMario/geoplot
|
geoplot/quad.py
|
subpartition
|
def subpartition(quadtree, nmin, nmax):
"""
Recursive core of the ``QuadTree.partition`` method. Just five lines of code, amazingly.
Parameters
----------
quadtree : QuadTree object instance
The QuadTree object instance being partitioned.
nmin : int
The splitting threshold. If this is not met this method will return a listing containing the root tree alone.
Returns
-------
A (probably nested) list of QuadTree object instances containing a number of points respecting the threshold
parameter.
"""
subtrees = quadtree.split()
if quadtree.n > nmax:
return [q.partition(nmin, nmax) for q in subtrees]
elif any([t.n < nmin for t in subtrees]):
return [quadtree]
else:
return [q.partition(nmin, nmax) for q in subtrees]
|
python
|
def subpartition(quadtree, nmin, nmax):
"""
Recursive core of the ``QuadTree.partition`` method. Just five lines of code, amazingly.
Parameters
----------
quadtree : QuadTree object instance
The QuadTree object instance being partitioned.
nmin : int
The splitting threshold. If this is not met this method will return a listing containing the root tree alone.
Returns
-------
A (probably nested) list of QuadTree object instances containing a number of points respecting the threshold
parameter.
"""
subtrees = quadtree.split()
if quadtree.n > nmax:
return [q.partition(nmin, nmax) for q in subtrees]
elif any([t.n < nmin for t in subtrees]):
return [quadtree]
else:
return [q.partition(nmin, nmax) for q in subtrees]
|
[
"def",
"subpartition",
"(",
"quadtree",
",",
"nmin",
",",
"nmax",
")",
":",
"subtrees",
"=",
"quadtree",
".",
"split",
"(",
")",
"if",
"quadtree",
".",
"n",
">",
"nmax",
":",
"return",
"[",
"q",
".",
"partition",
"(",
"nmin",
",",
"nmax",
")",
"for",
"q",
"in",
"subtrees",
"]",
"elif",
"any",
"(",
"[",
"t",
".",
"n",
"<",
"nmin",
"for",
"t",
"in",
"subtrees",
"]",
")",
":",
"return",
"[",
"quadtree",
"]",
"else",
":",
"return",
"[",
"q",
".",
"partition",
"(",
"nmin",
",",
"nmax",
")",
"for",
"q",
"in",
"subtrees",
"]"
] |
Recursive core of the ``QuadTree.partition`` method. Just five lines of code, amazingly.
Parameters
----------
quadtree : QuadTree object instance
The QuadTree object instance being partitioned.
nmin : int
The splitting threshold. If this is not met this method will return a listing containing the root tree alone.
Returns
-------
A (probably nested) list of QuadTree object instances containing a number of points respecting the threshold
parameter.
|
[
"Recursive",
"core",
"of",
"the",
"QuadTree",
".",
"partition",
"method",
".",
"Just",
"five",
"lines",
"of",
"code",
"amazingly",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/quad.py#L116-L138
|
8,973
|
ResidentMario/geoplot
|
geoplot/quad.py
|
QuadTree.split
|
def split(self):
"""
Splits the current QuadTree instance four ways through the midpoint.
Returns
-------
A list of four "sub" QuadTree instances, corresponding with the first, second, third, and fourth quartiles,
respectively.
"""
# TODO: Investigate why a small number of entries are lost every time this method is run.
min_x, max_x, min_y, max_y = self.bounds
mid_x, mid_y = (min_x + max_x) / 2, (min_y + max_y) / 2
q1 = (min_x, mid_x, mid_y, max_y)
q2 = (min_x, mid_x, min_y, mid_y)
q3 = (mid_x, max_x, mid_y, max_y)
q4 = (mid_x, max_x, min_y, mid_y)
return [QuadTree(self.data, bounds=q1), QuadTree(self.data, bounds=q2), QuadTree(self.data, bounds=q3),
QuadTree(self.data, bounds=q4)]
|
python
|
def split(self):
"""
Splits the current QuadTree instance four ways through the midpoint.
Returns
-------
A list of four "sub" QuadTree instances, corresponding with the first, second, third, and fourth quartiles,
respectively.
"""
# TODO: Investigate why a small number of entries are lost every time this method is run.
min_x, max_x, min_y, max_y = self.bounds
mid_x, mid_y = (min_x + max_x) / 2, (min_y + max_y) / 2
q1 = (min_x, mid_x, mid_y, max_y)
q2 = (min_x, mid_x, min_y, mid_y)
q3 = (mid_x, max_x, mid_y, max_y)
q4 = (mid_x, max_x, min_y, mid_y)
return [QuadTree(self.data, bounds=q1), QuadTree(self.data, bounds=q2), QuadTree(self.data, bounds=q3),
QuadTree(self.data, bounds=q4)]
|
[
"def",
"split",
"(",
"self",
")",
":",
"# TODO: Investigate why a small number of entries are lost every time this method is run.",
"min_x",
",",
"max_x",
",",
"min_y",
",",
"max_y",
"=",
"self",
".",
"bounds",
"mid_x",
",",
"mid_y",
"=",
"(",
"min_x",
"+",
"max_x",
")",
"/",
"2",
",",
"(",
"min_y",
"+",
"max_y",
")",
"/",
"2",
"q1",
"=",
"(",
"min_x",
",",
"mid_x",
",",
"mid_y",
",",
"max_y",
")",
"q2",
"=",
"(",
"min_x",
",",
"mid_x",
",",
"min_y",
",",
"mid_y",
")",
"q3",
"=",
"(",
"mid_x",
",",
"max_x",
",",
"mid_y",
",",
"max_y",
")",
"q4",
"=",
"(",
"mid_x",
",",
"max_x",
",",
"min_y",
",",
"mid_y",
")",
"return",
"[",
"QuadTree",
"(",
"self",
".",
"data",
",",
"bounds",
"=",
"q1",
")",
",",
"QuadTree",
"(",
"self",
".",
"data",
",",
"bounds",
"=",
"q2",
")",
",",
"QuadTree",
"(",
"self",
".",
"data",
",",
"bounds",
"=",
"q3",
")",
",",
"QuadTree",
"(",
"self",
".",
"data",
",",
"bounds",
"=",
"q4",
")",
"]"
] |
Splits the current QuadTree instance four ways through the midpoint.
Returns
-------
A list of four "sub" QuadTree instances, corresponding with the first, second, third, and fourth quartiles,
respectively.
|
[
"Splits",
"the",
"current",
"QuadTree",
"instance",
"four",
"ways",
"through",
"the",
"midpoint",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/quad.py#L71-L88
|
8,974
|
ResidentMario/geoplot
|
geoplot/quad.py
|
QuadTree.partition
|
def partition(self, nmin, nmax):
"""
This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the
smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh``
points.
Parameters
----------
thresh : int
The minimum number of points per partition. Care should be taken not to set this parameter to be too
low, as in large datasets a small cluster of highly adjacent points may result in a number of
sub-recursive splits possibly in excess of Python's global recursion limit.
Returns
-------
partitions : list of QuadTree object instances
A list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current
splitting rules, containing at least ``thresh`` points.
"""
if self.n < nmin:
return [self]
else:
ret = subpartition(self, nmin, nmax)
return flatten(ret)
|
python
|
def partition(self, nmin, nmax):
"""
This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the
smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh``
points.
Parameters
----------
thresh : int
The minimum number of points per partition. Care should be taken not to set this parameter to be too
low, as in large datasets a small cluster of highly adjacent points may result in a number of
sub-recursive splits possibly in excess of Python's global recursion limit.
Returns
-------
partitions : list of QuadTree object instances
A list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current
splitting rules, containing at least ``thresh`` points.
"""
if self.n < nmin:
return [self]
else:
ret = subpartition(self, nmin, nmax)
return flatten(ret)
|
[
"def",
"partition",
"(",
"self",
",",
"nmin",
",",
"nmax",
")",
":",
"if",
"self",
".",
"n",
"<",
"nmin",
":",
"return",
"[",
"self",
"]",
"else",
":",
"ret",
"=",
"subpartition",
"(",
"self",
",",
"nmin",
",",
"nmax",
")",
"return",
"flatten",
"(",
"ret",
")"
] |
This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the
smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh``
points.
Parameters
----------
thresh : int
The minimum number of points per partition. Care should be taken not to set this parameter to be too
low, as in large datasets a small cluster of highly adjacent points may result in a number of
sub-recursive splits possibly in excess of Python's global recursion limit.
Returns
-------
partitions : list of QuadTree object instances
A list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current
splitting rules, containing at least ``thresh`` points.
|
[
"This",
"method",
"call",
"decomposes",
"a",
"QuadTree",
"instances",
"into",
"a",
"list",
"of",
"sub",
"-",
"QuadTree",
"instances",
"which",
"are",
"the",
"smallest",
"possible",
"geospatial",
"buckets",
"given",
"the",
"current",
"splitting",
"rules",
"containing",
"at",
"least",
"thresh",
"points",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/quad.py#L90-L113
|
8,975
|
ResidentMario/geoplot
|
docs/examples/nyc-parking-tickets.py
|
plot_state_to_ax
|
def plot_state_to_ax(state, ax):
"""Reusable plotting wrapper."""
gplt.choropleth(tickets.set_index('id').loc[:, [state, 'geometry']],
hue=state,
projection=gcrs.AlbersEqualArea(), cmap='Blues',
linewidth=0.0, ax=ax)
gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), edgecolor='black', linewidth=0.5, ax=ax)
|
python
|
def plot_state_to_ax(state, ax):
"""Reusable plotting wrapper."""
gplt.choropleth(tickets.set_index('id').loc[:, [state, 'geometry']],
hue=state,
projection=gcrs.AlbersEqualArea(), cmap='Blues',
linewidth=0.0, ax=ax)
gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), edgecolor='black', linewidth=0.5, ax=ax)
|
[
"def",
"plot_state_to_ax",
"(",
"state",
",",
"ax",
")",
":",
"gplt",
".",
"choropleth",
"(",
"tickets",
".",
"set_index",
"(",
"'id'",
")",
".",
"loc",
"[",
":",
",",
"[",
"state",
",",
"'geometry'",
"]",
"]",
",",
"hue",
"=",
"state",
",",
"projection",
"=",
"gcrs",
".",
"AlbersEqualArea",
"(",
")",
",",
"cmap",
"=",
"'Blues'",
",",
"linewidth",
"=",
"0.0",
",",
"ax",
"=",
"ax",
")",
"gplt",
".",
"polyplot",
"(",
"boroughs",
",",
"projection",
"=",
"gcrs",
".",
"AlbersEqualArea",
"(",
")",
",",
"edgecolor",
"=",
"'black'",
",",
"linewidth",
"=",
"0.5",
",",
"ax",
"=",
"ax",
")"
] |
Reusable plotting wrapper.
|
[
"Reusable",
"plotting",
"wrapper",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/docs/examples/nyc-parking-tickets.py#L19-L25
|
8,976
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
polyplot
|
def polyplot(df, projection=None,
extent=None,
figsize=(8, 6), ax=None,
edgecolor='black',
facecolor='None', **kwargs):
"""
Trivial polygonal plot.
Parameters
----------
df : GeoDataFrame
The data being plotted.
projection : geoplot.crs object instance, optional
A geographic projection. For more information refer to `the tutorial page on projections
<https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
extent : None or (minx, maxx, miny, maxy), optional
Used to control plot x-axis and y-axis limits manually.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
Defaults to (8, 6), the ``matplotlib`` default global.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
ax : AxesSubplot or GeoAxesSubplot instance, optional
A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
kwargs: dict, optional
Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
Returns
-------
``AxesSubplot`` or ``GeoAxesSubplot``
The plot axis
Examples
--------
The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a
geometry and, optionally, a projection.
.. code-block:: python
import geoplot as gplt
import geoplot.crs as gcrs
gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
.. image:: ../figures/polyplot/polyplot-initial.png
However, note that ``polyplot`` is mainly intended to be used in concert with other plot types.
.. code-block:: python
ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(),
hue='BOROUGH', categorical=True,
legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
ax=ax)
.. image:: ../figures/polyplot/polyplot-stacked.png
Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
.. code-block:: python
ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(),
linewidth=0, facecolor='lightgray')
.. image:: ../figures/polyplot/polyplot-kwargs.png
"""
# Initialize the figure.
fig = _init_figure(ax, figsize)
if projection:
# Properly set up the projection.
projection = projection.load(df, {
'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])),
'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid]))
})
# Set up the axis.
if not ax:
ax = plt.subplot(111, projection=projection)
else:
if not ax:
ax = plt.gca()
# Clean up patches.
_lay_out_axes(ax, projection)
# Immediately return if input geometry is empty.
if len(df.geometry) == 0:
return ax
# Set extent.
extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior)
_set_extent(ax, projection, extent, extrema)
# Finally we draw the features.
if projection:
for geom in df.geometry:
features = ShapelyFeature([geom], ccrs.PlateCarree())
ax.add_feature(features, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
else:
for geom in df.geometry:
try: # Duck test for MultiPolygon.
for subgeom in geom:
feature = descartes.PolygonPatch(subgeom, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
ax.add_patch(feature)
except (TypeError, AssertionError): # Shapely Polygon.
feature = descartes.PolygonPatch(geom, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
ax.add_patch(feature)
return ax
|
python
|
def polyplot(df, projection=None,
extent=None,
figsize=(8, 6), ax=None,
edgecolor='black',
facecolor='None', **kwargs):
"""
Trivial polygonal plot.
Parameters
----------
df : GeoDataFrame
The data being plotted.
projection : geoplot.crs object instance, optional
A geographic projection. For more information refer to `the tutorial page on projections
<https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
extent : None or (minx, maxx, miny, maxy), optional
Used to control plot x-axis and y-axis limits manually.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
Defaults to (8, 6), the ``matplotlib`` default global.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
ax : AxesSubplot or GeoAxesSubplot instance, optional
A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
kwargs: dict, optional
Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
Returns
-------
``AxesSubplot`` or ``GeoAxesSubplot``
The plot axis
Examples
--------
The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a
geometry and, optionally, a projection.
.. code-block:: python
import geoplot as gplt
import geoplot.crs as gcrs
gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
.. image:: ../figures/polyplot/polyplot-initial.png
However, note that ``polyplot`` is mainly intended to be used in concert with other plot types.
.. code-block:: python
ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(),
hue='BOROUGH', categorical=True,
legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
ax=ax)
.. image:: ../figures/polyplot/polyplot-stacked.png
Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
.. code-block:: python
ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(),
linewidth=0, facecolor='lightgray')
.. image:: ../figures/polyplot/polyplot-kwargs.png
"""
# Initialize the figure.
fig = _init_figure(ax, figsize)
if projection:
# Properly set up the projection.
projection = projection.load(df, {
'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])),
'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid]))
})
# Set up the axis.
if not ax:
ax = plt.subplot(111, projection=projection)
else:
if not ax:
ax = plt.gca()
# Clean up patches.
_lay_out_axes(ax, projection)
# Immediately return if input geometry is empty.
if len(df.geometry) == 0:
return ax
# Set extent.
extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior)
_set_extent(ax, projection, extent, extrema)
# Finally we draw the features.
if projection:
for geom in df.geometry:
features = ShapelyFeature([geom], ccrs.PlateCarree())
ax.add_feature(features, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
else:
for geom in df.geometry:
try: # Duck test for MultiPolygon.
for subgeom in geom:
feature = descartes.PolygonPatch(subgeom, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
ax.add_patch(feature)
except (TypeError, AssertionError): # Shapely Polygon.
feature = descartes.PolygonPatch(geom, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
ax.add_patch(feature)
return ax
|
[
"def",
"polyplot",
"(",
"df",
",",
"projection",
"=",
"None",
",",
"extent",
"=",
"None",
",",
"figsize",
"=",
"(",
"8",
",",
"6",
")",
",",
"ax",
"=",
"None",
",",
"edgecolor",
"=",
"'black'",
",",
"facecolor",
"=",
"'None'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Initialize the figure.",
"fig",
"=",
"_init_figure",
"(",
"ax",
",",
"figsize",
")",
"if",
"projection",
":",
"# Properly set up the projection.",
"projection",
"=",
"projection",
".",
"load",
"(",
"df",
",",
"{",
"'central_longitude'",
":",
"lambda",
"df",
":",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"[",
"p",
".",
"x",
"for",
"p",
"in",
"df",
".",
"geometry",
".",
"centroid",
"]",
")",
")",
",",
"'central_latitude'",
":",
"lambda",
"df",
":",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"[",
"p",
".",
"y",
"for",
"p",
"in",
"df",
".",
"geometry",
".",
"centroid",
"]",
")",
")",
"}",
")",
"# Set up the axis.",
"if",
"not",
"ax",
":",
"ax",
"=",
"plt",
".",
"subplot",
"(",
"111",
",",
"projection",
"=",
"projection",
")",
"else",
":",
"if",
"not",
"ax",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"# Clean up patches.",
"_lay_out_axes",
"(",
"ax",
",",
"projection",
")",
"# Immediately return if input geometry is empty.",
"if",
"len",
"(",
"df",
".",
"geometry",
")",
"==",
"0",
":",
"return",
"ax",
"# Set extent.",
"extrema",
"=",
"_get_envelopes_min_maxes",
"(",
"df",
".",
"geometry",
".",
"envelope",
".",
"exterior",
")",
"_set_extent",
"(",
"ax",
",",
"projection",
",",
"extent",
",",
"extrema",
")",
"# Finally we draw the features.",
"if",
"projection",
":",
"for",
"geom",
"in",
"df",
".",
"geometry",
":",
"features",
"=",
"ShapelyFeature",
"(",
"[",
"geom",
"]",
",",
"ccrs",
".",
"PlateCarree",
"(",
")",
")",
"ax",
".",
"add_feature",
"(",
"features",
",",
"facecolor",
"=",
"facecolor",
",",
"edgecolor",
"=",
"edgecolor",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"for",
"geom",
"in",
"df",
".",
"geometry",
":",
"try",
":",
"# Duck test for MultiPolygon.",
"for",
"subgeom",
"in",
"geom",
":",
"feature",
"=",
"descartes",
".",
"PolygonPatch",
"(",
"subgeom",
",",
"facecolor",
"=",
"facecolor",
",",
"edgecolor",
"=",
"edgecolor",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"add_patch",
"(",
"feature",
")",
"except",
"(",
"TypeError",
",",
"AssertionError",
")",
":",
"# Shapely Polygon.",
"feature",
"=",
"descartes",
".",
"PolygonPatch",
"(",
"geom",
",",
"facecolor",
"=",
"facecolor",
",",
"edgecolor",
"=",
"edgecolor",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"add_patch",
"(",
"feature",
")",
"return",
"ax"
] |
Trivial polygonal plot.
Parameters
----------
df : GeoDataFrame
The data being plotted.
projection : geoplot.crs object instance, optional
A geographic projection. For more information refer to `the tutorial page on projections
<https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
extent : None or (minx, maxx, miny, maxy), optional
Used to control plot x-axis and y-axis limits manually.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
Defaults to (8, 6), the ``matplotlib`` default global.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
ax : AxesSubplot or GeoAxesSubplot instance, optional
A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
kwargs: dict, optional
Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
Returns
-------
``AxesSubplot`` or ``GeoAxesSubplot``
The plot axis
Examples
--------
The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a
geometry and, optionally, a projection.
.. code-block:: python
import geoplot as gplt
import geoplot.crs as gcrs
gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
.. image:: ../figures/polyplot/polyplot-initial.png
However, note that ``polyplot`` is mainly intended to be used in concert with other plot types.
.. code-block:: python
ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(),
hue='BOROUGH', categorical=True,
legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
ax=ax)
.. image:: ../figures/polyplot/polyplot-stacked.png
Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
.. code-block:: python
ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(),
linewidth=0, facecolor='lightgray')
.. image:: ../figures/polyplot/polyplot-kwargs.png
|
[
"Trivial",
"polygonal",
"plot",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L346-L462
|
8,977
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
choropleth
|
def choropleth(df, projection=None,
hue=None,
scheme=None, k=5, cmap='Set1', categorical=False, vmin=None, vmax=None,
legend=False, legend_kwargs=None, legend_labels=None,
extent=None,
figsize=(8, 6), ax=None,
**kwargs):
"""
Area aggregation plot.
Parameters
----------
df : GeoDataFrame
The data being plotted.
projection : geoplot.crs object instance, optional
A geographic projection. For more information refer to `the tutorial page on projections
<https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
hue : None, Series, GeoSeries, iterable, or str, optional
Applies a colormap to the output points.
categorical : boolean, optional
Set to ``True`` if ``hue`` references a categorical variable, and ``False`` (the default) otherwise. Ignored
if ``hue`` is left unspecified.
scheme : None or {"quantiles"|"equal_interval"|"fisher_Jenks"}, optional
Controls how the colormap bin edges are determined. Ignored if ``hue`` is left unspecified.
k : int or None, optional
Ignored if ``hue`` is left unspecified. Otherwise, if ``categorical`` is False, controls how many colors to
use (5 is the default). If set to ``None``, a continuous colormap will be used.
cmap : matplotlib color, optional
The `matplotlib colormap <http://matplotlib.org/examples/color/colormaps_reference.html>`_ to be used.
Ignored if ``hue`` is left unspecified.
vmin : float, optional
Values below this level will be colored the same threshold value. Defaults to the dataset minimum. Ignored
if ``hue`` is left unspecified.
vmax : float, optional
Values above this level will be colored the same threshold value. Defaults to the dataset maximum. Ignored
if ``hue`` is left unspecified.
legend : boolean, optional
Whether or not to include a legend. Ignored if neither a ``hue`` nor a ``scale`` is specified.
legend_values : list, optional
The values to use in the legend. Defaults to equal intervals. For more information see `the Gallery demo
<https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_.
legend_labels : list, optional
The names to use in the legend. Defaults to the variable values. For more information see `the Gallery demo
<https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_.
legend_kwargs : dict, optional
Keyword arguments to be passed to `the underlying legend <http://matplotlib.org/users/legend_guide.html>`_.
extent : None or (minx, maxx, miny, maxy), optional
Used to control plot x-axis and y-axis limits manually.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
ax : AxesSubplot or GeoAxesSubplot instance, optional
A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
kwargs: dict, optional
Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
Returns
-------
``AxesSubplot`` or ``GeoAxesSubplot``
The plot axis
Examples
--------
A choropleth takes observations that have been aggregated on some meaningful polygonal level (e.g. census tract,
state, country, or continent) and displays the data to the reader using color. It is a well-known plot type,
and likeliest the most general-purpose and well-known of the specifically spatial plot types. It is especially
powerful when combined with meaningful or actionable aggregation areas; if no such aggregations exist,
or the aggregations you have access to are mostly incidental, its value is more limited.
The ``choropleth`` requires a series of enclosed areas consisting of ``shapely`` ``Polygon`` or ``MultiPolygon``
entities, and a set of data about them that you would like to express in color. A basic choropleth requires
geometry, a ``hue`` variable, and, optionally, a projection.
.. code-block:: python
import geoplot as gplt
import geoplot.crs as gcrs
gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree())
.. image:: ../figures/choropleth/choropleth-initial.png
Change the colormap with the ``cmap`` parameter.
.. code-block:: python
gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree(), cmap='Blues')
.. image:: ../figures/choropleth/choropleth-cmap.png
If your variable of interest is already `categorical
<http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_, you can specify ``categorical=True`` to
use the labels in your dataset directly. To add a legend, specify ``legend``.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName',
categorical=True, legend=True)
.. image:: ../figures/choropleth/choropleth-legend.png
Keyword arguments can be passed to the legend using the ``legend_kwargs`` argument. These arguments will be
passed to the underlying ``matplotlib.legend.Legend`` instance (`ref
<http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_). The ``loc`` and ``bbox_to_anchor``
parameters are particularly useful for positioning the legend. Other additional arguments will be passed to the
underlying ``matplotlib`` `scatter plot <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`_.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName',
categorical=True, legend=True, legend_kwargs={'loc': 'upper left'})
.. image:: ../figures/choropleth/choropleth-legend-kwargs.png
Additional arguments not in the method signature will be passed as keyword parameters to the underlying
`matplotlib Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True,
linewidth=0)
.. image:: ../figures/choropleth/choropleth-kwargs.png
Choropleths default to splitting the data into five buckets with approximately equal numbers of observations in
them. Change the number of buckets by specifying ``k``. Or, to use a continuous colormap, specify ``k=None``. In
this case a colorbar legend will be used.
.. code-block:: python
gplt.choropleth(polydata, hue='latdep', cmap='Blues', k=None, legend=True,
projection=gcrs.PlateCarree())
.. image:: ../figures/choropleth/choropleth-k-none.png
The ``choropleth`` binning methodology is controlled using by `scheme`` parameter. The default is ``quantile``,
which bins observations into classes of different sizes but the same numbers of observations. ``equal_interval``
will creates bins that are the same size, but potentially containing different numbers of observations.
The more complicated ``fisher_jenks`` scheme is an intermediate between the two.
.. code-block:: python
gplt.choropleth(census_tracts, hue='mock_data', projection=gcrs.AlbersEqualArea(),
legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
scheme='equal_interval')
.. image:: ../figures/choropleth/choropleth-scheme.png
"""
# Initialize the figure.
fig = _init_figure(ax, figsize)
if projection:
projection = projection.load(df, {
'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])),
'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid]))
})
# Set up the axis.
if not ax:
ax = plt.subplot(111, projection=projection)
else:
if not ax:
ax = plt.gca()
# Clean up patches.
_lay_out_axes(ax, projection)
# Immediately return if input geometry is empty.
if len(df.geometry) == 0:
return ax
# Set extent.
extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior)
_set_extent(ax, projection, extent, extrema)
# Format the data to be displayed for input.
hue = _validate_hue(df, hue)
if hue is None:
raise ValueError("No 'hue' specified.")
# Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous,
# based on whether or not ``k`` is specified (``hue`` must be specified for either to work).
if k is not None:
# Categorical colormap code path.
# Validate buckets.
categorical, k, scheme = _validate_buckets(categorical, k, scheme)
if hue is not None:
cmap, categories, hue_values = _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax)
colors = [cmap.to_rgba(v) for v in hue_values]
# Add a legend, if appropriate.
if legend:
_paint_hue_legend(ax, categories, cmap, legend_labels, legend_kwargs)
else:
colors = ['steelblue']*len(df)
elif k is None and hue is not None:
# Continuous colormap code path.
hue_values = hue
cmap = _continuous_colormap(hue_values, cmap, vmin, vmax)
colors = [cmap.to_rgba(v) for v in hue_values]
# Add a legend, if appropriate.
if legend:
_paint_colorbar_legend(ax, hue_values, cmap, legend_kwargs)
# Draw the features.
if projection:
for color, geom in zip(colors, df.geometry):
features = ShapelyFeature([geom], ccrs.PlateCarree())
ax.add_feature(features, facecolor=color, **kwargs)
else:
for color, geom in zip(colors, df.geometry):
try: # Duck test for MultiPolygon.
for subgeom in geom:
feature = descartes.PolygonPatch(subgeom, facecolor=color, **kwargs)
ax.add_patch(feature)
except (TypeError, AssertionError): # Shapely Polygon.
feature = descartes.PolygonPatch(geom, facecolor=color, **kwargs)
ax.add_patch(feature)
return ax
|
python
|
def choropleth(df, projection=None,
hue=None,
scheme=None, k=5, cmap='Set1', categorical=False, vmin=None, vmax=None,
legend=False, legend_kwargs=None, legend_labels=None,
extent=None,
figsize=(8, 6), ax=None,
**kwargs):
"""
Area aggregation plot.
Parameters
----------
df : GeoDataFrame
The data being plotted.
projection : geoplot.crs object instance, optional
A geographic projection. For more information refer to `the tutorial page on projections
<https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
hue : None, Series, GeoSeries, iterable, or str, optional
Applies a colormap to the output points.
categorical : boolean, optional
Set to ``True`` if ``hue`` references a categorical variable, and ``False`` (the default) otherwise. Ignored
if ``hue`` is left unspecified.
scheme : None or {"quantiles"|"equal_interval"|"fisher_Jenks"}, optional
Controls how the colormap bin edges are determined. Ignored if ``hue`` is left unspecified.
k : int or None, optional
Ignored if ``hue`` is left unspecified. Otherwise, if ``categorical`` is False, controls how many colors to
use (5 is the default). If set to ``None``, a continuous colormap will be used.
cmap : matplotlib color, optional
The `matplotlib colormap <http://matplotlib.org/examples/color/colormaps_reference.html>`_ to be used.
Ignored if ``hue`` is left unspecified.
vmin : float, optional
Values below this level will be colored the same threshold value. Defaults to the dataset minimum. Ignored
if ``hue`` is left unspecified.
vmax : float, optional
Values above this level will be colored the same threshold value. Defaults to the dataset maximum. Ignored
if ``hue`` is left unspecified.
legend : boolean, optional
Whether or not to include a legend. Ignored if neither a ``hue`` nor a ``scale`` is specified.
legend_values : list, optional
The values to use in the legend. Defaults to equal intervals. For more information see `the Gallery demo
<https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_.
legend_labels : list, optional
The names to use in the legend. Defaults to the variable values. For more information see `the Gallery demo
<https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_.
legend_kwargs : dict, optional
Keyword arguments to be passed to `the underlying legend <http://matplotlib.org/users/legend_guide.html>`_.
extent : None or (minx, maxx, miny, maxy), optional
Used to control plot x-axis and y-axis limits manually.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
ax : AxesSubplot or GeoAxesSubplot instance, optional
A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
kwargs: dict, optional
Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
Returns
-------
``AxesSubplot`` or ``GeoAxesSubplot``
The plot axis
Examples
--------
A choropleth takes observations that have been aggregated on some meaningful polygonal level (e.g. census tract,
state, country, or continent) and displays the data to the reader using color. It is a well-known plot type,
and likeliest the most general-purpose and well-known of the specifically spatial plot types. It is especially
powerful when combined with meaningful or actionable aggregation areas; if no such aggregations exist,
or the aggregations you have access to are mostly incidental, its value is more limited.
The ``choropleth`` requires a series of enclosed areas consisting of ``shapely`` ``Polygon`` or ``MultiPolygon``
entities, and a set of data about them that you would like to express in color. A basic choropleth requires
geometry, a ``hue`` variable, and, optionally, a projection.
.. code-block:: python
import geoplot as gplt
import geoplot.crs as gcrs
gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree())
.. image:: ../figures/choropleth/choropleth-initial.png
Change the colormap with the ``cmap`` parameter.
.. code-block:: python
gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree(), cmap='Blues')
.. image:: ../figures/choropleth/choropleth-cmap.png
If your variable of interest is already `categorical
<http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_, you can specify ``categorical=True`` to
use the labels in your dataset directly. To add a legend, specify ``legend``.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName',
categorical=True, legend=True)
.. image:: ../figures/choropleth/choropleth-legend.png
Keyword arguments can be passed to the legend using the ``legend_kwargs`` argument. These arguments will be
passed to the underlying ``matplotlib.legend.Legend`` instance (`ref
<http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_). The ``loc`` and ``bbox_to_anchor``
parameters are particularly useful for positioning the legend. Other additional arguments will be passed to the
underlying ``matplotlib`` `scatter plot <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`_.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName',
categorical=True, legend=True, legend_kwargs={'loc': 'upper left'})
.. image:: ../figures/choropleth/choropleth-legend-kwargs.png
Additional arguments not in the method signature will be passed as keyword parameters to the underlying
`matplotlib Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True,
linewidth=0)
.. image:: ../figures/choropleth/choropleth-kwargs.png
Choropleths default to splitting the data into five buckets with approximately equal numbers of observations in
them. Change the number of buckets by specifying ``k``. Or, to use a continuous colormap, specify ``k=None``. In
this case a colorbar legend will be used.
.. code-block:: python
gplt.choropleth(polydata, hue='latdep', cmap='Blues', k=None, legend=True,
projection=gcrs.PlateCarree())
.. image:: ../figures/choropleth/choropleth-k-none.png
The ``choropleth`` binning methodology is controlled using by `scheme`` parameter. The default is ``quantile``,
which bins observations into classes of different sizes but the same numbers of observations. ``equal_interval``
will creates bins that are the same size, but potentially containing different numbers of observations.
The more complicated ``fisher_jenks`` scheme is an intermediate between the two.
.. code-block:: python
gplt.choropleth(census_tracts, hue='mock_data', projection=gcrs.AlbersEqualArea(),
legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
scheme='equal_interval')
.. image:: ../figures/choropleth/choropleth-scheme.png
"""
# Initialize the figure.
fig = _init_figure(ax, figsize)
if projection:
projection = projection.load(df, {
'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])),
'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid]))
})
# Set up the axis.
if not ax:
ax = plt.subplot(111, projection=projection)
else:
if not ax:
ax = plt.gca()
# Clean up patches.
_lay_out_axes(ax, projection)
# Immediately return if input geometry is empty.
if len(df.geometry) == 0:
return ax
# Set extent.
extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior)
_set_extent(ax, projection, extent, extrema)
# Format the data to be displayed for input.
hue = _validate_hue(df, hue)
if hue is None:
raise ValueError("No 'hue' specified.")
# Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous,
# based on whether or not ``k`` is specified (``hue`` must be specified for either to work).
if k is not None:
# Categorical colormap code path.
# Validate buckets.
categorical, k, scheme = _validate_buckets(categorical, k, scheme)
if hue is not None:
cmap, categories, hue_values = _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax)
colors = [cmap.to_rgba(v) for v in hue_values]
# Add a legend, if appropriate.
if legend:
_paint_hue_legend(ax, categories, cmap, legend_labels, legend_kwargs)
else:
colors = ['steelblue']*len(df)
elif k is None and hue is not None:
# Continuous colormap code path.
hue_values = hue
cmap = _continuous_colormap(hue_values, cmap, vmin, vmax)
colors = [cmap.to_rgba(v) for v in hue_values]
# Add a legend, if appropriate.
if legend:
_paint_colorbar_legend(ax, hue_values, cmap, legend_kwargs)
# Draw the features.
if projection:
for color, geom in zip(colors, df.geometry):
features = ShapelyFeature([geom], ccrs.PlateCarree())
ax.add_feature(features, facecolor=color, **kwargs)
else:
for color, geom in zip(colors, df.geometry):
try: # Duck test for MultiPolygon.
for subgeom in geom:
feature = descartes.PolygonPatch(subgeom, facecolor=color, **kwargs)
ax.add_patch(feature)
except (TypeError, AssertionError): # Shapely Polygon.
feature = descartes.PolygonPatch(geom, facecolor=color, **kwargs)
ax.add_patch(feature)
return ax
|
[
"def",
"choropleth",
"(",
"df",
",",
"projection",
"=",
"None",
",",
"hue",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"k",
"=",
"5",
",",
"cmap",
"=",
"'Set1'",
",",
"categorical",
"=",
"False",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"legend",
"=",
"False",
",",
"legend_kwargs",
"=",
"None",
",",
"legend_labels",
"=",
"None",
",",
"extent",
"=",
"None",
",",
"figsize",
"=",
"(",
"8",
",",
"6",
")",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Initialize the figure.",
"fig",
"=",
"_init_figure",
"(",
"ax",
",",
"figsize",
")",
"if",
"projection",
":",
"projection",
"=",
"projection",
".",
"load",
"(",
"df",
",",
"{",
"'central_longitude'",
":",
"lambda",
"df",
":",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"[",
"p",
".",
"x",
"for",
"p",
"in",
"df",
".",
"geometry",
".",
"centroid",
"]",
")",
")",
",",
"'central_latitude'",
":",
"lambda",
"df",
":",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"[",
"p",
".",
"y",
"for",
"p",
"in",
"df",
".",
"geometry",
".",
"centroid",
"]",
")",
")",
"}",
")",
"# Set up the axis.",
"if",
"not",
"ax",
":",
"ax",
"=",
"plt",
".",
"subplot",
"(",
"111",
",",
"projection",
"=",
"projection",
")",
"else",
":",
"if",
"not",
"ax",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"# Clean up patches.",
"_lay_out_axes",
"(",
"ax",
",",
"projection",
")",
"# Immediately return if input geometry is empty.",
"if",
"len",
"(",
"df",
".",
"geometry",
")",
"==",
"0",
":",
"return",
"ax",
"# Set extent.",
"extrema",
"=",
"_get_envelopes_min_maxes",
"(",
"df",
".",
"geometry",
".",
"envelope",
".",
"exterior",
")",
"_set_extent",
"(",
"ax",
",",
"projection",
",",
"extent",
",",
"extrema",
")",
"# Format the data to be displayed for input.",
"hue",
"=",
"_validate_hue",
"(",
"df",
",",
"hue",
")",
"if",
"hue",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No 'hue' specified.\"",
")",
"# Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous,",
"# based on whether or not ``k`` is specified (``hue`` must be specified for either to work).",
"if",
"k",
"is",
"not",
"None",
":",
"# Categorical colormap code path.",
"# Validate buckets.",
"categorical",
",",
"k",
",",
"scheme",
"=",
"_validate_buckets",
"(",
"categorical",
",",
"k",
",",
"scheme",
")",
"if",
"hue",
"is",
"not",
"None",
":",
"cmap",
",",
"categories",
",",
"hue_values",
"=",
"_discrete_colorize",
"(",
"categorical",
",",
"hue",
",",
"scheme",
",",
"k",
",",
"cmap",
",",
"vmin",
",",
"vmax",
")",
"colors",
"=",
"[",
"cmap",
".",
"to_rgba",
"(",
"v",
")",
"for",
"v",
"in",
"hue_values",
"]",
"# Add a legend, if appropriate.",
"if",
"legend",
":",
"_paint_hue_legend",
"(",
"ax",
",",
"categories",
",",
"cmap",
",",
"legend_labels",
",",
"legend_kwargs",
")",
"else",
":",
"colors",
"=",
"[",
"'steelblue'",
"]",
"*",
"len",
"(",
"df",
")",
"elif",
"k",
"is",
"None",
"and",
"hue",
"is",
"not",
"None",
":",
"# Continuous colormap code path.",
"hue_values",
"=",
"hue",
"cmap",
"=",
"_continuous_colormap",
"(",
"hue_values",
",",
"cmap",
",",
"vmin",
",",
"vmax",
")",
"colors",
"=",
"[",
"cmap",
".",
"to_rgba",
"(",
"v",
")",
"for",
"v",
"in",
"hue_values",
"]",
"# Add a legend, if appropriate.",
"if",
"legend",
":",
"_paint_colorbar_legend",
"(",
"ax",
",",
"hue_values",
",",
"cmap",
",",
"legend_kwargs",
")",
"# Draw the features.",
"if",
"projection",
":",
"for",
"color",
",",
"geom",
"in",
"zip",
"(",
"colors",
",",
"df",
".",
"geometry",
")",
":",
"features",
"=",
"ShapelyFeature",
"(",
"[",
"geom",
"]",
",",
"ccrs",
".",
"PlateCarree",
"(",
")",
")",
"ax",
".",
"add_feature",
"(",
"features",
",",
"facecolor",
"=",
"color",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"for",
"color",
",",
"geom",
"in",
"zip",
"(",
"colors",
",",
"df",
".",
"geometry",
")",
":",
"try",
":",
"# Duck test for MultiPolygon.",
"for",
"subgeom",
"in",
"geom",
":",
"feature",
"=",
"descartes",
".",
"PolygonPatch",
"(",
"subgeom",
",",
"facecolor",
"=",
"color",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"add_patch",
"(",
"feature",
")",
"except",
"(",
"TypeError",
",",
"AssertionError",
")",
":",
"# Shapely Polygon.",
"feature",
"=",
"descartes",
".",
"PolygonPatch",
"(",
"geom",
",",
"facecolor",
"=",
"color",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"add_patch",
"(",
"feature",
")",
"return",
"ax"
] |
Area aggregation plot.
Parameters
----------
df : GeoDataFrame
The data being plotted.
projection : geoplot.crs object instance, optional
A geographic projection. For more information refer to `the tutorial page on projections
<https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
hue : None, Series, GeoSeries, iterable, or str, optional
Applies a colormap to the output points.
categorical : boolean, optional
Set to ``True`` if ``hue`` references a categorical variable, and ``False`` (the default) otherwise. Ignored
if ``hue`` is left unspecified.
scheme : None or {"quantiles"|"equal_interval"|"fisher_Jenks"}, optional
Controls how the colormap bin edges are determined. Ignored if ``hue`` is left unspecified.
k : int or None, optional
Ignored if ``hue`` is left unspecified. Otherwise, if ``categorical`` is False, controls how many colors to
use (5 is the default). If set to ``None``, a continuous colormap will be used.
cmap : matplotlib color, optional
The `matplotlib colormap <http://matplotlib.org/examples/color/colormaps_reference.html>`_ to be used.
Ignored if ``hue`` is left unspecified.
vmin : float, optional
Values below this level will be colored the same threshold value. Defaults to the dataset minimum. Ignored
if ``hue`` is left unspecified.
vmax : float, optional
Values above this level will be colored the same threshold value. Defaults to the dataset maximum. Ignored
if ``hue`` is left unspecified.
legend : boolean, optional
Whether or not to include a legend. Ignored if neither a ``hue`` nor a ``scale`` is specified.
legend_values : list, optional
The values to use in the legend. Defaults to equal intervals. For more information see `the Gallery demo
<https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_.
legend_labels : list, optional
The names to use in the legend. Defaults to the variable values. For more information see `the Gallery demo
<https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_.
legend_kwargs : dict, optional
Keyword arguments to be passed to `the underlying legend <http://matplotlib.org/users/legend_guide.html>`_.
extent : None or (minx, maxx, miny, maxy), optional
Used to control plot x-axis and y-axis limits manually.
figsize : tuple, optional
An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
ax : AxesSubplot or GeoAxesSubplot instance, optional
A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
kwargs: dict, optional
Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
<http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
Returns
-------
``AxesSubplot`` or ``GeoAxesSubplot``
The plot axis
Examples
--------
A choropleth takes observations that have been aggregated on some meaningful polygonal level (e.g. census tract,
state, country, or continent) and displays the data to the reader using color. It is a well-known plot type,
and likeliest the most general-purpose and well-known of the specifically spatial plot types. It is especially
powerful when combined with meaningful or actionable aggregation areas; if no such aggregations exist,
or the aggregations you have access to are mostly incidental, its value is more limited.
The ``choropleth`` requires a series of enclosed areas consisting of ``shapely`` ``Polygon`` or ``MultiPolygon``
entities, and a set of data about them that you would like to express in color. A basic choropleth requires
geometry, a ``hue`` variable, and, optionally, a projection.
.. code-block:: python
import geoplot as gplt
import geoplot.crs as gcrs
gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree())
.. image:: ../figures/choropleth/choropleth-initial.png
Change the colormap with the ``cmap`` parameter.
.. code-block:: python
gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree(), cmap='Blues')
.. image:: ../figures/choropleth/choropleth-cmap.png
If your variable of interest is already `categorical
<http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_, you can specify ``categorical=True`` to
use the labels in your dataset directly. To add a legend, specify ``legend``.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName',
categorical=True, legend=True)
.. image:: ../figures/choropleth/choropleth-legend.png
Keyword arguments can be passed to the legend using the ``legend_kwargs`` argument. These arguments will be
passed to the underlying ``matplotlib.legend.Legend`` instance (`ref
<http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_). The ``loc`` and ``bbox_to_anchor``
parameters are particularly useful for positioning the legend. Other additional arguments will be passed to the
underlying ``matplotlib`` `scatter plot <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`_.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName',
categorical=True, legend=True, legend_kwargs={'loc': 'upper left'})
.. image:: ../figures/choropleth/choropleth-legend-kwargs.png
Additional arguments not in the method signature will be passed as keyword parameters to the underlying
`matplotlib Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.
.. code-block:: python
gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True,
linewidth=0)
.. image:: ../figures/choropleth/choropleth-kwargs.png
Choropleths default to splitting the data into five buckets with approximately equal numbers of observations in
them. Change the number of buckets by specifying ``k``. Or, to use a continuous colormap, specify ``k=None``. In
this case a colorbar legend will be used.
.. code-block:: python
gplt.choropleth(polydata, hue='latdep', cmap='Blues', k=None, legend=True,
projection=gcrs.PlateCarree())
.. image:: ../figures/choropleth/choropleth-k-none.png
The ``choropleth`` binning methodology is controlled using by `scheme`` parameter. The default is ``quantile``,
which bins observations into classes of different sizes but the same numbers of observations. ``equal_interval``
will creates bins that are the same size, but potentially containing different numbers of observations.
The more complicated ``fisher_jenks`` scheme is an intermediate between the two.
.. code-block:: python
gplt.choropleth(census_tracts, hue='mock_data', projection=gcrs.AlbersEqualArea(),
legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
scheme='equal_interval')
.. image:: ../figures/choropleth/choropleth-scheme.png
|
[
"Area",
"aggregation",
"plot",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L465-L687
|
8,978
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_get_envelopes_min_maxes
|
def _get_envelopes_min_maxes(envelopes):
"""
Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note
tha the ``Quadtree.bounds`` object property serves a similar role.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope.exterior``.
Returns
-------
(xmin, xmax, ymin, ymax) : tuple
The data extrema.
"""
xmin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][0],
linearring.coords[2][0],
linearring.coords[3][0],
linearring.coords[4][0]])))
xmax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][0],
linearring.coords[2][0],
linearring.coords[3][0],
linearring.coords[4][0]])))
ymin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][1],
linearring.coords[2][1],
linearring.coords[3][1],
linearring.coords[4][1]])))
ymax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][1],
linearring.coords[2][1],
linearring.coords[3][1],
linearring.coords[4][1]])))
return xmin, xmax, ymin, ymax
|
python
|
def _get_envelopes_min_maxes(envelopes):
"""
Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note
tha the ``Quadtree.bounds`` object property serves a similar role.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope.exterior``.
Returns
-------
(xmin, xmax, ymin, ymax) : tuple
The data extrema.
"""
xmin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][0],
linearring.coords[2][0],
linearring.coords[3][0],
linearring.coords[4][0]])))
xmax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][0],
linearring.coords[2][0],
linearring.coords[3][0],
linearring.coords[4][0]])))
ymin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][1],
linearring.coords[2][1],
linearring.coords[3][1],
linearring.coords[4][1]])))
ymax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][1],
linearring.coords[2][1],
linearring.coords[3][1],
linearring.coords[4][1]])))
return xmin, xmax, ymin, ymax
|
[
"def",
"_get_envelopes_min_maxes",
"(",
"envelopes",
")",
":",
"xmin",
"=",
"np",
".",
"min",
"(",
"envelopes",
".",
"map",
"(",
"lambda",
"linearring",
":",
"np",
".",
"min",
"(",
"[",
"linearring",
".",
"coords",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"linearring",
".",
"coords",
"[",
"2",
"]",
"[",
"0",
"]",
",",
"linearring",
".",
"coords",
"[",
"3",
"]",
"[",
"0",
"]",
",",
"linearring",
".",
"coords",
"[",
"4",
"]",
"[",
"0",
"]",
"]",
")",
")",
")",
"xmax",
"=",
"np",
".",
"max",
"(",
"envelopes",
".",
"map",
"(",
"lambda",
"linearring",
":",
"np",
".",
"max",
"(",
"[",
"linearring",
".",
"coords",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"linearring",
".",
"coords",
"[",
"2",
"]",
"[",
"0",
"]",
",",
"linearring",
".",
"coords",
"[",
"3",
"]",
"[",
"0",
"]",
",",
"linearring",
".",
"coords",
"[",
"4",
"]",
"[",
"0",
"]",
"]",
")",
")",
")",
"ymin",
"=",
"np",
".",
"min",
"(",
"envelopes",
".",
"map",
"(",
"lambda",
"linearring",
":",
"np",
".",
"min",
"(",
"[",
"linearring",
".",
"coords",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"linearring",
".",
"coords",
"[",
"2",
"]",
"[",
"1",
"]",
",",
"linearring",
".",
"coords",
"[",
"3",
"]",
"[",
"1",
"]",
",",
"linearring",
".",
"coords",
"[",
"4",
"]",
"[",
"1",
"]",
"]",
")",
")",
")",
"ymax",
"=",
"np",
".",
"max",
"(",
"envelopes",
".",
"map",
"(",
"lambda",
"linearring",
":",
"np",
".",
"max",
"(",
"[",
"linearring",
".",
"coords",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"linearring",
".",
"coords",
"[",
"2",
"]",
"[",
"1",
"]",
",",
"linearring",
".",
"coords",
"[",
"3",
"]",
"[",
"1",
"]",
",",
"linearring",
".",
"coords",
"[",
"4",
"]",
"[",
"1",
"]",
"]",
")",
")",
")",
"return",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax"
] |
Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note
tha the ``Quadtree.bounds`` object property serves a similar role.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope.exterior``.
Returns
-------
(xmin, xmax, ymin, ymax) : tuple
The data extrema.
|
[
"Returns",
"the",
"extrema",
"of",
"the",
"inputted",
"polygonal",
"envelopes",
".",
"Used",
"for",
"setting",
"chart",
"extent",
"where",
"appropriate",
".",
"Note",
"tha",
"the",
"Quadtree",
".",
"bounds",
"object",
"property",
"serves",
"a",
"similar",
"role",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2192-L2224
|
8,979
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_get_envelopes_centroid
|
def _get_envelopes_centroid(envelopes):
"""
Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this
library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope``.
Returns
-------
(mean_x, mean_y) : tuple
The data centroid.
"""
xmin, xmax, ymin, ymax = _get_envelopes_min_maxes(envelopes)
return np.mean(xmin, xmax), np.mean(ymin, ymax)
|
python
|
def _get_envelopes_centroid(envelopes):
"""
Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this
library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope``.
Returns
-------
(mean_x, mean_y) : tuple
The data centroid.
"""
xmin, xmax, ymin, ymax = _get_envelopes_min_maxes(envelopes)
return np.mean(xmin, xmax), np.mean(ymin, ymax)
|
[
"def",
"_get_envelopes_centroid",
"(",
"envelopes",
")",
":",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"_get_envelopes_min_maxes",
"(",
"envelopes",
")",
"return",
"np",
".",
"mean",
"(",
"xmin",
",",
"xmax",
")",
",",
"np",
".",
"mean",
"(",
"ymin",
",",
"ymax",
")"
] |
Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this
library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope``.
Returns
-------
(mean_x, mean_y) : tuple
The data centroid.
|
[
"Returns",
"the",
"centroid",
"of",
"an",
"inputted",
"geometry",
"column",
".",
"Not",
"currently",
"in",
"use",
"as",
"this",
"is",
"now",
"handled",
"by",
"this",
"library",
"s",
"CRS",
"wrapper",
"directly",
".",
"Light",
"wrapper",
"over",
"_get_envelopes_min_maxes",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2227-L2243
|
8,980
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_set_extent
|
def _set_extent(ax, projection, extent, extrema):
"""
Sets the plot extent.
Parameters
----------
ax : cartopy.GeoAxesSubplot instance
The axis whose boundaries are being tweaked.
projection : None or geoplot.crs instance
The projection, if one is being used.
extent : None or (xmin, xmax, ymin, ymax) tuple
A copy of the ``extent`` top-level parameter, if the user choses to specify their own extent. These values
will be used if ``extent`` is non-``None``.
extrema : None or (xmin, xmax, ymin, ymax) tuple
Plot-calculated extrema. These values, which are calculated in the plot above and passed to this function
(different plots require different calculations), will be used if a user-provided ``extent`` is not provided.
Returns
-------
None
"""
if extent:
xmin, xmax, ymin, ymax = extent
xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90)
if projection: # Input ``extent`` into set_extent().
ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree())
else: # Input ``extent`` into set_ylim, set_xlim.
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
else:
xmin, xmax, ymin, ymax = extrema
xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90)
if projection: # Input ``extrema`` into set_extent.
ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree())
else: # Input ``extrema`` into set_ylim, set_xlim.
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
|
python
|
def _set_extent(ax, projection, extent, extrema):
"""
Sets the plot extent.
Parameters
----------
ax : cartopy.GeoAxesSubplot instance
The axis whose boundaries are being tweaked.
projection : None or geoplot.crs instance
The projection, if one is being used.
extent : None or (xmin, xmax, ymin, ymax) tuple
A copy of the ``extent`` top-level parameter, if the user choses to specify their own extent. These values
will be used if ``extent`` is non-``None``.
extrema : None or (xmin, xmax, ymin, ymax) tuple
Plot-calculated extrema. These values, which are calculated in the plot above and passed to this function
(different plots require different calculations), will be used if a user-provided ``extent`` is not provided.
Returns
-------
None
"""
if extent:
xmin, xmax, ymin, ymax = extent
xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90)
if projection: # Input ``extent`` into set_extent().
ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree())
else: # Input ``extent`` into set_ylim, set_xlim.
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
else:
xmin, xmax, ymin, ymax = extrema
xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90)
if projection: # Input ``extrema`` into set_extent.
ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree())
else: # Input ``extrema`` into set_ylim, set_xlim.
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
|
[
"def",
"_set_extent",
"(",
"ax",
",",
"projection",
",",
"extent",
",",
"extrema",
")",
":",
"if",
"extent",
":",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"extent",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"max",
"(",
"xmin",
",",
"-",
"180",
")",
",",
"min",
"(",
"xmax",
",",
"180",
")",
",",
"max",
"(",
"ymin",
",",
"-",
"90",
")",
",",
"min",
"(",
"ymax",
",",
"90",
")",
"if",
"projection",
":",
"# Input ``extent`` into set_extent().",
"ax",
".",
"set_extent",
"(",
"(",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
")",
",",
"crs",
"=",
"ccrs",
".",
"PlateCarree",
"(",
")",
")",
"else",
":",
"# Input ``extent`` into set_ylim, set_xlim.",
"ax",
".",
"set_xlim",
"(",
"(",
"xmin",
",",
"xmax",
")",
")",
"ax",
".",
"set_ylim",
"(",
"(",
"ymin",
",",
"ymax",
")",
")",
"else",
":",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"extrema",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"max",
"(",
"xmin",
",",
"-",
"180",
")",
",",
"min",
"(",
"xmax",
",",
"180",
")",
",",
"max",
"(",
"ymin",
",",
"-",
"90",
")",
",",
"min",
"(",
"ymax",
",",
"90",
")",
"if",
"projection",
":",
"# Input ``extrema`` into set_extent.",
"ax",
".",
"set_extent",
"(",
"(",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
")",
",",
"crs",
"=",
"ccrs",
".",
"PlateCarree",
"(",
")",
")",
"else",
":",
"# Input ``extrema`` into set_ylim, set_xlim.",
"ax",
".",
"set_xlim",
"(",
"(",
"xmin",
",",
"xmax",
")",
")",
"ax",
".",
"set_ylim",
"(",
"(",
"ymin",
",",
"ymax",
")",
")"
] |
Sets the plot extent.
Parameters
----------
ax : cartopy.GeoAxesSubplot instance
The axis whose boundaries are being tweaked.
projection : None or geoplot.crs instance
The projection, if one is being used.
extent : None or (xmin, xmax, ymin, ymax) tuple
A copy of the ``extent`` top-level parameter, if the user choses to specify their own extent. These values
will be used if ``extent`` is non-``None``.
extrema : None or (xmin, xmax, ymin, ymax) tuple
Plot-calculated extrema. These values, which are calculated in the plot above and passed to this function
(different plots require different calculations), will be used if a user-provided ``extent`` is not provided.
Returns
-------
None
|
[
"Sets",
"the",
"plot",
"extent",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2246-L2285
|
8,981
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_lay_out_axes
|
def _lay_out_axes(ax, projection):
"""
``cartopy`` enables a a transparent background patch and an "outline" patch by default. This short method simply
hides these extraneous visual features. If the plot is a pure ``matplotlib`` one, it does the same thing by
removing the axis altogether.
Parameters
----------
ax : matplotlib.Axes instance
The ``matplotlib.Axes`` instance being manipulated.
projection : None or geoplot.crs instance
The projection, if one is used.
Returns
-------
None
"""
if projection is not None:
try:
ax.background_patch.set_visible(False)
ax.outline_patch.set_visible(False)
except AttributeError: # Testing...
pass
else:
plt.gca().axison = False
|
python
|
def _lay_out_axes(ax, projection):
"""
``cartopy`` enables a a transparent background patch and an "outline" patch by default. This short method simply
hides these extraneous visual features. If the plot is a pure ``matplotlib`` one, it does the same thing by
removing the axis altogether.
Parameters
----------
ax : matplotlib.Axes instance
The ``matplotlib.Axes`` instance being manipulated.
projection : None or geoplot.crs instance
The projection, if one is used.
Returns
-------
None
"""
if projection is not None:
try:
ax.background_patch.set_visible(False)
ax.outline_patch.set_visible(False)
except AttributeError: # Testing...
pass
else:
plt.gca().axison = False
|
[
"def",
"_lay_out_axes",
"(",
"ax",
",",
"projection",
")",
":",
"if",
"projection",
"is",
"not",
"None",
":",
"try",
":",
"ax",
".",
"background_patch",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"outline_patch",
".",
"set_visible",
"(",
"False",
")",
"except",
"AttributeError",
":",
"# Testing...",
"pass",
"else",
":",
"plt",
".",
"gca",
"(",
")",
".",
"axison",
"=",
"False"
] |
``cartopy`` enables a a transparent background patch and an "outline" patch by default. This short method simply
hides these extraneous visual features. If the plot is a pure ``matplotlib`` one, it does the same thing by
removing the axis altogether.
Parameters
----------
ax : matplotlib.Axes instance
The ``matplotlib.Axes`` instance being manipulated.
projection : None or geoplot.crs instance
The projection, if one is used.
Returns
-------
None
|
[
"cartopy",
"enables",
"a",
"a",
"transparent",
"background",
"patch",
"and",
"an",
"outline",
"patch",
"by",
"default",
".",
"This",
"short",
"method",
"simply",
"hides",
"these",
"extraneous",
"visual",
"features",
".",
"If",
"the",
"plot",
"is",
"a",
"pure",
"matplotlib",
"one",
"it",
"does",
"the",
"same",
"thing",
"by",
"removing",
"the",
"axis",
"altogether",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2288-L2312
|
8,982
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_continuous_colormap
|
def _continuous_colormap(hue, cmap, vmin, vmax):
"""
Creates a continuous colormap.
Parameters
----------
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized
iterables before this method is called.
cmap : ``matplotlib.cm`` instance
The `matplotlib` colormap instance which will be used to colorize the geometries.
vmin : float
A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is below this level will all be colored by the same threshold value. The value for this variable is
meant to be inherited from the top-level variable of the same name.
vmax : float
A strict ceiling on the value associated with the "top" of the colormap spectrum. Data column entries whose
value is above this level will all be colored by the same threshold value. The value for this variable is
meant to be inherited from the top-level variable of the same name.
Returns
-------
cmap : ``mpl.cm.ScalarMappable`` instance
A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs.
"""
mn = min(hue) if vmin is None else vmin
mx = max(hue) if vmax is None else vmax
norm = mpl.colors.Normalize(vmin=mn, vmax=mx)
return mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
|
python
|
def _continuous_colormap(hue, cmap, vmin, vmax):
"""
Creates a continuous colormap.
Parameters
----------
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized
iterables before this method is called.
cmap : ``matplotlib.cm`` instance
The `matplotlib` colormap instance which will be used to colorize the geometries.
vmin : float
A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is below this level will all be colored by the same threshold value. The value for this variable is
meant to be inherited from the top-level variable of the same name.
vmax : float
A strict ceiling on the value associated with the "top" of the colormap spectrum. Data column entries whose
value is above this level will all be colored by the same threshold value. The value for this variable is
meant to be inherited from the top-level variable of the same name.
Returns
-------
cmap : ``mpl.cm.ScalarMappable`` instance
A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs.
"""
mn = min(hue) if vmin is None else vmin
mx = max(hue) if vmax is None else vmax
norm = mpl.colors.Normalize(vmin=mn, vmax=mx)
return mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
|
[
"def",
"_continuous_colormap",
"(",
"hue",
",",
"cmap",
",",
"vmin",
",",
"vmax",
")",
":",
"mn",
"=",
"min",
"(",
"hue",
")",
"if",
"vmin",
"is",
"None",
"else",
"vmin",
"mx",
"=",
"max",
"(",
"hue",
")",
"if",
"vmax",
"is",
"None",
"else",
"vmax",
"norm",
"=",
"mpl",
".",
"colors",
".",
"Normalize",
"(",
"vmin",
"=",
"mn",
",",
"vmax",
"=",
"mx",
")",
"return",
"mpl",
".",
"cm",
".",
"ScalarMappable",
"(",
"norm",
"=",
"norm",
",",
"cmap",
"=",
"cmap",
")"
] |
Creates a continuous colormap.
Parameters
----------
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized
iterables before this method is called.
cmap : ``matplotlib.cm`` instance
The `matplotlib` colormap instance which will be used to colorize the geometries.
vmin : float
A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is below this level will all be colored by the same threshold value. The value for this variable is
meant to be inherited from the top-level variable of the same name.
vmax : float
A strict ceiling on the value associated with the "top" of the colormap spectrum. Data column entries whose
value is above this level will all be colored by the same threshold value. The value for this variable is
meant to be inherited from the top-level variable of the same name.
Returns
-------
cmap : ``mpl.cm.ScalarMappable`` instance
A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs.
|
[
"Creates",
"a",
"continuous",
"colormap",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2345-L2374
|
8,983
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_discrete_colorize
|
def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax):
"""
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical
ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we
assume that the input data is categorical.
This code makes extensive use of ``geopandas`` choropleth facilities.
Parameters
----------
categorical : boolean
Whether or not the input variable is already categorical.
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized
iterables before this method is called.
scheme : str
The mapclassify binning scheme to be used for splitting data values (or rather, the the string representation
thereof).
k : int
The number of bins which will be used. This parameter will be ignored if ``categorical`` is True. The default
value should be 5---this should be set before this method is called.
cmap : ``matplotlib.cm`` instance
The `matplotlib` colormap instance which will be used to colorize the geometries. This colormap
determines the spectrum; our algorithm determines the cuts.
vmin : float
A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is below this level will all be colored by the same threshold value.
vmax : float
A strict cealing on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is above this level will all be colored by the same threshold value.
Returns
-------
(cmap, categories, values) : tuple
A tuple meant for assignment containing the values for various properties set by this method call.
"""
if not categorical:
binning = _mapclassify_choro(hue, scheme, k=k)
values = binning.yb
binedges = [binning.yb.min()] + binning.bins.tolist()
categories = ['{0:.2f} - {1:.2f}'.format(binedges[i], binedges[i + 1])
for i in range(len(binedges) - 1)]
else:
categories = np.unique(hue)
if len(categories) > 10:
warnings.warn("Generating a colormap using a categorical column with over 10 individual categories. "
"This is not recommended!")
value_map = {v: i for i, v in enumerate(categories)}
values = [value_map[d] for d in hue]
cmap = _norm_cmap(values, cmap, mpl.colors.Normalize, mpl.cm, vmin=vmin, vmax=vmax)
return cmap, categories, values
|
python
|
def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax):
"""
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical
ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we
assume that the input data is categorical.
This code makes extensive use of ``geopandas`` choropleth facilities.
Parameters
----------
categorical : boolean
Whether or not the input variable is already categorical.
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized
iterables before this method is called.
scheme : str
The mapclassify binning scheme to be used for splitting data values (or rather, the the string representation
thereof).
k : int
The number of bins which will be used. This parameter will be ignored if ``categorical`` is True. The default
value should be 5---this should be set before this method is called.
cmap : ``matplotlib.cm`` instance
The `matplotlib` colormap instance which will be used to colorize the geometries. This colormap
determines the spectrum; our algorithm determines the cuts.
vmin : float
A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is below this level will all be colored by the same threshold value.
vmax : float
A strict cealing on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is above this level will all be colored by the same threshold value.
Returns
-------
(cmap, categories, values) : tuple
A tuple meant for assignment containing the values for various properties set by this method call.
"""
if not categorical:
binning = _mapclassify_choro(hue, scheme, k=k)
values = binning.yb
binedges = [binning.yb.min()] + binning.bins.tolist()
categories = ['{0:.2f} - {1:.2f}'.format(binedges[i], binedges[i + 1])
for i in range(len(binedges) - 1)]
else:
categories = np.unique(hue)
if len(categories) > 10:
warnings.warn("Generating a colormap using a categorical column with over 10 individual categories. "
"This is not recommended!")
value_map = {v: i for i, v in enumerate(categories)}
values = [value_map[d] for d in hue]
cmap = _norm_cmap(values, cmap, mpl.colors.Normalize, mpl.cm, vmin=vmin, vmax=vmax)
return cmap, categories, values
|
[
"def",
"_discrete_colorize",
"(",
"categorical",
",",
"hue",
",",
"scheme",
",",
"k",
",",
"cmap",
",",
"vmin",
",",
"vmax",
")",
":",
"if",
"not",
"categorical",
":",
"binning",
"=",
"_mapclassify_choro",
"(",
"hue",
",",
"scheme",
",",
"k",
"=",
"k",
")",
"values",
"=",
"binning",
".",
"yb",
"binedges",
"=",
"[",
"binning",
".",
"yb",
".",
"min",
"(",
")",
"]",
"+",
"binning",
".",
"bins",
".",
"tolist",
"(",
")",
"categories",
"=",
"[",
"'{0:.2f} - {1:.2f}'",
".",
"format",
"(",
"binedges",
"[",
"i",
"]",
",",
"binedges",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"binedges",
")",
"-",
"1",
")",
"]",
"else",
":",
"categories",
"=",
"np",
".",
"unique",
"(",
"hue",
")",
"if",
"len",
"(",
"categories",
")",
">",
"10",
":",
"warnings",
".",
"warn",
"(",
"\"Generating a colormap using a categorical column with over 10 individual categories. \"",
"\"This is not recommended!\"",
")",
"value_map",
"=",
"{",
"v",
":",
"i",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"categories",
")",
"}",
"values",
"=",
"[",
"value_map",
"[",
"d",
"]",
"for",
"d",
"in",
"hue",
"]",
"cmap",
"=",
"_norm_cmap",
"(",
"values",
",",
"cmap",
",",
"mpl",
".",
"colors",
".",
"Normalize",
",",
"mpl",
".",
"cm",
",",
"vmin",
"=",
"vmin",
",",
"vmax",
"=",
"vmax",
")",
"return",
"cmap",
",",
"categories",
",",
"values"
] |
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical
ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we
assume that the input data is categorical.
This code makes extensive use of ``geopandas`` choropleth facilities.
Parameters
----------
categorical : boolean
Whether or not the input variable is already categorical.
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized
iterables before this method is called.
scheme : str
The mapclassify binning scheme to be used for splitting data values (or rather, the the string representation
thereof).
k : int
The number of bins which will be used. This parameter will be ignored if ``categorical`` is True. The default
value should be 5---this should be set before this method is called.
cmap : ``matplotlib.cm`` instance
The `matplotlib` colormap instance which will be used to colorize the geometries. This colormap
determines the spectrum; our algorithm determines the cuts.
vmin : float
A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is below this level will all be colored by the same threshold value.
vmax : float
A strict cealing on the value associated with the "bottom" of the colormap spectrum. Data column entries whose
value is above this level will all be colored by the same threshold value.
Returns
-------
(cmap, categories, values) : tuple
A tuple meant for assignment containing the values for various properties set by this method call.
|
[
"Creates",
"a",
"discrete",
"colormap",
"either",
"using",
"an",
"already",
"-",
"categorical",
"data",
"variable",
"or",
"by",
"bucketing",
"a",
"non",
"-",
"categorical",
"ordinal",
"one",
".",
"If",
"a",
"scheme",
"is",
"provided",
"we",
"compute",
"a",
"distribution",
"for",
"the",
"given",
"data",
".",
"If",
"one",
"is",
"not",
"provided",
"we",
"assume",
"that",
"the",
"input",
"data",
"is",
"categorical",
"."
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2377-L2428
|
8,984
|
ResidentMario/geoplot
|
geoplot/geoplot.py
|
_norm_cmap
|
def _norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None):
"""
Normalize and set colormap. Taken from geopandas@0.2.1 codebase, removed in geopandas@0.3.0.
"""
mn = min(values) if vmin is None else vmin
mx = max(values) if vmax is None else vmax
norm = normalize(vmin=mn, vmax=mx)
n_cmap = cm.ScalarMappable(norm=norm, cmap=cmap)
return n_cmap
|
python
|
def _norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None):
"""
Normalize and set colormap. Taken from geopandas@0.2.1 codebase, removed in geopandas@0.3.0.
"""
mn = min(values) if vmin is None else vmin
mx = max(values) if vmax is None else vmax
norm = normalize(vmin=mn, vmax=mx)
n_cmap = cm.ScalarMappable(norm=norm, cmap=cmap)
return n_cmap
|
[
"def",
"_norm_cmap",
"(",
"values",
",",
"cmap",
",",
"normalize",
",",
"cm",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"mn",
"=",
"min",
"(",
"values",
")",
"if",
"vmin",
"is",
"None",
"else",
"vmin",
"mx",
"=",
"max",
"(",
"values",
")",
"if",
"vmax",
"is",
"None",
"else",
"vmax",
"norm",
"=",
"normalize",
"(",
"vmin",
"=",
"mn",
",",
"vmax",
"=",
"mx",
")",
"n_cmap",
"=",
"cm",
".",
"ScalarMappable",
"(",
"norm",
"=",
"norm",
",",
"cmap",
"=",
"cmap",
")",
"return",
"n_cmap"
] |
Normalize and set colormap. Taken from geopandas@0.2.1 codebase, removed in geopandas@0.3.0.
|
[
"Normalize",
"and",
"set",
"colormap",
".",
"Taken",
"from",
"geopandas"
] |
942b474878187a87a95a27fbe41285dfdc1d20ca
|
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2733-L2742
|
8,985
|
tmux-python/libtmux
|
libtmux/common.py
|
get_version
|
def get_version():
"""
Return tmux version.
If tmux is built from git master, the version returned will be the latest
version appended with -master, e.g. ``2.4-master``.
If using OpenBSD's base system tmux, the version will have ``-openbsd``
appended to the latest version, e.g. ``2.4-openbsd``.
Returns
-------
:class:`distutils.version.LooseVersion`
tmux version according to :func:`libtmux.common.which`'s tmux
"""
proc = tmux_cmd('-V')
if proc.stderr:
if proc.stderr[0] == 'tmux: unknown option -- V':
if sys.platform.startswith("openbsd"): # openbsd has no tmux -V
return LooseVersion('%s-openbsd' % TMUX_MAX_VERSION)
raise exc.LibTmuxException(
'libtmux supports tmux %s and greater. This system'
' is running tmux 1.3 or earlier.' % TMUX_MIN_VERSION
)
raise exc.VersionTooLow(proc.stderr)
version = proc.stdout[0].split('tmux ')[1]
# Allow latest tmux HEAD
if version == 'master':
return LooseVersion('%s-master' % TMUX_MAX_VERSION)
version = re.sub(r'[a-z-]', '', version)
return LooseVersion(version)
|
python
|
def get_version():
"""
Return tmux version.
If tmux is built from git master, the version returned will be the latest
version appended with -master, e.g. ``2.4-master``.
If using OpenBSD's base system tmux, the version will have ``-openbsd``
appended to the latest version, e.g. ``2.4-openbsd``.
Returns
-------
:class:`distutils.version.LooseVersion`
tmux version according to :func:`libtmux.common.which`'s tmux
"""
proc = tmux_cmd('-V')
if proc.stderr:
if proc.stderr[0] == 'tmux: unknown option -- V':
if sys.platform.startswith("openbsd"): # openbsd has no tmux -V
return LooseVersion('%s-openbsd' % TMUX_MAX_VERSION)
raise exc.LibTmuxException(
'libtmux supports tmux %s and greater. This system'
' is running tmux 1.3 or earlier.' % TMUX_MIN_VERSION
)
raise exc.VersionTooLow(proc.stderr)
version = proc.stdout[0].split('tmux ')[1]
# Allow latest tmux HEAD
if version == 'master':
return LooseVersion('%s-master' % TMUX_MAX_VERSION)
version = re.sub(r'[a-z-]', '', version)
return LooseVersion(version)
|
[
"def",
"get_version",
"(",
")",
":",
"proc",
"=",
"tmux_cmd",
"(",
"'-V'",
")",
"if",
"proc",
".",
"stderr",
":",
"if",
"proc",
".",
"stderr",
"[",
"0",
"]",
"==",
"'tmux: unknown option -- V'",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"openbsd\"",
")",
":",
"# openbsd has no tmux -V",
"return",
"LooseVersion",
"(",
"'%s-openbsd'",
"%",
"TMUX_MAX_VERSION",
")",
"raise",
"exc",
".",
"LibTmuxException",
"(",
"'libtmux supports tmux %s and greater. This system'",
"' is running tmux 1.3 or earlier.'",
"%",
"TMUX_MIN_VERSION",
")",
"raise",
"exc",
".",
"VersionTooLow",
"(",
"proc",
".",
"stderr",
")",
"version",
"=",
"proc",
".",
"stdout",
"[",
"0",
"]",
".",
"split",
"(",
"'tmux '",
")",
"[",
"1",
"]",
"# Allow latest tmux HEAD",
"if",
"version",
"==",
"'master'",
":",
"return",
"LooseVersion",
"(",
"'%s-master'",
"%",
"TMUX_MAX_VERSION",
")",
"version",
"=",
"re",
".",
"sub",
"(",
"r'[a-z-]'",
",",
"''",
",",
"version",
")",
"return",
"LooseVersion",
"(",
"version",
")"
] |
Return tmux version.
If tmux is built from git master, the version returned will be the latest
version appended with -master, e.g. ``2.4-master``.
If using OpenBSD's base system tmux, the version will have ``-openbsd``
appended to the latest version, e.g. ``2.4-openbsd``.
Returns
-------
:class:`distutils.version.LooseVersion`
tmux version according to :func:`libtmux.common.which`'s tmux
|
[
"Return",
"tmux",
"version",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L442-L476
|
8,986
|
tmux-python/libtmux
|
libtmux/common.py
|
has_minimum_version
|
def has_minimum_version(raises=True):
"""
Return if tmux meets version requirement. Version >1.8 or above.
Parameters
----------
raises : bool
raise exception if below minimum version requirement
Returns
-------
bool
True if tmux meets minimum required version.
Raises
------
libtmux.exc.VersionTooLow
tmux version below minimum required for libtmux
Notes
-----
.. versionchanged:: 0.7.0
No longer returns version, returns True or False
.. versionchanged:: 0.1.7
Versions will now remove trailing letters per `Issue 55`_.
.. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55.
"""
if get_version() < LooseVersion(TMUX_MIN_VERSION):
if raises:
raise exc.VersionTooLow(
'libtmux only supports tmux %s and greater. This system'
' has %s installed. Upgrade your tmux to use libtmux.'
% (TMUX_MIN_VERSION, get_version())
)
else:
return False
return True
|
python
|
def has_minimum_version(raises=True):
"""
Return if tmux meets version requirement. Version >1.8 or above.
Parameters
----------
raises : bool
raise exception if below minimum version requirement
Returns
-------
bool
True if tmux meets minimum required version.
Raises
------
libtmux.exc.VersionTooLow
tmux version below minimum required for libtmux
Notes
-----
.. versionchanged:: 0.7.0
No longer returns version, returns True or False
.. versionchanged:: 0.1.7
Versions will now remove trailing letters per `Issue 55`_.
.. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55.
"""
if get_version() < LooseVersion(TMUX_MIN_VERSION):
if raises:
raise exc.VersionTooLow(
'libtmux only supports tmux %s and greater. This system'
' has %s installed. Upgrade your tmux to use libtmux.'
% (TMUX_MIN_VERSION, get_version())
)
else:
return False
return True
|
[
"def",
"has_minimum_version",
"(",
"raises",
"=",
"True",
")",
":",
"if",
"get_version",
"(",
")",
"<",
"LooseVersion",
"(",
"TMUX_MIN_VERSION",
")",
":",
"if",
"raises",
":",
"raise",
"exc",
".",
"VersionTooLow",
"(",
"'libtmux only supports tmux %s and greater. This system'",
"' has %s installed. Upgrade your tmux to use libtmux.'",
"%",
"(",
"TMUX_MIN_VERSION",
",",
"get_version",
"(",
")",
")",
")",
"else",
":",
"return",
"False",
"return",
"True"
] |
Return if tmux meets version requirement. Version >1.8 or above.
Parameters
----------
raises : bool
raise exception if below minimum version requirement
Returns
-------
bool
True if tmux meets minimum required version.
Raises
------
libtmux.exc.VersionTooLow
tmux version below minimum required for libtmux
Notes
-----
.. versionchanged:: 0.7.0
No longer returns version, returns True or False
.. versionchanged:: 0.1.7
Versions will now remove trailing letters per `Issue 55`_.
.. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55.
|
[
"Return",
"if",
"tmux",
"meets",
"version",
"requirement",
".",
"Version",
">",
"1",
".",
"8",
"or",
"above",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L564-L603
|
8,987
|
tmux-python/libtmux
|
libtmux/common.py
|
session_check_name
|
def session_check_name(session_name):
"""
Raises exception session name invalid, modeled after tmux function.
tmux(1) session names may not be empty, or include periods or colons.
These delimiters are reserved for noting session, window and pane.
Parameters
----------
session_name : str
Name of session.
Raises
------
:exc:`exc.BadSessionName`
Invalid session name.
"""
if not session_name or len(session_name) == 0:
raise exc.BadSessionName("tmux session names may not be empty.")
elif '.' in session_name:
raise exc.BadSessionName(
"tmux session name \"%s\" may not contain periods.", session_name
)
elif ':' in session_name:
raise exc.BadSessionName(
"tmux session name \"%s\" may not contain colons.", session_name
)
|
python
|
def session_check_name(session_name):
"""
Raises exception session name invalid, modeled after tmux function.
tmux(1) session names may not be empty, or include periods or colons.
These delimiters are reserved for noting session, window and pane.
Parameters
----------
session_name : str
Name of session.
Raises
------
:exc:`exc.BadSessionName`
Invalid session name.
"""
if not session_name or len(session_name) == 0:
raise exc.BadSessionName("tmux session names may not be empty.")
elif '.' in session_name:
raise exc.BadSessionName(
"tmux session name \"%s\" may not contain periods.", session_name
)
elif ':' in session_name:
raise exc.BadSessionName(
"tmux session name \"%s\" may not contain colons.", session_name
)
|
[
"def",
"session_check_name",
"(",
"session_name",
")",
":",
"if",
"not",
"session_name",
"or",
"len",
"(",
"session_name",
")",
"==",
"0",
":",
"raise",
"exc",
".",
"BadSessionName",
"(",
"\"tmux session names may not be empty.\"",
")",
"elif",
"'.'",
"in",
"session_name",
":",
"raise",
"exc",
".",
"BadSessionName",
"(",
"\"tmux session name \\\"%s\\\" may not contain periods.\"",
",",
"session_name",
")",
"elif",
"':'",
"in",
"session_name",
":",
"raise",
"exc",
".",
"BadSessionName",
"(",
"\"tmux session name \\\"%s\\\" may not contain colons.\"",
",",
"session_name",
")"
] |
Raises exception session name invalid, modeled after tmux function.
tmux(1) session names may not be empty, or include periods or colons.
These delimiters are reserved for noting session, window and pane.
Parameters
----------
session_name : str
Name of session.
Raises
------
:exc:`exc.BadSessionName`
Invalid session name.
|
[
"Raises",
"exception",
"session",
"name",
"invalid",
"modeled",
"after",
"tmux",
"function",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L606-L632
|
8,988
|
tmux-python/libtmux
|
libtmux/common.py
|
handle_option_error
|
def handle_option_error(error):
"""Raises exception if error in option command found.
Purpose: As of tmux 2.4, there are now 3 different types of option errors:
- unknown option
- invalid option
- ambiguous option
Before 2.4, unknown option was the user.
All errors raised will have the base error of :exc:`exc.OptionError`. So to
catch any option error, use ``except exc.OptionError``.
Parameters
----------
error : str
Error response from subprocess call.
Raises
------
:exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`,
:exc:`exc.AmbiguousOption`
"""
if 'unknown option' in error:
raise exc.UnknownOption(error)
elif 'invalid option' in error:
raise exc.InvalidOption(error)
elif 'ambiguous option' in error:
raise exc.AmbiguousOption(error)
else:
raise exc.OptionError(error)
|
python
|
def handle_option_error(error):
"""Raises exception if error in option command found.
Purpose: As of tmux 2.4, there are now 3 different types of option errors:
- unknown option
- invalid option
- ambiguous option
Before 2.4, unknown option was the user.
All errors raised will have the base error of :exc:`exc.OptionError`. So to
catch any option error, use ``except exc.OptionError``.
Parameters
----------
error : str
Error response from subprocess call.
Raises
------
:exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`,
:exc:`exc.AmbiguousOption`
"""
if 'unknown option' in error:
raise exc.UnknownOption(error)
elif 'invalid option' in error:
raise exc.InvalidOption(error)
elif 'ambiguous option' in error:
raise exc.AmbiguousOption(error)
else:
raise exc.OptionError(error)
|
[
"def",
"handle_option_error",
"(",
"error",
")",
":",
"if",
"'unknown option'",
"in",
"error",
":",
"raise",
"exc",
".",
"UnknownOption",
"(",
"error",
")",
"elif",
"'invalid option'",
"in",
"error",
":",
"raise",
"exc",
".",
"InvalidOption",
"(",
"error",
")",
"elif",
"'ambiguous option'",
"in",
"error",
":",
"raise",
"exc",
".",
"AmbiguousOption",
"(",
"error",
")",
"else",
":",
"raise",
"exc",
".",
"OptionError",
"(",
"error",
")"
] |
Raises exception if error in option command found.
Purpose: As of tmux 2.4, there are now 3 different types of option errors:
- unknown option
- invalid option
- ambiguous option
Before 2.4, unknown option was the user.
All errors raised will have the base error of :exc:`exc.OptionError`. So to
catch any option error, use ``except exc.OptionError``.
Parameters
----------
error : str
Error response from subprocess call.
Raises
------
:exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`,
:exc:`exc.AmbiguousOption`
|
[
"Raises",
"exception",
"if",
"error",
"in",
"option",
"command",
"found",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L635-L666
|
8,989
|
tmux-python/libtmux
|
libtmux/common.py
|
TmuxRelationalObject.where
|
def where(self, attrs, first=False):
"""
Return objects matching child objects properties.
Parameters
----------
attrs : dict
tmux properties to match values of
Returns
-------
list
"""
# from https://github.com/serkanyersen/underscore.py
def by(val, *args):
for key, value in attrs.items():
try:
if attrs[key] != val[key]:
return False
except KeyError:
return False
return True
if first:
return list(filter(by, self.children))[0]
else:
return list(filter(by, self.children))
|
python
|
def where(self, attrs, first=False):
"""
Return objects matching child objects properties.
Parameters
----------
attrs : dict
tmux properties to match values of
Returns
-------
list
"""
# from https://github.com/serkanyersen/underscore.py
def by(val, *args):
for key, value in attrs.items():
try:
if attrs[key] != val[key]:
return False
except KeyError:
return False
return True
if first:
return list(filter(by, self.children))[0]
else:
return list(filter(by, self.children))
|
[
"def",
"where",
"(",
"self",
",",
"attrs",
",",
"first",
"=",
"False",
")",
":",
"# from https://github.com/serkanyersen/underscore.py",
"def",
"by",
"(",
"val",
",",
"*",
"args",
")",
":",
"for",
"key",
",",
"value",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"attrs",
"[",
"key",
"]",
"!=",
"val",
"[",
"key",
"]",
":",
"return",
"False",
"except",
"KeyError",
":",
"return",
"False",
"return",
"True",
"if",
"first",
":",
"return",
"list",
"(",
"filter",
"(",
"by",
",",
"self",
".",
"children",
")",
")",
"[",
"0",
"]",
"else",
":",
"return",
"list",
"(",
"filter",
"(",
"by",
",",
"self",
".",
"children",
")",
")"
] |
Return objects matching child objects properties.
Parameters
----------
attrs : dict
tmux properties to match values of
Returns
-------
list
|
[
"Return",
"objects",
"matching",
"child",
"objects",
"properties",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L324-L351
|
8,990
|
tmux-python/libtmux
|
libtmux/common.py
|
TmuxRelationalObject.get_by_id
|
def get_by_id(self, id):
"""
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbone.js: http://backbonejs.org/
.. _.get(): http://backbonejs.org/#Collection-get
"""
for child in self.children:
if child[self.child_id_attribute] == id:
return child
else:
continue
return None
|
python
|
def get_by_id(self, id):
"""
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbone.js: http://backbonejs.org/
.. _.get(): http://backbonejs.org/#Collection-get
"""
for child in self.children:
if child[self.child_id_attribute] == id:
return child
else:
continue
return None
|
[
"def",
"get_by_id",
"(",
"self",
",",
"id",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"child",
"[",
"self",
".",
"child_id_attribute",
"]",
"==",
"id",
":",
"return",
"child",
"else",
":",
"continue",
"return",
"None"
] |
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbone.js: http://backbonejs.org/
.. _.get(): http://backbonejs.org/#Collection-get
|
[
"Return",
"object",
"based",
"on",
"child_id_attribute",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L353-L378
|
8,991
|
tmux-python/libtmux
|
libtmux/window.py
|
Window.select_window
|
def select_window(self):
"""
Select window. Return ``self``.
To select a window object asynchrously. If a ``window`` object exists
and is no longer longer the current window, ``w.select_window()``
will make ``w`` the current window.
Returns
-------
:class:`Window`
"""
target = ('%s:%s' % (self.get('session_id'), self.index),)
return self.session.select_window(target)
|
python
|
def select_window(self):
"""
Select window. Return ``self``.
To select a window object asynchrously. If a ``window`` object exists
and is no longer longer the current window, ``w.select_window()``
will make ``w`` the current window.
Returns
-------
:class:`Window`
"""
target = ('%s:%s' % (self.get('session_id'), self.index),)
return self.session.select_window(target)
|
[
"def",
"select_window",
"(",
"self",
")",
":",
"target",
"=",
"(",
"'%s:%s'",
"%",
"(",
"self",
".",
"get",
"(",
"'session_id'",
")",
",",
"self",
".",
"index",
")",
",",
")",
"return",
"self",
".",
"session",
".",
"select_window",
"(",
"target",
")"
] |
Select window. Return ``self``.
To select a window object asynchrously. If a ``window`` object exists
and is no longer longer the current window, ``w.select_window()``
will make ``w`` the current window.
Returns
-------
:class:`Window`
|
[
"Select",
"window",
".",
"Return",
"self",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/window.py#L341-L354
|
8,992
|
tmux-python/libtmux
|
libtmux/server.py
|
Server.cmd
|
def cmd(self, *args, **kwargs):
"""
Execute tmux command and return output.
Returns
-------
:class:`common.tmux_cmd`
Notes
-----
.. versionchanged:: 0.8
Renamed from ``.tmux`` to ``.cmd``.
"""
args = list(args)
if self.socket_name:
args.insert(0, '-L{0}'.format(self.socket_name))
if self.socket_path:
args.insert(0, '-S{0}'.format(self.socket_path))
if self.config_file:
args.insert(0, '-f{0}'.format(self.config_file))
if self.colors:
if self.colors == 256:
args.insert(0, '-2')
elif self.colors == 88:
args.insert(0, '-8')
else:
raise ValueError('Server.colors must equal 88 or 256')
return tmux_cmd(*args, **kwargs)
|
python
|
def cmd(self, *args, **kwargs):
"""
Execute tmux command and return output.
Returns
-------
:class:`common.tmux_cmd`
Notes
-----
.. versionchanged:: 0.8
Renamed from ``.tmux`` to ``.cmd``.
"""
args = list(args)
if self.socket_name:
args.insert(0, '-L{0}'.format(self.socket_name))
if self.socket_path:
args.insert(0, '-S{0}'.format(self.socket_path))
if self.config_file:
args.insert(0, '-f{0}'.format(self.config_file))
if self.colors:
if self.colors == 256:
args.insert(0, '-2')
elif self.colors == 88:
args.insert(0, '-8')
else:
raise ValueError('Server.colors must equal 88 or 256')
return tmux_cmd(*args, **kwargs)
|
[
"def",
"cmd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"if",
"self",
".",
"socket_name",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'-L{0}'",
".",
"format",
"(",
"self",
".",
"socket_name",
")",
")",
"if",
"self",
".",
"socket_path",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'-S{0}'",
".",
"format",
"(",
"self",
".",
"socket_path",
")",
")",
"if",
"self",
".",
"config_file",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'-f{0}'",
".",
"format",
"(",
"self",
".",
"config_file",
")",
")",
"if",
"self",
".",
"colors",
":",
"if",
"self",
".",
"colors",
"==",
"256",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'-2'",
")",
"elif",
"self",
".",
"colors",
"==",
"88",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'-8'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Server.colors must equal 88 or 256'",
")",
"return",
"tmux_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Execute tmux command and return output.
Returns
-------
:class:`common.tmux_cmd`
Notes
-----
.. versionchanged:: 0.8
Renamed from ``.tmux`` to ``.cmd``.
|
[
"Execute",
"tmux",
"command",
"and",
"return",
"output",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/server.py#L99-L129
|
8,993
|
tmux-python/libtmux
|
libtmux/session.py
|
Session.switch_client
|
def switch_client(self):
"""
Switch client to this session.
Raises
------
:exc:`exc.LibTmuxException`
"""
proc = self.cmd('switch-client', '-t%s' % self.id)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr)
|
python
|
def switch_client(self):
"""
Switch client to this session.
Raises
------
:exc:`exc.LibTmuxException`
"""
proc = self.cmd('switch-client', '-t%s' % self.id)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr)
|
[
"def",
"switch_client",
"(",
"self",
")",
":",
"proc",
"=",
"self",
".",
"cmd",
"(",
"'switch-client'",
",",
"'-t%s'",
"%",
"self",
".",
"id",
")",
"if",
"proc",
".",
"stderr",
":",
"raise",
"exc",
".",
"LibTmuxException",
"(",
"proc",
".",
"stderr",
")"
] |
Switch client to this session.
Raises
------
:exc:`exc.LibTmuxException`
|
[
"Switch",
"client",
"to",
"this",
"session",
"."
] |
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
|
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/session.py#L122-L134
|
8,994
|
Yubico/yubikey-manager
|
ykman/cli/opgp.py
|
openpgp
|
def openpgp(ctx):
"""
Manage OpenPGP Application.
Examples:
\b
Set the retries for PIN, Reset Code and Admin PIN to 10:
$ ykman openpgp set-retries 10 10 10
\b
Require touch to use the authentication key:
$ ykman openpgp touch aut on
"""
try:
ctx.obj['controller'] = OpgpController(ctx.obj['dev'].driver)
except APDUError as e:
if e.sw == SW.NOT_FOUND:
ctx.fail("The OpenPGP application can't be found on this "
'YubiKey.')
logger.debug('Failed to load OpenPGP Application', exc_info=e)
ctx.fail('Failed to load OpenPGP Application')
|
python
|
def openpgp(ctx):
"""
Manage OpenPGP Application.
Examples:
\b
Set the retries for PIN, Reset Code and Admin PIN to 10:
$ ykman openpgp set-retries 10 10 10
\b
Require touch to use the authentication key:
$ ykman openpgp touch aut on
"""
try:
ctx.obj['controller'] = OpgpController(ctx.obj['dev'].driver)
except APDUError as e:
if e.sw == SW.NOT_FOUND:
ctx.fail("The OpenPGP application can't be found on this "
'YubiKey.')
logger.debug('Failed to load OpenPGP Application', exc_info=e)
ctx.fail('Failed to load OpenPGP Application')
|
[
"def",
"openpgp",
"(",
"ctx",
")",
":",
"try",
":",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"=",
"OpgpController",
"(",
"ctx",
".",
"obj",
"[",
"'dev'",
"]",
".",
"driver",
")",
"except",
"APDUError",
"as",
"e",
":",
"if",
"e",
".",
"sw",
"==",
"SW",
".",
"NOT_FOUND",
":",
"ctx",
".",
"fail",
"(",
"\"The OpenPGP application can't be found on this \"",
"'YubiKey.'",
")",
"logger",
".",
"debug",
"(",
"'Failed to load OpenPGP Application'",
",",
"exc_info",
"=",
"e",
")",
"ctx",
".",
"fail",
"(",
"'Failed to load OpenPGP Application'",
")"
] |
Manage OpenPGP Application.
Examples:
\b
Set the retries for PIN, Reset Code and Admin PIN to 10:
$ ykman openpgp set-retries 10 10 10
\b
Require touch to use the authentication key:
$ ykman openpgp touch aut on
|
[
"Manage",
"OpenPGP",
"Application",
"."
] |
3ac27bc59ae76a59db9d09a530494add2edbbabf
|
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L83-L104
|
8,995
|
Yubico/yubikey-manager
|
ykman/cli/opgp.py
|
info
|
def info(ctx):
"""
Display status of OpenPGP application.
"""
controller = ctx.obj['controller']
click.echo('OpenPGP version: %d.%d.%d' % controller.version)
retries = controller.get_remaining_pin_tries()
click.echo('PIN tries remaining: {}'.format(retries.pin))
click.echo('Reset code tries remaining: {}'.format(retries.reset))
click.echo('Admin PIN tries remaining: {}'.format(retries.admin))
click.echo()
click.echo('Touch policies')
click.echo(
'Signature key {.name}'.format(
controller.get_touch(KEY_SLOT.SIGNATURE)))
click.echo(
'Encryption key {.name}'.format(
controller.get_touch(KEY_SLOT.ENCRYPTION)))
click.echo(
'Authentication key {.name}'.format(
controller.get_touch(KEY_SLOT.AUTHENTICATION)))
|
python
|
def info(ctx):
"""
Display status of OpenPGP application.
"""
controller = ctx.obj['controller']
click.echo('OpenPGP version: %d.%d.%d' % controller.version)
retries = controller.get_remaining_pin_tries()
click.echo('PIN tries remaining: {}'.format(retries.pin))
click.echo('Reset code tries remaining: {}'.format(retries.reset))
click.echo('Admin PIN tries remaining: {}'.format(retries.admin))
click.echo()
click.echo('Touch policies')
click.echo(
'Signature key {.name}'.format(
controller.get_touch(KEY_SLOT.SIGNATURE)))
click.echo(
'Encryption key {.name}'.format(
controller.get_touch(KEY_SLOT.ENCRYPTION)))
click.echo(
'Authentication key {.name}'.format(
controller.get_touch(KEY_SLOT.AUTHENTICATION)))
|
[
"def",
"info",
"(",
"ctx",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"click",
".",
"echo",
"(",
"'OpenPGP version: %d.%d.%d'",
"%",
"controller",
".",
"version",
")",
"retries",
"=",
"controller",
".",
"get_remaining_pin_tries",
"(",
")",
"click",
".",
"echo",
"(",
"'PIN tries remaining: {}'",
".",
"format",
"(",
"retries",
".",
"pin",
")",
")",
"click",
".",
"echo",
"(",
"'Reset code tries remaining: {}'",
".",
"format",
"(",
"retries",
".",
"reset",
")",
")",
"click",
".",
"echo",
"(",
"'Admin PIN tries remaining: {}'",
".",
"format",
"(",
"retries",
".",
"admin",
")",
")",
"click",
".",
"echo",
"(",
")",
"click",
".",
"echo",
"(",
"'Touch policies'",
")",
"click",
".",
"echo",
"(",
"'Signature key {.name}'",
".",
"format",
"(",
"controller",
".",
"get_touch",
"(",
"KEY_SLOT",
".",
"SIGNATURE",
")",
")",
")",
"click",
".",
"echo",
"(",
"'Encryption key {.name}'",
".",
"format",
"(",
"controller",
".",
"get_touch",
"(",
"KEY_SLOT",
".",
"ENCRYPTION",
")",
")",
")",
"click",
".",
"echo",
"(",
"'Authentication key {.name}'",
".",
"format",
"(",
"controller",
".",
"get_touch",
"(",
"KEY_SLOT",
".",
"AUTHENTICATION",
")",
")",
")"
] |
Display status of OpenPGP application.
|
[
"Display",
"status",
"of",
"OpenPGP",
"application",
"."
] |
3ac27bc59ae76a59db9d09a530494add2edbbabf
|
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L109-L129
|
8,996
|
Yubico/yubikey-manager
|
ykman/cli/opgp.py
|
reset
|
def reset(ctx):
"""
Reset OpenPGP application.
This action will wipe all OpenPGP data, and set all PINs to their default
values.
"""
click.echo("Resetting OpenPGP data, don't remove your YubiKey...")
ctx.obj['controller'].reset()
click.echo('Success! All data has been cleared and default PINs are set.')
echo_default_pins()
|
python
|
def reset(ctx):
"""
Reset OpenPGP application.
This action will wipe all OpenPGP data, and set all PINs to their default
values.
"""
click.echo("Resetting OpenPGP data, don't remove your YubiKey...")
ctx.obj['controller'].reset()
click.echo('Success! All data has been cleared and default PINs are set.')
echo_default_pins()
|
[
"def",
"reset",
"(",
"ctx",
")",
":",
"click",
".",
"echo",
"(",
"\"Resetting OpenPGP data, don't remove your YubiKey...\"",
")",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
".",
"reset",
"(",
")",
"click",
".",
"echo",
"(",
"'Success! All data has been cleared and default PINs are set.'",
")",
"echo_default_pins",
"(",
")"
] |
Reset OpenPGP application.
This action will wipe all OpenPGP data, and set all PINs to their default
values.
|
[
"Reset",
"OpenPGP",
"application",
"."
] |
3ac27bc59ae76a59db9d09a530494add2edbbabf
|
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L137-L147
|
8,997
|
Yubico/yubikey-manager
|
ykman/cli/opgp.py
|
touch
|
def touch(ctx, key, policy, admin_pin, force):
"""
Manage touch policy for OpenPGP keys.
\b
KEY Key slot to set (sig, enc or aut).
POLICY Touch policy to set (on, off or fixed).
"""
controller = ctx.obj['controller']
old_policy = controller.get_touch(key)
if old_policy == TOUCH_MODE.FIXED:
ctx.fail('A FIXED policy cannot be changed!')
force or click.confirm('Set touch policy of {.name} key to {.name}?'.format(
key, policy), abort=True, err=True)
if admin_pin is None:
admin_pin = click.prompt('Enter admin PIN', hide_input=True, err=True)
controller.set_touch(key, policy, admin_pin.encode('utf8'))
|
python
|
def touch(ctx, key, policy, admin_pin, force):
"""
Manage touch policy for OpenPGP keys.
\b
KEY Key slot to set (sig, enc or aut).
POLICY Touch policy to set (on, off or fixed).
"""
controller = ctx.obj['controller']
old_policy = controller.get_touch(key)
if old_policy == TOUCH_MODE.FIXED:
ctx.fail('A FIXED policy cannot be changed!')
force or click.confirm('Set touch policy of {.name} key to {.name}?'.format(
key, policy), abort=True, err=True)
if admin_pin is None:
admin_pin = click.prompt('Enter admin PIN', hide_input=True, err=True)
controller.set_touch(key, policy, admin_pin.encode('utf8'))
|
[
"def",
"touch",
"(",
"ctx",
",",
"key",
",",
"policy",
",",
"admin_pin",
",",
"force",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"old_policy",
"=",
"controller",
".",
"get_touch",
"(",
"key",
")",
"if",
"old_policy",
"==",
"TOUCH_MODE",
".",
"FIXED",
":",
"ctx",
".",
"fail",
"(",
"'A FIXED policy cannot be changed!'",
")",
"force",
"or",
"click",
".",
"confirm",
"(",
"'Set touch policy of {.name} key to {.name}?'",
".",
"format",
"(",
"key",
",",
"policy",
")",
",",
"abort",
"=",
"True",
",",
"err",
"=",
"True",
")",
"if",
"admin_pin",
"is",
"None",
":",
"admin_pin",
"=",
"click",
".",
"prompt",
"(",
"'Enter admin PIN'",
",",
"hide_input",
"=",
"True",
",",
"err",
"=",
"True",
")",
"controller",
".",
"set_touch",
"(",
"key",
",",
"policy",
",",
"admin_pin",
".",
"encode",
"(",
"'utf8'",
")",
")"
] |
Manage touch policy for OpenPGP keys.
\b
KEY Key slot to set (sig, enc or aut).
POLICY Touch policy to set (on, off or fixed).
|
[
"Manage",
"touch",
"policy",
"for",
"OpenPGP",
"keys",
"."
] |
3ac27bc59ae76a59db9d09a530494add2edbbabf
|
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L165-L183
|
8,998
|
Yubico/yubikey-manager
|
ykman/cli/opgp.py
|
set_pin_retries
|
def set_pin_retries(ctx, pw_attempts, admin_pin, force):
"""
Manage pin-retries.
Sets the number of attempts available before locking for each PIN.
PW_ATTEMPTS should be three integer values corresponding to the number of
attempts for the PIN, Reset Code, and Admin PIN, respectively.
"""
controller = ctx.obj['controller']
resets_pins = controller.version < (4, 0, 0)
if resets_pins:
click.echo('WARNING: Setting PIN retries will reset the values for all '
'3 PINs!')
force or click.confirm('Set PIN retry counters to: {} {} {}?'.format(
*pw_attempts), abort=True, err=True)
controller.set_pin_retries(*(pw_attempts + (admin_pin.encode('utf8'),)))
click.echo('PIN retries successfully set.')
if resets_pins:
click.echo('Default PINs are set.')
echo_default_pins()
|
python
|
def set_pin_retries(ctx, pw_attempts, admin_pin, force):
"""
Manage pin-retries.
Sets the number of attempts available before locking for each PIN.
PW_ATTEMPTS should be three integer values corresponding to the number of
attempts for the PIN, Reset Code, and Admin PIN, respectively.
"""
controller = ctx.obj['controller']
resets_pins = controller.version < (4, 0, 0)
if resets_pins:
click.echo('WARNING: Setting PIN retries will reset the values for all '
'3 PINs!')
force or click.confirm('Set PIN retry counters to: {} {} {}?'.format(
*pw_attempts), abort=True, err=True)
controller.set_pin_retries(*(pw_attempts + (admin_pin.encode('utf8'),)))
click.echo('PIN retries successfully set.')
if resets_pins:
click.echo('Default PINs are set.')
echo_default_pins()
|
[
"def",
"set_pin_retries",
"(",
"ctx",
",",
"pw_attempts",
",",
"admin_pin",
",",
"force",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"resets_pins",
"=",
"controller",
".",
"version",
"<",
"(",
"4",
",",
"0",
",",
"0",
")",
"if",
"resets_pins",
":",
"click",
".",
"echo",
"(",
"'WARNING: Setting PIN retries will reset the values for all '",
"'3 PINs!'",
")",
"force",
"or",
"click",
".",
"confirm",
"(",
"'Set PIN retry counters to: {} {} {}?'",
".",
"format",
"(",
"*",
"pw_attempts",
")",
",",
"abort",
"=",
"True",
",",
"err",
"=",
"True",
")",
"controller",
".",
"set_pin_retries",
"(",
"*",
"(",
"pw_attempts",
"+",
"(",
"admin_pin",
".",
"encode",
"(",
"'utf8'",
")",
",",
")",
")",
")",
"click",
".",
"echo",
"(",
"'PIN retries successfully set.'",
")",
"if",
"resets_pins",
":",
"click",
".",
"echo",
"(",
"'Default PINs are set.'",
")",
"echo_default_pins",
"(",
")"
] |
Manage pin-retries.
Sets the number of attempts available before locking for each PIN.
PW_ATTEMPTS should be three integer values corresponding to the number of
attempts for the PIN, Reset Code, and Admin PIN, respectively.
|
[
"Manage",
"pin",
"-",
"retries",
"."
] |
3ac27bc59ae76a59db9d09a530494add2edbbabf
|
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L192-L212
|
8,999
|
Yubico/yubikey-manager
|
ykman/cli/piv.py
|
piv
|
def piv(ctx):
"""
Manage PIV Application.
Examples:
\b
Generate an ECC P-256 private key and a self-signed certificate in
slot 9a:
$ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem
$ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem
\b
Change the PIN from 123456 to 654321:
$ ykman piv change-pin --pin 123456 --new-pin 654321
\b
Reset all PIV data and restore default settings:
$ ykman piv reset
"""
try:
ctx.obj['controller'] = PivController(ctx.obj['dev'].driver)
except APDUError as e:
if e.sw == SW.NOT_FOUND:
ctx.fail("The PIV application can't be found on this YubiKey.")
raise
|
python
|
def piv(ctx):
"""
Manage PIV Application.
Examples:
\b
Generate an ECC P-256 private key and a self-signed certificate in
slot 9a:
$ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem
$ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem
\b
Change the PIN from 123456 to 654321:
$ ykman piv change-pin --pin 123456 --new-pin 654321
\b
Reset all PIV data and restore default settings:
$ ykman piv reset
"""
try:
ctx.obj['controller'] = PivController(ctx.obj['dev'].driver)
except APDUError as e:
if e.sw == SW.NOT_FOUND:
ctx.fail("The PIV application can't be found on this YubiKey.")
raise
|
[
"def",
"piv",
"(",
"ctx",
")",
":",
"try",
":",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"=",
"PivController",
"(",
"ctx",
".",
"obj",
"[",
"'dev'",
"]",
".",
"driver",
")",
"except",
"APDUError",
"as",
"e",
":",
"if",
"e",
".",
"sw",
"==",
"SW",
".",
"NOT_FOUND",
":",
"ctx",
".",
"fail",
"(",
"\"The PIV application can't be found on this YubiKey.\"",
")",
"raise"
] |
Manage PIV Application.
Examples:
\b
Generate an ECC P-256 private key and a self-signed certificate in
slot 9a:
$ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem
$ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem
\b
Change the PIN from 123456 to 654321:
$ ykman piv change-pin --pin 123456 --new-pin 654321
\b
Reset all PIV data and restore default settings:
$ ykman piv reset
|
[
"Manage",
"PIV",
"Application",
"."
] |
3ac27bc59ae76a59db9d09a530494add2edbbabf
|
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L95-L120
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.