partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
raise_hostname
Raises a TLSVerificationError due to a hostname mismatch :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError
oscrypto/_tls.py
def raise_hostname(certificate, hostname): """ Raises a TLSVerificationError due to a hostname mismatch :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError """ is_ip = re.match('^\\d+\\.\\d+\\.\\d+\\.\\d+$', hostname) or hostname.find(':') != -1 if is_ip: hostname_type = 'IP address %s' % hostname else: hostname_type = 'domain name %s' % hostname message = 'Server certificate verification failed - %s does not match' % hostname_type valid_ips = ', '.join(certificate.valid_ips) valid_domains = ', '.join(certificate.valid_domains) if valid_domains: message += ' valid domains: %s' % valid_domains if valid_domains and valid_ips: message += ' or' if valid_ips: message += ' valid IP addresses: %s' % valid_ips raise TLSVerificationError(message, certificate)
def raise_hostname(certificate, hostname): """ Raises a TLSVerificationError due to a hostname mismatch :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError """ is_ip = re.match('^\\d+\\.\\d+\\.\\d+\\.\\d+$', hostname) or hostname.find(':') != -1 if is_ip: hostname_type = 'IP address %s' % hostname else: hostname_type = 'domain name %s' % hostname message = 'Server certificate verification failed - %s does not match' % hostname_type valid_ips = ', '.join(certificate.valid_ips) valid_domains = ', '.join(certificate.valid_domains) if valid_domains: message += ' valid domains: %s' % valid_domains if valid_domains and valid_ips: message += ' or' if valid_ips: message += ' valid IP addresses: %s' % valid_ips raise TLSVerificationError(message, certificate)
[ "Raises", "a", "TLSVerificationError", "due", "to", "a", "hostname", "mismatch" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L352-L377
[ "def", "raise_hostname", "(", "certificate", ",", "hostname", ")", ":", "is_ip", "=", "re", ".", "match", "(", "'^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$'", ",", "hostname", ")", "or", "hostname", ".", "find", "(", "':'", ")", "!=", "-", "1", "if", "is_ip", ":", "hostname_type", "=", "'IP address %s'", "%", "hostname", "else", ":", "hostname_type", "=", "'domain name %s'", "%", "hostname", "message", "=", "'Server certificate verification failed - %s does not match'", "%", "hostname_type", "valid_ips", "=", "', '", ".", "join", "(", "certificate", ".", "valid_ips", ")", "valid_domains", "=", "', '", ".", "join", "(", "certificate", ".", "valid_domains", ")", "if", "valid_domains", ":", "message", "+=", "' valid domains: %s'", "%", "valid_domains", "if", "valid_domains", "and", "valid_ips", ":", "message", "+=", "' or'", "if", "valid_ips", ":", "message", "+=", "' valid IP addresses: %s'", "%", "valid_ips", "raise", "TLSVerificationError", "(", "message", ",", "certificate", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
raise_expired_not_yet_valid
Raises a TLSVerificationError due to certificate being expired, or not yet being valid :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError
oscrypto/_tls.py
def raise_expired_not_yet_valid(certificate): """ Raises a TLSVerificationError due to certificate being expired, or not yet being valid :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError """ validity = certificate['tbs_certificate']['validity'] not_after = validity['not_after'].native not_before = validity['not_before'].native now = datetime.now(timezone.utc) if not_before > now: formatted_before = not_before.strftime('%Y-%m-%d %H:%M:%SZ') message = 'Server certificate verification failed - certificate not valid until %s' % formatted_before elif not_after < now: formatted_after = not_after.strftime('%Y-%m-%d %H:%M:%SZ') message = 'Server certificate verification failed - certificate expired %s' % formatted_after raise TLSVerificationError(message, certificate)
def raise_expired_not_yet_valid(certificate): """ Raises a TLSVerificationError due to certificate being expired, or not yet being valid :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError """ validity = certificate['tbs_certificate']['validity'] not_after = validity['not_after'].native not_before = validity['not_before'].native now = datetime.now(timezone.utc) if not_before > now: formatted_before = not_before.strftime('%Y-%m-%d %H:%M:%SZ') message = 'Server certificate verification failed - certificate not valid until %s' % formatted_before elif not_after < now: formatted_after = not_after.strftime('%Y-%m-%d %H:%M:%SZ') message = 'Server certificate verification failed - certificate expired %s' % formatted_after raise TLSVerificationError(message, certificate)
[ "Raises", "a", "TLSVerificationError", "due", "to", "certificate", "being", "expired", "or", "not", "yet", "being", "valid" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L470-L495
[ "def", "raise_expired_not_yet_valid", "(", "certificate", ")", ":", "validity", "=", "certificate", "[", "'tbs_certificate'", "]", "[", "'validity'", "]", "not_after", "=", "validity", "[", "'not_after'", "]", ".", "native", "not_before", "=", "validity", "[", "'not_before'", "]", ".", "native", "now", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "if", "not_before", ">", "now", ":", "formatted_before", "=", "not_before", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%SZ'", ")", "message", "=", "'Server certificate verification failed - certificate not valid until %s'", "%", "formatted_before", "elif", "not_after", "<", "now", ":", "formatted_after", "=", "not_after", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%SZ'", ")", "message", "=", "'Server certificate verification failed - certificate expired %s'", "%", "formatted_after", "raise", "TLSVerificationError", "(", "message", ",", "certificate", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
detect_other_protocol
Looks at the server handshake bytes to try and detect a different protocol :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None, or a unicode string of "ftp", "http", "imap", "pop3", "smtp"
oscrypto/_tls.py
def detect_other_protocol(server_handshake_bytes): """ Looks at the server handshake bytes to try and detect a different protocol :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None, or a unicode string of "ftp", "http", "imap", "pop3", "smtp" """ if server_handshake_bytes[0:5] == b'HTTP/': return 'HTTP' if server_handshake_bytes[0:4] == b'220 ': if re.match(b'^[^\r\n]*ftp', server_handshake_bytes, re.I): return 'FTP' else: return 'SMTP' if server_handshake_bytes[0:4] == b'220-': return 'FTP' if server_handshake_bytes[0:4] == b'+OK ': return 'POP3' if server_handshake_bytes[0:4] == b'* OK' or server_handshake_bytes[0:9] == b'* PREAUTH': return 'IMAP' return None
def detect_other_protocol(server_handshake_bytes): """ Looks at the server handshake bytes to try and detect a different protocol :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None, or a unicode string of "ftp", "http", "imap", "pop3", "smtp" """ if server_handshake_bytes[0:5] == b'HTTP/': return 'HTTP' if server_handshake_bytes[0:4] == b'220 ': if re.match(b'^[^\r\n]*ftp', server_handshake_bytes, re.I): return 'FTP' else: return 'SMTP' if server_handshake_bytes[0:4] == b'220-': return 'FTP' if server_handshake_bytes[0:4] == b'+OK ': return 'POP3' if server_handshake_bytes[0:4] == b'* OK' or server_handshake_bytes[0:9] == b'* PREAUTH': return 'IMAP' return None
[ "Looks", "at", "the", "server", "handshake", "bytes", "to", "try", "and", "detect", "a", "different", "protocol" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L561-L590
[ "def", "detect_other_protocol", "(", "server_handshake_bytes", ")", ":", "if", "server_handshake_bytes", "[", "0", ":", "5", "]", "==", "b'HTTP/'", ":", "return", "'HTTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'220 '", ":", "if", "re", ".", "match", "(", "b'^[^\\r\\n]*ftp'", ",", "server_handshake_bytes", ",", "re", ".", "I", ")", ":", "return", "'FTP'", "else", ":", "return", "'SMTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'220-'", ":", "return", "'FTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'+OK '", ":", "return", "'POP3'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'* OK'", "or", "server_handshake_bytes", "[", "0", ":", "9", "]", "==", "b'* PREAUTH'", ":", "return", "'IMAP'", "return", "None" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
constant_compare
Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal
oscrypto/util.py
def constant_compare(a, b): """ Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal """ if not isinstance(a, byte_cls): raise TypeError(pretty_message( ''' a must be a byte string, not %s ''', type_name(a) )) if not isinstance(b, byte_cls): raise TypeError(pretty_message( ''' b must be a byte string, not %s ''', type_name(b) )) if len(a) != len(b): return False if sys.version_info < (3,): a = [ord(char) for char in a] b = [ord(char) for char in b] result = 0 for x, y in zip(a, b): result |= x ^ y return result == 0
def constant_compare(a, b): """ Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal """ if not isinstance(a, byte_cls): raise TypeError(pretty_message( ''' a must be a byte string, not %s ''', type_name(a) )) if not isinstance(b, byte_cls): raise TypeError(pretty_message( ''' b must be a byte string, not %s ''', type_name(b) )) if len(a) != len(b): return False if sys.version_info < (3,): a = [ord(char) for char in a] b = [ord(char) for char in b] result = 0 for x, y in zip(a, b): result |= x ^ y return result == 0
[ "Compares", "two", "byte", "strings", "in", "constant", "time", "to", "see", "if", "they", "are", "equal" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/util.py#L23-L63
[ "def", "constant_compare", "(", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "a", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n a must be a byte string, not %s\n '''", ",", "type_name", "(", "a", ")", ")", ")", "if", "not", "isinstance", "(", "b", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n b must be a byte string, not %s\n '''", ",", "type_name", "(", "b", ")", ")", ")", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "if", "sys", ".", "version_info", "<", "(", "3", ",", ")", ":", "a", "=", "[", "ord", "(", "char", ")", "for", "char", "in", "a", "]", "b", "=", "[", "ord", "(", "char", ")", "for", "char", "in", "b", "]", "result", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "a", ",", "b", ")", ":", "result", "|=", "x", "^", "y", "return", "result", "==", "0" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_try_decode
Tries decoding a byte string from the OS into a unicode string :param byte_string: A byte string :return: A unicode string
oscrypto/_win/_decode.py
def _try_decode(byte_string): """ Tries decoding a byte string from the OS into a unicode string :param byte_string: A byte string :return: A unicode string """ try: return str_cls(byte_string, _encoding) # If the "correct" encoding did not work, try some defaults, and then just # obliterate characters that we can't seen to decode properly except (UnicodeDecodeError): for encoding in _fallback_encodings: try: return str_cls(byte_string, encoding, errors='strict') except (UnicodeDecodeError): pass return str_cls(byte_string, errors='replace')
def _try_decode(byte_string): """ Tries decoding a byte string from the OS into a unicode string :param byte_string: A byte string :return: A unicode string """ try: return str_cls(byte_string, _encoding) # If the "correct" encoding did not work, try some defaults, and then just # obliterate characters that we can't seen to decode properly except (UnicodeDecodeError): for encoding in _fallback_encodings: try: return str_cls(byte_string, encoding, errors='strict') except (UnicodeDecodeError): pass return str_cls(byte_string, errors='replace')
[ "Tries", "decoding", "a", "byte", "string", "from", "the", "OS", "into", "a", "unicode", "string" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/_decode.py#L13-L36
[ "def", "_try_decode", "(", "byte_string", ")", ":", "try", ":", "return", "str_cls", "(", "byte_string", ",", "_encoding", ")", "# If the \"correct\" encoding did not work, try some defaults, and then just", "# obliterate characters that we can't seen to decode properly", "except", "(", "UnicodeDecodeError", ")", ":", "for", "encoding", "in", "_fallback_encodings", ":", "try", ":", "return", "str_cls", "(", "byte_string", ",", "encoding", ",", "errors", "=", "'strict'", ")", "except", "(", "UnicodeDecodeError", ")", ":", "pass", "return", "str_cls", "(", "byte_string", ",", "errors", "=", "'replace'", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_read_callback
Callback called by Secure Transport to actually read the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type to write the data to :param data_length_pointer: A size_t pointer FFI type of the amount of data to read. Will be overwritten with the amount of data read on return. :return: An integer status code of the result - 0 for success
oscrypto/_osx/tls.py
def _read_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually read the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type to write the data to :param data_length_pointer: A size_t pointer FFI type of the amount of data to read. Will be overwritten with the amount of data read on return. :return: An integer status code of the result - 0 for success """ self = None try: self = _connection_refs.get(connection_id) if not self: socket = _socket_refs.get(connection_id) else: socket = self._socket if not self and not socket: return 0 bytes_requested = deref(data_length_pointer) timeout = socket.gettimeout() error = None data = b'' try: while len(data) < bytes_requested: # Python 2 on Travis CI seems to have issues with blocking on # recv() for longer than the socket timeout value, so we select if timeout is not None and timeout > 0.0: read_ready, _, _ = select.select([socket], [], [], timeout) if len(read_ready) == 0: raise socket_.error(errno.EAGAIN, 'timed out') chunk = socket.recv(bytes_requested - len(data)) data += chunk if chunk == b'': if len(data) == 0: if timeout is None: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort break except (socket_.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort if self and not self._done_handshake: # SecureTransport doesn't bother to check if the TLS record header # is valid before asking to read more data, which can result in # connection hangs. Here we do basic checks to get around the issue. if len(data) >= 3 and len(self._server_hello) == 0: # Check to ensure it is an alert or handshake first valid_record_type = data[0:1] in set([b'\x15', b'\x16']) # Check if the protocol version is SSL 3.0 or TLS 1.0-1.3 valid_protocol_version = data[1:3] in set([ b'\x03\x00', b'\x03\x01', b'\x03\x02', b'\x03\x03', b'\x03\x04' ]) if not valid_record_type or not valid_protocol_version: self._server_hello += data + _read_remaining(socket) return SecurityConst.errSSLProtocol self._server_hello += data write_to_buffer(data_buffer, data) pointer_set(data_length_pointer, len(data)) if len(data) != bytes_requested: return SecurityConst.errSSLWouldBlock return 0 except (KeyboardInterrupt) as e: if self: self._exception = e return SecurityConst.errSSLClosedAbort
def _read_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually read the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type to write the data to :param data_length_pointer: A size_t pointer FFI type of the amount of data to read. Will be overwritten with the amount of data read on return. :return: An integer status code of the result - 0 for success """ self = None try: self = _connection_refs.get(connection_id) if not self: socket = _socket_refs.get(connection_id) else: socket = self._socket if not self and not socket: return 0 bytes_requested = deref(data_length_pointer) timeout = socket.gettimeout() error = None data = b'' try: while len(data) < bytes_requested: # Python 2 on Travis CI seems to have issues with blocking on # recv() for longer than the socket timeout value, so we select if timeout is not None and timeout > 0.0: read_ready, _, _ = select.select([socket], [], [], timeout) if len(read_ready) == 0: raise socket_.error(errno.EAGAIN, 'timed out') chunk = socket.recv(bytes_requested - len(data)) data += chunk if chunk == b'': if len(data) == 0: if timeout is None: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort break except (socket_.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort if self and not self._done_handshake: # SecureTransport doesn't bother to check if the TLS record header # is valid before asking to read more data, which can result in # connection hangs. Here we do basic checks to get around the issue. if len(data) >= 3 and len(self._server_hello) == 0: # Check to ensure it is an alert or handshake first valid_record_type = data[0:1] in set([b'\x15', b'\x16']) # Check if the protocol version is SSL 3.0 or TLS 1.0-1.3 valid_protocol_version = data[1:3] in set([ b'\x03\x00', b'\x03\x01', b'\x03\x02', b'\x03\x03', b'\x03\x04' ]) if not valid_record_type or not valid_protocol_version: self._server_hello += data + _read_remaining(socket) return SecurityConst.errSSLProtocol self._server_hello += data write_to_buffer(data_buffer, data) pointer_set(data_length_pointer, len(data)) if len(data) != bytes_requested: return SecurityConst.errSSLWouldBlock return 0 except (KeyboardInterrupt) as e: if self: self._exception = e return SecurityConst.errSSLClosedAbort
[ "Callback", "called", "by", "Secure", "Transport", "to", "actually", "read", "the", "socket" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L99-L187
[ "def", "_read_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "self", "=", "None", "try", ":", "self", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "not", "self", ":", "socket", "=", "_socket_refs", ".", "get", "(", "connection_id", ")", "else", ":", "socket", "=", "self", ".", "_socket", "if", "not", "self", "and", "not", "socket", ":", "return", "0", "bytes_requested", "=", "deref", "(", "data_length_pointer", ")", "timeout", "=", "socket", ".", "gettimeout", "(", ")", "error", "=", "None", "data", "=", "b''", "try", ":", "while", "len", "(", "data", ")", "<", "bytes_requested", ":", "# Python 2 on Travis CI seems to have issues with blocking on", "# recv() for longer than the socket timeout value, so we select", "if", "timeout", "is", "not", "None", "and", "timeout", ">", "0.0", ":", "read_ready", ",", "_", ",", "_", "=", "select", ".", "select", "(", "[", "socket", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "if", "len", "(", "read_ready", ")", "==", "0", ":", "raise", "socket_", ".", "error", "(", "errno", ".", "EAGAIN", ",", "'timed out'", ")", "chunk", "=", "socket", ".", "recv", "(", "bytes_requested", "-", "len", "(", "data", ")", ")", "data", "+=", "chunk", "if", "chunk", "==", "b''", ":", "if", "len", "(", "data", ")", "==", "0", ":", "if", "timeout", "is", "None", ":", "return", "SecurityConst", ".", "errSSLClosedNoNotify", "return", "SecurityConst", ".", "errSSLClosedAbort", "break", "except", "(", "socket_", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedNoNotify", "return", "SecurityConst", ".", "errSSLClosedAbort", "if", "self", "and", "not", "self", ".", "_done_handshake", ":", "# SecureTransport doesn't bother to check if the TLS record header", "# is valid before asking to read more data, which can result in", "# connection hangs. Here we do basic checks to get around the issue.", "if", "len", "(", "data", ")", ">=", "3", "and", "len", "(", "self", ".", "_server_hello", ")", "==", "0", ":", "# Check to ensure it is an alert or handshake first", "valid_record_type", "=", "data", "[", "0", ":", "1", "]", "in", "set", "(", "[", "b'\\x15'", ",", "b'\\x16'", "]", ")", "# Check if the protocol version is SSL 3.0 or TLS 1.0-1.3", "valid_protocol_version", "=", "data", "[", "1", ":", "3", "]", "in", "set", "(", "[", "b'\\x03\\x00'", ",", "b'\\x03\\x01'", ",", "b'\\x03\\x02'", ",", "b'\\x03\\x03'", ",", "b'\\x03\\x04'", "]", ")", "if", "not", "valid_record_type", "or", "not", "valid_protocol_version", ":", "self", ".", "_server_hello", "+=", "data", "+", "_read_remaining", "(", "socket", ")", "return", "SecurityConst", ".", "errSSLProtocol", "self", ".", "_server_hello", "+=", "data", "write_to_buffer", "(", "data_buffer", ",", "data", ")", "pointer_set", "(", "data_length_pointer", ",", "len", "(", "data", ")", ")", "if", "len", "(", "data", ")", "!=", "bytes_requested", ":", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "(", "KeyboardInterrupt", ")", "as", "e", ":", "if", "self", ":", "self", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLClosedAbort" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_read_remaining
Reads everything available from the socket - used for debugging when there is a protocol error :param socket: The socket to read from :return: A byte string of the remaining data
oscrypto/_osx/tls.py
def _read_remaining(socket): """ Reads everything available from the socket - used for debugging when there is a protocol error :param socket: The socket to read from :return: A byte string of the remaining data """ output = b'' old_timeout = socket.gettimeout() try: socket.settimeout(0.0) output += socket.recv(8192) except (socket_.error): pass finally: socket.settimeout(old_timeout) return output
def _read_remaining(socket): """ Reads everything available from the socket - used for debugging when there is a protocol error :param socket: The socket to read from :return: A byte string of the remaining data """ output = b'' old_timeout = socket.gettimeout() try: socket.settimeout(0.0) output += socket.recv(8192) except (socket_.error): pass finally: socket.settimeout(old_timeout) return output
[ "Reads", "everything", "available", "from", "the", "socket", "-", "used", "for", "debugging", "when", "there", "is", "a", "protocol", "error" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L190-L211
[ "def", "_read_remaining", "(", "socket", ")", ":", "output", "=", "b''", "old_timeout", "=", "socket", ".", "gettimeout", "(", ")", "try", ":", "socket", ".", "settimeout", "(", "0.0", ")", "output", "+=", "socket", ".", "recv", "(", "8192", ")", "except", "(", "socket_", ".", "error", ")", ":", "pass", "finally", ":", "socket", ".", "settimeout", "(", "old_timeout", ")", "return", "output" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_write_callback
Callback called by Secure Transport to actually write to the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type containing the data to write :param data_length_pointer: A size_t pointer FFI type of the amount of data to write. Will be overwritten with the amount of data actually written on return. :return: An integer status code of the result - 0 for success
oscrypto/_osx/tls.py
def _write_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually write to the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type containing the data to write :param data_length_pointer: A size_t pointer FFI type of the amount of data to write. Will be overwritten with the amount of data actually written on return. :return: An integer status code of the result - 0 for success """ try: self = _connection_refs.get(connection_id) if not self: socket = _socket_refs.get(connection_id) else: socket = self._socket if not self and not socket: return 0 data_length = deref(data_length_pointer) data = bytes_from_buffer(data_buffer, data_length) if self and not self._done_handshake: self._client_hello += data error = None try: sent = socket.send(data) except (socket_.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort if sent != data_length: pointer_set(data_length_pointer, sent) return SecurityConst.errSSLWouldBlock return 0 except (KeyboardInterrupt) as e: self._exception = e return SecurityConst.errSSLPeerUserCancelled
def _write_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually write to the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type containing the data to write :param data_length_pointer: A size_t pointer FFI type of the amount of data to write. Will be overwritten with the amount of data actually written on return. :return: An integer status code of the result - 0 for success """ try: self = _connection_refs.get(connection_id) if not self: socket = _socket_refs.get(connection_id) else: socket = self._socket if not self and not socket: return 0 data_length = deref(data_length_pointer) data = bytes_from_buffer(data_buffer, data_length) if self and not self._done_handshake: self._client_hello += data error = None try: sent = socket.send(data) except (socket_.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort if sent != data_length: pointer_set(data_length_pointer, sent) return SecurityConst.errSSLWouldBlock return 0 except (KeyboardInterrupt) as e: self._exception = e return SecurityConst.errSSLPeerUserCancelled
[ "Callback", "called", "by", "Secure", "Transport", "to", "actually", "write", "to", "the", "socket" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L214-L266
[ "def", "_write_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "try", ":", "self", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "not", "self", ":", "socket", "=", "_socket_refs", ".", "get", "(", "connection_id", ")", "else", ":", "socket", "=", "self", ".", "_socket", "if", "not", "self", "and", "not", "socket", ":", "return", "0", "data_length", "=", "deref", "(", "data_length_pointer", ")", "data", "=", "bytes_from_buffer", "(", "data_buffer", ",", "data_length", ")", "if", "self", "and", "not", "self", ".", "_done_handshake", ":", "self", ".", "_client_hello", "+=", "data", "error", "=", "None", "try", ":", "sent", "=", "socket", ".", "send", "(", "data", ")", "except", "(", "socket_", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedNoNotify", "return", "SecurityConst", ".", "errSSLClosedAbort", "if", "sent", "!=", "data_length", ":", "pointer_set", "(", "data_length_pointer", ",", "sent", ")", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "(", "KeyboardInterrupt", ")", "as", "e", ":", "self", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLPeerUserCancelled" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket._handshake
Perform an initial TLS handshake
oscrypto/_osx/tls.py
def _handshake(self): """ Perform an initial TLS handshake """ session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref = None ocsp_search_ref = None ocsp_policy_ref = None policy_array_ref = None try: if osx_version_info < (10, 8): session_context_pointer = new(Security, 'SSLContextRef *') result = Security.SSLNewContext(False, session_context_pointer) handle_sec_error(result) session_context = unwrap(session_context_pointer) else: session_context = Security.SSLCreateContext( null(), SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( session_context, _read_callback_pointer, _write_callback_pointer ) handle_sec_error(result) self._connection_id = id(self) % 2147483647 _connection_refs[self._connection_id] = self _socket_refs[self._connection_id] = self._socket result = Security.SSLSetConnection(session_context, self._connection_id) handle_sec_error(result) utf8_domain = self._hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( session_context, utf8_domain, len(utf8_domain) ) handle_sec_error(result) if osx_version_info >= (10, 10): disable_auto_validation = self._session._manual_validation or self._session._extra_trust_roots explicit_validation = (not self._session._manual_validation) and self._session._extra_trust_roots else: disable_auto_validation = True explicit_validation = not self._session._manual_validation # Ensure requested protocol support is set for the session if osx_version_info < (10, 8): for protocol in ['SSLv2', 'SSLv3', 'TLSv1']: protocol_const = _PROTOCOL_STRING_CONST_MAP[protocol] enabled = protocol in self._session._protocols result = Security.SSLSetProtocolVersionEnabled( session_context, protocol_const, enabled ) handle_sec_error(result) if disable_auto_validation: result = Security.SSLSetEnableCertVerify(session_context, False) handle_sec_error(result) else: protocol_consts = [_PROTOCOL_STRING_CONST_MAP[protocol] for protocol in self._session._protocols] min_protocol = min(protocol_consts) max_protocol = max(protocol_consts) result = Security.SSLSetProtocolVersionMin( session_context, min_protocol ) handle_sec_error(result) result = Security.SSLSetProtocolVersionMax( session_context, max_protocol ) handle_sec_error(result) if disable_auto_validation: result = Security.SSLSetSessionOption( session_context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) handle_sec_error(result) # Disable all sorts of bad cipher suites supported_ciphers_pointer = new(Security, 'size_t *') result = Security.SSLGetNumberSupportedCiphers(session_context, supported_ciphers_pointer) handle_sec_error(result) supported_ciphers = deref(supported_ciphers_pointer) cipher_buffer = buffer_from_bytes(supported_ciphers * 4) supported_cipher_suites_pointer = cast(Security, 'uint32_t *', cipher_buffer) result = Security.SSLGetSupportedCiphers( session_context, supported_cipher_suites_pointer, supported_ciphers_pointer ) handle_sec_error(result) supported_ciphers = deref(supported_ciphers_pointer) supported_cipher_suites = array_from_pointer( Security, 'uint32_t', supported_cipher_suites_pointer, supported_ciphers ) good_ciphers = [] for supported_cipher_suite in supported_cipher_suites: cipher_suite = int_to_bytes(supported_cipher_suite, width=2) cipher_suite_name = CIPHER_SUITE_MAP.get(cipher_suite, cipher_suite) good_cipher = _cipher_blacklist_regex.search(cipher_suite_name) is None if good_cipher: good_ciphers.append(supported_cipher_suite) num_good_ciphers = len(good_ciphers) good_ciphers_array = new(Security, 'uint32_t[]', num_good_ciphers) array_set(good_ciphers_array, good_ciphers) good_ciphers_pointer = cast(Security, 'uint32_t *', good_ciphers_array) result = Security.SSLSetEnabledCiphers( session_context, good_ciphers_pointer, num_good_ciphers ) handle_sec_error(result) # Set a peer id from the session to allow for session reuse, the hostname # is appended to prevent a bug on OS X 10.7 where it tries to reuse a # connection even if the hostnames are different. peer_id = self._session._peer_id + self._hostname.encode('utf-8') result = Security.SSLSetPeerID(session_context, peer_id, len(peer_id)) handle_sec_error(result) handshake_result = Security.SSLHandshake(session_context) if self._exception is not None: exception = self._exception self._exception = None raise exception while handshake_result == SecurityConst.errSSLWouldBlock: handshake_result = Security.SSLHandshake(session_context) if self._exception is not None: exception = self._exception self._exception = None raise exception if osx_version_info < (10, 8) and osx_version_info >= (10, 7): do_validation = explicit_validation and handshake_result == 0 else: do_validation = explicit_validation and handshake_result == SecurityConst.errSSLServerAuthCompleted if do_validation: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) cf_string_hostname = CFHelpers.cf_string_from_unicode(self._hostname) ssl_policy_ref = Security.SecPolicyCreateSSL(True, cf_string_hostname) result = CoreFoundation.CFRelease(cf_string_hostname) handle_cf_error(result) # Create a new policy for OCSP checking to disable it ocsp_oid_pointer = struct(Security, 'CSSM_OID') ocsp_oid = unwrap(ocsp_oid_pointer) ocsp_oid.Length = len(SecurityConst.APPLE_TP_REVOCATION_OCSP) ocsp_oid_buffer = buffer_from_bytes(SecurityConst.APPLE_TP_REVOCATION_OCSP) ocsp_oid.Data = cast(Security, 'char *', ocsp_oid_buffer) ocsp_search_ref_pointer = new(Security, 'SecPolicySearchRef *') result = Security.SecPolicySearchCreate( SecurityConst.CSSM_CERT_X_509v3, ocsp_oid_pointer, null(), ocsp_search_ref_pointer ) handle_sec_error(result) ocsp_search_ref = unwrap(ocsp_search_ref_pointer) ocsp_policy_ref_pointer = new(Security, 'SecPolicyRef *') result = Security.SecPolicySearchCopyNext(ocsp_search_ref, ocsp_policy_ref_pointer) handle_sec_error(result) ocsp_policy_ref = unwrap(ocsp_policy_ref_pointer) ocsp_struct_pointer = struct(Security, 'CSSM_APPLE_TP_OCSP_OPTIONS') ocsp_struct = unwrap(ocsp_struct_pointer) ocsp_struct.Version = SecurityConst.CSSM_APPLE_TP_OCSP_OPTS_VERSION ocsp_struct.Flags = ( SecurityConst.CSSM_TP_ACTION_OCSP_DISABLE_NET | SecurityConst.CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE ) ocsp_struct_bytes = struct_bytes(ocsp_struct_pointer) cssm_data_pointer = struct(Security, 'CSSM_DATA') cssm_data = unwrap(cssm_data_pointer) cssm_data.Length = len(ocsp_struct_bytes) ocsp_struct_buffer = buffer_from_bytes(ocsp_struct_bytes) cssm_data.Data = cast(Security, 'char *', ocsp_struct_buffer) result = Security.SecPolicySetValue(ocsp_policy_ref, cssm_data_pointer) handle_sec_error(result) # Create a new policy for CRL checking to disable it crl_oid_pointer = struct(Security, 'CSSM_OID') crl_oid = unwrap(crl_oid_pointer) crl_oid.Length = len(SecurityConst.APPLE_TP_REVOCATION_CRL) crl_oid_buffer = buffer_from_bytes(SecurityConst.APPLE_TP_REVOCATION_CRL) crl_oid.Data = cast(Security, 'char *', crl_oid_buffer) crl_search_ref_pointer = new(Security, 'SecPolicySearchRef *') result = Security.SecPolicySearchCreate( SecurityConst.CSSM_CERT_X_509v3, crl_oid_pointer, null(), crl_search_ref_pointer ) handle_sec_error(result) crl_search_ref = unwrap(crl_search_ref_pointer) crl_policy_ref_pointer = new(Security, 'SecPolicyRef *') result = Security.SecPolicySearchCopyNext(crl_search_ref, crl_policy_ref_pointer) handle_sec_error(result) crl_policy_ref = unwrap(crl_policy_ref_pointer) crl_struct_pointer = struct(Security, 'CSSM_APPLE_TP_CRL_OPTIONS') crl_struct = unwrap(crl_struct_pointer) crl_struct.Version = SecurityConst.CSSM_APPLE_TP_CRL_OPTS_VERSION crl_struct.CrlFlags = 0 crl_struct_bytes = struct_bytes(crl_struct_pointer) cssm_data_pointer = struct(Security, 'CSSM_DATA') cssm_data = unwrap(cssm_data_pointer) cssm_data.Length = len(crl_struct_bytes) crl_struct_buffer = buffer_from_bytes(crl_struct_bytes) cssm_data.Data = cast(Security, 'char *', crl_struct_buffer) result = Security.SecPolicySetValue(crl_policy_ref, cssm_data_pointer) handle_sec_error(result) policy_array_ref = CFHelpers.cf_array_from_list([ ssl_policy_ref, crl_policy_ref, ocsp_policy_ref ]) result = Security.SecTrustSetPolicies(trust_ref, policy_array_ref) handle_sec_error(result) if self._session._extra_trust_roots: ca_cert_refs = [] ca_certs = [] for cert in self._session._extra_trust_roots: ca_cert = load_certificate(cert) ca_certs.append(ca_cert) ca_cert_refs.append(ca_cert.sec_certificate_ref) result = Security.SecTrustSetAnchorCertificatesOnly(trust_ref, False) handle_sec_error(result) array_ref = CFHelpers.cf_array_from_list(ca_cert_refs) result = Security.SecTrustSetAnchorCertificates(trust_ref, array_ref) handle_sec_error(result) result_pointer = new(Security, 'SecTrustResultType *') result = Security.SecTrustEvaluate(trust_ref, result_pointer) handle_sec_error(result) trust_result_code = deref(result_pointer) invalid_chain_error_codes = set([ SecurityConst.kSecTrustResultProceed, SecurityConst.kSecTrustResultUnspecified ]) if trust_result_code not in invalid_chain_error_codes: handshake_result = SecurityConst.errSSLXCertChainInvalid else: handshake_result = Security.SSLHandshake(session_context) while handshake_result == SecurityConst.errSSLWouldBlock: handshake_result = Security.SSLHandshake(session_context) self._done_handshake = True handshake_error_codes = set([ SecurityConst.errSSLXCertChainInvalid, SecurityConst.errSSLCertExpired, SecurityConst.errSSLCertNotYetValid, SecurityConst.errSSLUnknownRootCert, SecurityConst.errSSLNoRootCert, SecurityConst.errSSLHostNameMismatch, SecurityConst.errSSLInternal, ]) # In testing, only errSSLXCertChainInvalid was ever returned for # all of these different situations, however we include the others # for completeness. To get the real reason we have to use the # certificate from the handshake and use the deprecated function # SecTrustGetCssmResultCode(). if handshake_result in handshake_error_codes: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) result_code_pointer = new(Security, 'OSStatus *') result = Security.SecTrustGetCssmResultCode(trust_ref, result_code_pointer) result_code = deref(result_code_pointer) chain = extract_chain(self._server_hello) self_signed = False revoked = False expired = False not_yet_valid = False no_issuer = False cert = None bad_hostname = False if chain: cert = chain[0] oscrypto_cert = load_certificate(cert) self_signed = oscrypto_cert.self_signed revoked = result_code == SecurityConst.CSSMERR_TP_CERT_REVOKED no_issuer = not self_signed and result_code == SecurityConst.CSSMERR_TP_NOT_TRUSTED expired = result_code == SecurityConst.CSSMERR_TP_CERT_EXPIRED not_yet_valid = result_code == SecurityConst.CSSMERR_TP_CERT_NOT_VALID_YET bad_hostname = result_code == SecurityConst.CSSMERR_APPLETP_HOSTNAME_MISMATCH # On macOS 10.12, some expired certificates return errSSLInternal if osx_version_info >= (10, 12): validity = cert['tbs_certificate']['validity'] not_before = validity['not_before'].chosen.native not_after = validity['not_after'].chosen.native utcnow = datetime.datetime.now(timezone.utc) expired = not_after < utcnow not_yet_valid = not_before > utcnow if chain and chain[0].hash_algo in set(['md5', 'md2']): raise_weak_signature(chain[0]) if revoked: raise_revoked(cert) if bad_hostname: raise_hostname(cert, self._hostname) elif expired or not_yet_valid: raise_expired_not_yet_valid(cert) elif no_issuer: raise_no_issuer(cert) elif self_signed: raise_self_signed(cert) if detect_client_auth_request(self._server_hello): raise_client_auth() raise_verification(cert) if handshake_result == SecurityConst.errSSLPeerHandshakeFail: if detect_client_auth_request(self._server_hello): raise_client_auth() raise_handshake() if handshake_result == SecurityConst.errSSLWeakPeerEphemeralDHKey: raise_dh_params() if handshake_result == SecurityConst.errSSLPeerProtocolVersion: raise_protocol_version() if handshake_result in set([SecurityConst.errSSLRecordOverflow, SecurityConst.errSSLProtocol]): self._server_hello += _read_remaining(self._socket) raise_protocol_error(self._server_hello) if handshake_result in set([SecurityConst.errSSLClosedNoNotify, SecurityConst.errSSLClosedAbort]): if not self._done_handshake: self._server_hello += _read_remaining(self._socket) if detect_other_protocol(self._server_hello): raise_protocol_error(self._server_hello) raise_disconnection() if osx_version_info < (10, 10): dh_params_length = get_dh_params_length(self._server_hello) if dh_params_length is not None and dh_params_length < 1024: raise_dh_params() would_block = handshake_result == SecurityConst.errSSLWouldBlock server_auth_complete = handshake_result == SecurityConst.errSSLServerAuthCompleted manual_validation = self._session._manual_validation and server_auth_complete if not would_block and not manual_validation: handle_sec_error(handshake_result, TLSError) self._session_context = session_context protocol_const_pointer = new(Security, 'SSLProtocol *') result = Security.SSLGetNegotiatedProtocolVersion( session_context, protocol_const_pointer ) handle_sec_error(result) protocol_const = deref(protocol_const_pointer) self._protocol = _PROTOCOL_CONST_STRING_MAP[protocol_const] cipher_int_pointer = new(Security, 'SSLCipherSuite *') result = Security.SSLGetNegotiatedCipher( session_context, cipher_int_pointer ) handle_sec_error(result) cipher_int = deref(cipher_int_pointer) cipher_bytes = int_to_bytes(cipher_int, width=2) self._cipher_suite = CIPHER_SUITE_MAP.get(cipher_bytes, cipher_bytes) session_info = parse_session_info( self._server_hello, self._client_hello ) self._compression = session_info['compression'] self._session_id = session_info['session_id'] self._session_ticket = session_info['session_ticket'] except (OSError, socket_.error): if session_context: if osx_version_info < (10, 8): result = Security.SSLDisposeContext(session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(session_context) handle_cf_error(result) self._session_context = None self.close() raise finally: # Trying to release crl_search_ref or ocsp_search_ref results in # a segmentation fault, so we do not do that if ssl_policy_ref: result = CoreFoundation.CFRelease(ssl_policy_ref) handle_cf_error(result) ssl_policy_ref = None if crl_policy_ref: result = CoreFoundation.CFRelease(crl_policy_ref) handle_cf_error(result) crl_policy_ref = None if ocsp_policy_ref: result = CoreFoundation.CFRelease(ocsp_policy_ref) handle_cf_error(result) ocsp_policy_ref = None if policy_array_ref: result = CoreFoundation.CFRelease(policy_array_ref) handle_cf_error(result) policy_array_ref = None
def _handshake(self): """ Perform an initial TLS handshake """ session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref = None ocsp_search_ref = None ocsp_policy_ref = None policy_array_ref = None try: if osx_version_info < (10, 8): session_context_pointer = new(Security, 'SSLContextRef *') result = Security.SSLNewContext(False, session_context_pointer) handle_sec_error(result) session_context = unwrap(session_context_pointer) else: session_context = Security.SSLCreateContext( null(), SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( session_context, _read_callback_pointer, _write_callback_pointer ) handle_sec_error(result) self._connection_id = id(self) % 2147483647 _connection_refs[self._connection_id] = self _socket_refs[self._connection_id] = self._socket result = Security.SSLSetConnection(session_context, self._connection_id) handle_sec_error(result) utf8_domain = self._hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( session_context, utf8_domain, len(utf8_domain) ) handle_sec_error(result) if osx_version_info >= (10, 10): disable_auto_validation = self._session._manual_validation or self._session._extra_trust_roots explicit_validation = (not self._session._manual_validation) and self._session._extra_trust_roots else: disable_auto_validation = True explicit_validation = not self._session._manual_validation # Ensure requested protocol support is set for the session if osx_version_info < (10, 8): for protocol in ['SSLv2', 'SSLv3', 'TLSv1']: protocol_const = _PROTOCOL_STRING_CONST_MAP[protocol] enabled = protocol in self._session._protocols result = Security.SSLSetProtocolVersionEnabled( session_context, protocol_const, enabled ) handle_sec_error(result) if disable_auto_validation: result = Security.SSLSetEnableCertVerify(session_context, False) handle_sec_error(result) else: protocol_consts = [_PROTOCOL_STRING_CONST_MAP[protocol] for protocol in self._session._protocols] min_protocol = min(protocol_consts) max_protocol = max(protocol_consts) result = Security.SSLSetProtocolVersionMin( session_context, min_protocol ) handle_sec_error(result) result = Security.SSLSetProtocolVersionMax( session_context, max_protocol ) handle_sec_error(result) if disable_auto_validation: result = Security.SSLSetSessionOption( session_context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) handle_sec_error(result) # Disable all sorts of bad cipher suites supported_ciphers_pointer = new(Security, 'size_t *') result = Security.SSLGetNumberSupportedCiphers(session_context, supported_ciphers_pointer) handle_sec_error(result) supported_ciphers = deref(supported_ciphers_pointer) cipher_buffer = buffer_from_bytes(supported_ciphers * 4) supported_cipher_suites_pointer = cast(Security, 'uint32_t *', cipher_buffer) result = Security.SSLGetSupportedCiphers( session_context, supported_cipher_suites_pointer, supported_ciphers_pointer ) handle_sec_error(result) supported_ciphers = deref(supported_ciphers_pointer) supported_cipher_suites = array_from_pointer( Security, 'uint32_t', supported_cipher_suites_pointer, supported_ciphers ) good_ciphers = [] for supported_cipher_suite in supported_cipher_suites: cipher_suite = int_to_bytes(supported_cipher_suite, width=2) cipher_suite_name = CIPHER_SUITE_MAP.get(cipher_suite, cipher_suite) good_cipher = _cipher_blacklist_regex.search(cipher_suite_name) is None if good_cipher: good_ciphers.append(supported_cipher_suite) num_good_ciphers = len(good_ciphers) good_ciphers_array = new(Security, 'uint32_t[]', num_good_ciphers) array_set(good_ciphers_array, good_ciphers) good_ciphers_pointer = cast(Security, 'uint32_t *', good_ciphers_array) result = Security.SSLSetEnabledCiphers( session_context, good_ciphers_pointer, num_good_ciphers ) handle_sec_error(result) # Set a peer id from the session to allow for session reuse, the hostname # is appended to prevent a bug on OS X 10.7 where it tries to reuse a # connection even if the hostnames are different. peer_id = self._session._peer_id + self._hostname.encode('utf-8') result = Security.SSLSetPeerID(session_context, peer_id, len(peer_id)) handle_sec_error(result) handshake_result = Security.SSLHandshake(session_context) if self._exception is not None: exception = self._exception self._exception = None raise exception while handshake_result == SecurityConst.errSSLWouldBlock: handshake_result = Security.SSLHandshake(session_context) if self._exception is not None: exception = self._exception self._exception = None raise exception if osx_version_info < (10, 8) and osx_version_info >= (10, 7): do_validation = explicit_validation and handshake_result == 0 else: do_validation = explicit_validation and handshake_result == SecurityConst.errSSLServerAuthCompleted if do_validation: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) cf_string_hostname = CFHelpers.cf_string_from_unicode(self._hostname) ssl_policy_ref = Security.SecPolicyCreateSSL(True, cf_string_hostname) result = CoreFoundation.CFRelease(cf_string_hostname) handle_cf_error(result) # Create a new policy for OCSP checking to disable it ocsp_oid_pointer = struct(Security, 'CSSM_OID') ocsp_oid = unwrap(ocsp_oid_pointer) ocsp_oid.Length = len(SecurityConst.APPLE_TP_REVOCATION_OCSP) ocsp_oid_buffer = buffer_from_bytes(SecurityConst.APPLE_TP_REVOCATION_OCSP) ocsp_oid.Data = cast(Security, 'char *', ocsp_oid_buffer) ocsp_search_ref_pointer = new(Security, 'SecPolicySearchRef *') result = Security.SecPolicySearchCreate( SecurityConst.CSSM_CERT_X_509v3, ocsp_oid_pointer, null(), ocsp_search_ref_pointer ) handle_sec_error(result) ocsp_search_ref = unwrap(ocsp_search_ref_pointer) ocsp_policy_ref_pointer = new(Security, 'SecPolicyRef *') result = Security.SecPolicySearchCopyNext(ocsp_search_ref, ocsp_policy_ref_pointer) handle_sec_error(result) ocsp_policy_ref = unwrap(ocsp_policy_ref_pointer) ocsp_struct_pointer = struct(Security, 'CSSM_APPLE_TP_OCSP_OPTIONS') ocsp_struct = unwrap(ocsp_struct_pointer) ocsp_struct.Version = SecurityConst.CSSM_APPLE_TP_OCSP_OPTS_VERSION ocsp_struct.Flags = ( SecurityConst.CSSM_TP_ACTION_OCSP_DISABLE_NET | SecurityConst.CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE ) ocsp_struct_bytes = struct_bytes(ocsp_struct_pointer) cssm_data_pointer = struct(Security, 'CSSM_DATA') cssm_data = unwrap(cssm_data_pointer) cssm_data.Length = len(ocsp_struct_bytes) ocsp_struct_buffer = buffer_from_bytes(ocsp_struct_bytes) cssm_data.Data = cast(Security, 'char *', ocsp_struct_buffer) result = Security.SecPolicySetValue(ocsp_policy_ref, cssm_data_pointer) handle_sec_error(result) # Create a new policy for CRL checking to disable it crl_oid_pointer = struct(Security, 'CSSM_OID') crl_oid = unwrap(crl_oid_pointer) crl_oid.Length = len(SecurityConst.APPLE_TP_REVOCATION_CRL) crl_oid_buffer = buffer_from_bytes(SecurityConst.APPLE_TP_REVOCATION_CRL) crl_oid.Data = cast(Security, 'char *', crl_oid_buffer) crl_search_ref_pointer = new(Security, 'SecPolicySearchRef *') result = Security.SecPolicySearchCreate( SecurityConst.CSSM_CERT_X_509v3, crl_oid_pointer, null(), crl_search_ref_pointer ) handle_sec_error(result) crl_search_ref = unwrap(crl_search_ref_pointer) crl_policy_ref_pointer = new(Security, 'SecPolicyRef *') result = Security.SecPolicySearchCopyNext(crl_search_ref, crl_policy_ref_pointer) handle_sec_error(result) crl_policy_ref = unwrap(crl_policy_ref_pointer) crl_struct_pointer = struct(Security, 'CSSM_APPLE_TP_CRL_OPTIONS') crl_struct = unwrap(crl_struct_pointer) crl_struct.Version = SecurityConst.CSSM_APPLE_TP_CRL_OPTS_VERSION crl_struct.CrlFlags = 0 crl_struct_bytes = struct_bytes(crl_struct_pointer) cssm_data_pointer = struct(Security, 'CSSM_DATA') cssm_data = unwrap(cssm_data_pointer) cssm_data.Length = len(crl_struct_bytes) crl_struct_buffer = buffer_from_bytes(crl_struct_bytes) cssm_data.Data = cast(Security, 'char *', crl_struct_buffer) result = Security.SecPolicySetValue(crl_policy_ref, cssm_data_pointer) handle_sec_error(result) policy_array_ref = CFHelpers.cf_array_from_list([ ssl_policy_ref, crl_policy_ref, ocsp_policy_ref ]) result = Security.SecTrustSetPolicies(trust_ref, policy_array_ref) handle_sec_error(result) if self._session._extra_trust_roots: ca_cert_refs = [] ca_certs = [] for cert in self._session._extra_trust_roots: ca_cert = load_certificate(cert) ca_certs.append(ca_cert) ca_cert_refs.append(ca_cert.sec_certificate_ref) result = Security.SecTrustSetAnchorCertificatesOnly(trust_ref, False) handle_sec_error(result) array_ref = CFHelpers.cf_array_from_list(ca_cert_refs) result = Security.SecTrustSetAnchorCertificates(trust_ref, array_ref) handle_sec_error(result) result_pointer = new(Security, 'SecTrustResultType *') result = Security.SecTrustEvaluate(trust_ref, result_pointer) handle_sec_error(result) trust_result_code = deref(result_pointer) invalid_chain_error_codes = set([ SecurityConst.kSecTrustResultProceed, SecurityConst.kSecTrustResultUnspecified ]) if trust_result_code not in invalid_chain_error_codes: handshake_result = SecurityConst.errSSLXCertChainInvalid else: handshake_result = Security.SSLHandshake(session_context) while handshake_result == SecurityConst.errSSLWouldBlock: handshake_result = Security.SSLHandshake(session_context) self._done_handshake = True handshake_error_codes = set([ SecurityConst.errSSLXCertChainInvalid, SecurityConst.errSSLCertExpired, SecurityConst.errSSLCertNotYetValid, SecurityConst.errSSLUnknownRootCert, SecurityConst.errSSLNoRootCert, SecurityConst.errSSLHostNameMismatch, SecurityConst.errSSLInternal, ]) # In testing, only errSSLXCertChainInvalid was ever returned for # all of these different situations, however we include the others # for completeness. To get the real reason we have to use the # certificate from the handshake and use the deprecated function # SecTrustGetCssmResultCode(). if handshake_result in handshake_error_codes: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) result_code_pointer = new(Security, 'OSStatus *') result = Security.SecTrustGetCssmResultCode(trust_ref, result_code_pointer) result_code = deref(result_code_pointer) chain = extract_chain(self._server_hello) self_signed = False revoked = False expired = False not_yet_valid = False no_issuer = False cert = None bad_hostname = False if chain: cert = chain[0] oscrypto_cert = load_certificate(cert) self_signed = oscrypto_cert.self_signed revoked = result_code == SecurityConst.CSSMERR_TP_CERT_REVOKED no_issuer = not self_signed and result_code == SecurityConst.CSSMERR_TP_NOT_TRUSTED expired = result_code == SecurityConst.CSSMERR_TP_CERT_EXPIRED not_yet_valid = result_code == SecurityConst.CSSMERR_TP_CERT_NOT_VALID_YET bad_hostname = result_code == SecurityConst.CSSMERR_APPLETP_HOSTNAME_MISMATCH # On macOS 10.12, some expired certificates return errSSLInternal if osx_version_info >= (10, 12): validity = cert['tbs_certificate']['validity'] not_before = validity['not_before'].chosen.native not_after = validity['not_after'].chosen.native utcnow = datetime.datetime.now(timezone.utc) expired = not_after < utcnow not_yet_valid = not_before > utcnow if chain and chain[0].hash_algo in set(['md5', 'md2']): raise_weak_signature(chain[0]) if revoked: raise_revoked(cert) if bad_hostname: raise_hostname(cert, self._hostname) elif expired or not_yet_valid: raise_expired_not_yet_valid(cert) elif no_issuer: raise_no_issuer(cert) elif self_signed: raise_self_signed(cert) if detect_client_auth_request(self._server_hello): raise_client_auth() raise_verification(cert) if handshake_result == SecurityConst.errSSLPeerHandshakeFail: if detect_client_auth_request(self._server_hello): raise_client_auth() raise_handshake() if handshake_result == SecurityConst.errSSLWeakPeerEphemeralDHKey: raise_dh_params() if handshake_result == SecurityConst.errSSLPeerProtocolVersion: raise_protocol_version() if handshake_result in set([SecurityConst.errSSLRecordOverflow, SecurityConst.errSSLProtocol]): self._server_hello += _read_remaining(self._socket) raise_protocol_error(self._server_hello) if handshake_result in set([SecurityConst.errSSLClosedNoNotify, SecurityConst.errSSLClosedAbort]): if not self._done_handshake: self._server_hello += _read_remaining(self._socket) if detect_other_protocol(self._server_hello): raise_protocol_error(self._server_hello) raise_disconnection() if osx_version_info < (10, 10): dh_params_length = get_dh_params_length(self._server_hello) if dh_params_length is not None and dh_params_length < 1024: raise_dh_params() would_block = handshake_result == SecurityConst.errSSLWouldBlock server_auth_complete = handshake_result == SecurityConst.errSSLServerAuthCompleted manual_validation = self._session._manual_validation and server_auth_complete if not would_block and not manual_validation: handle_sec_error(handshake_result, TLSError) self._session_context = session_context protocol_const_pointer = new(Security, 'SSLProtocol *') result = Security.SSLGetNegotiatedProtocolVersion( session_context, protocol_const_pointer ) handle_sec_error(result) protocol_const = deref(protocol_const_pointer) self._protocol = _PROTOCOL_CONST_STRING_MAP[protocol_const] cipher_int_pointer = new(Security, 'SSLCipherSuite *') result = Security.SSLGetNegotiatedCipher( session_context, cipher_int_pointer ) handle_sec_error(result) cipher_int = deref(cipher_int_pointer) cipher_bytes = int_to_bytes(cipher_int, width=2) self._cipher_suite = CIPHER_SUITE_MAP.get(cipher_bytes, cipher_bytes) session_info = parse_session_info( self._server_hello, self._client_hello ) self._compression = session_info['compression'] self._session_id = session_info['session_id'] self._session_ticket = session_info['session_ticket'] except (OSError, socket_.error): if session_context: if osx_version_info < (10, 8): result = Security.SSLDisposeContext(session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(session_context) handle_cf_error(result) self._session_context = None self.close() raise finally: # Trying to release crl_search_ref or ocsp_search_ref results in # a segmentation fault, so we do not do that if ssl_policy_ref: result = CoreFoundation.CFRelease(ssl_policy_ref) handle_cf_error(result) ssl_policy_ref = None if crl_policy_ref: result = CoreFoundation.CFRelease(crl_policy_ref) handle_cf_error(result) crl_policy_ref = None if ocsp_policy_ref: result = CoreFoundation.CFRelease(ocsp_policy_ref) handle_cf_error(result) ocsp_policy_ref = None if policy_array_ref: result = CoreFoundation.CFRelease(policy_array_ref) handle_cf_error(result) policy_array_ref = None
[ "Perform", "an", "initial", "TLS", "handshake" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L531-L1004
[ "def", "_handshake", "(", "self", ")", ":", "session_context", "=", "None", "ssl_policy_ref", "=", "None", "crl_search_ref", "=", "None", "crl_policy_ref", "=", "None", "ocsp_search_ref", "=", "None", "ocsp_policy_ref", "=", "None", "policy_array_ref", "=", "None", "try", ":", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", ":", "session_context_pointer", "=", "new", "(", "Security", ",", "'SSLContextRef *'", ")", "result", "=", "Security", ".", "SSLNewContext", "(", "False", ",", "session_context_pointer", ")", "handle_sec_error", "(", "result", ")", "session_context", "=", "unwrap", "(", "session_context_pointer", ")", "else", ":", "session_context", "=", "Security", ".", "SSLCreateContext", "(", "null", "(", ")", ",", "SecurityConst", ".", "kSSLClientSide", ",", "SecurityConst", ".", "kSSLStreamType", ")", "result", "=", "Security", ".", "SSLSetIOFuncs", "(", "session_context", ",", "_read_callback_pointer", ",", "_write_callback_pointer", ")", "handle_sec_error", "(", "result", ")", "self", ".", "_connection_id", "=", "id", "(", "self", ")", "%", "2147483647", "_connection_refs", "[", "self", ".", "_connection_id", "]", "=", "self", "_socket_refs", "[", "self", ".", "_connection_id", "]", "=", "self", ".", "_socket", "result", "=", "Security", ".", "SSLSetConnection", "(", "session_context", ",", "self", ".", "_connection_id", ")", "handle_sec_error", "(", "result", ")", "utf8_domain", "=", "self", ".", "_hostname", ".", "encode", "(", "'utf-8'", ")", "result", "=", "Security", ".", "SSLSetPeerDomainName", "(", "session_context", ",", "utf8_domain", ",", "len", "(", "utf8_domain", ")", ")", "handle_sec_error", "(", "result", ")", "if", "osx_version_info", ">=", "(", "10", ",", "10", ")", ":", "disable_auto_validation", "=", "self", ".", "_session", ".", "_manual_validation", "or", "self", ".", "_session", ".", "_extra_trust_roots", "explicit_validation", "=", "(", "not", "self", ".", "_session", ".", "_manual_validation", ")", "and", "self", ".", "_session", ".", "_extra_trust_roots", "else", ":", "disable_auto_validation", "=", "True", "explicit_validation", "=", "not", "self", ".", "_session", ".", "_manual_validation", "# Ensure requested protocol support is set for the session", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", ":", "for", "protocol", "in", "[", "'SSLv2'", ",", "'SSLv3'", ",", "'TLSv1'", "]", ":", "protocol_const", "=", "_PROTOCOL_STRING_CONST_MAP", "[", "protocol", "]", "enabled", "=", "protocol", "in", "self", ".", "_session", ".", "_protocols", "result", "=", "Security", ".", "SSLSetProtocolVersionEnabled", "(", "session_context", ",", "protocol_const", ",", "enabled", ")", "handle_sec_error", "(", "result", ")", "if", "disable_auto_validation", ":", "result", "=", "Security", ".", "SSLSetEnableCertVerify", "(", "session_context", ",", "False", ")", "handle_sec_error", "(", "result", ")", "else", ":", "protocol_consts", "=", "[", "_PROTOCOL_STRING_CONST_MAP", "[", "protocol", "]", "for", "protocol", "in", "self", ".", "_session", ".", "_protocols", "]", "min_protocol", "=", "min", "(", "protocol_consts", ")", "max_protocol", "=", "max", "(", "protocol_consts", ")", "result", "=", "Security", ".", "SSLSetProtocolVersionMin", "(", "session_context", ",", "min_protocol", ")", "handle_sec_error", "(", "result", ")", "result", "=", "Security", ".", "SSLSetProtocolVersionMax", "(", "session_context", ",", "max_protocol", ")", "handle_sec_error", "(", "result", ")", "if", "disable_auto_validation", ":", "result", "=", "Security", ".", "SSLSetSessionOption", "(", "session_context", ",", "SecurityConst", ".", "kSSLSessionOptionBreakOnServerAuth", ",", "True", ")", "handle_sec_error", "(", "result", ")", "# Disable all sorts of bad cipher suites", "supported_ciphers_pointer", "=", "new", "(", "Security", ",", "'size_t *'", ")", "result", "=", "Security", ".", "SSLGetNumberSupportedCiphers", "(", "session_context", ",", "supported_ciphers_pointer", ")", "handle_sec_error", "(", "result", ")", "supported_ciphers", "=", "deref", "(", "supported_ciphers_pointer", ")", "cipher_buffer", "=", "buffer_from_bytes", "(", "supported_ciphers", "*", "4", ")", "supported_cipher_suites_pointer", "=", "cast", "(", "Security", ",", "'uint32_t *'", ",", "cipher_buffer", ")", "result", "=", "Security", ".", "SSLGetSupportedCiphers", "(", "session_context", ",", "supported_cipher_suites_pointer", ",", "supported_ciphers_pointer", ")", "handle_sec_error", "(", "result", ")", "supported_ciphers", "=", "deref", "(", "supported_ciphers_pointer", ")", "supported_cipher_suites", "=", "array_from_pointer", "(", "Security", ",", "'uint32_t'", ",", "supported_cipher_suites_pointer", ",", "supported_ciphers", ")", "good_ciphers", "=", "[", "]", "for", "supported_cipher_suite", "in", "supported_cipher_suites", ":", "cipher_suite", "=", "int_to_bytes", "(", "supported_cipher_suite", ",", "width", "=", "2", ")", "cipher_suite_name", "=", "CIPHER_SUITE_MAP", ".", "get", "(", "cipher_suite", ",", "cipher_suite", ")", "good_cipher", "=", "_cipher_blacklist_regex", ".", "search", "(", "cipher_suite_name", ")", "is", "None", "if", "good_cipher", ":", "good_ciphers", ".", "append", "(", "supported_cipher_suite", ")", "num_good_ciphers", "=", "len", "(", "good_ciphers", ")", "good_ciphers_array", "=", "new", "(", "Security", ",", "'uint32_t[]'", ",", "num_good_ciphers", ")", "array_set", "(", "good_ciphers_array", ",", "good_ciphers", ")", "good_ciphers_pointer", "=", "cast", "(", "Security", ",", "'uint32_t *'", ",", "good_ciphers_array", ")", "result", "=", "Security", ".", "SSLSetEnabledCiphers", "(", "session_context", ",", "good_ciphers_pointer", ",", "num_good_ciphers", ")", "handle_sec_error", "(", "result", ")", "# Set a peer id from the session to allow for session reuse, the hostname", "# is appended to prevent a bug on OS X 10.7 where it tries to reuse a", "# connection even if the hostnames are different.", "peer_id", "=", "self", ".", "_session", ".", "_peer_id", "+", "self", ".", "_hostname", ".", "encode", "(", "'utf-8'", ")", "result", "=", "Security", ".", "SSLSetPeerID", "(", "session_context", ",", "peer_id", ",", "len", "(", "peer_id", ")", ")", "handle_sec_error", "(", "result", ")", "handshake_result", "=", "Security", ".", "SSLHandshake", "(", "session_context", ")", "if", "self", ".", "_exception", "is", "not", "None", ":", "exception", "=", "self", ".", "_exception", "self", ".", "_exception", "=", "None", "raise", "exception", "while", "handshake_result", "==", "SecurityConst", ".", "errSSLWouldBlock", ":", "handshake_result", "=", "Security", ".", "SSLHandshake", "(", "session_context", ")", "if", "self", ".", "_exception", "is", "not", "None", ":", "exception", "=", "self", ".", "_exception", "self", ".", "_exception", "=", "None", "raise", "exception", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", "and", "osx_version_info", ">=", "(", "10", ",", "7", ")", ":", "do_validation", "=", "explicit_validation", "and", "handshake_result", "==", "0", "else", ":", "do_validation", "=", "explicit_validation", "and", "handshake_result", "==", "SecurityConst", ".", "errSSLServerAuthCompleted", "if", "do_validation", ":", "trust_ref_pointer", "=", "new", "(", "Security", ",", "'SecTrustRef *'", ")", "result", "=", "Security", ".", "SSLCopyPeerTrust", "(", "session_context", ",", "trust_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "trust_ref", "=", "unwrap", "(", "trust_ref_pointer", ")", "cf_string_hostname", "=", "CFHelpers", ".", "cf_string_from_unicode", "(", "self", ".", "_hostname", ")", "ssl_policy_ref", "=", "Security", ".", "SecPolicyCreateSSL", "(", "True", ",", "cf_string_hostname", ")", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "cf_string_hostname", ")", "handle_cf_error", "(", "result", ")", "# Create a new policy for OCSP checking to disable it", "ocsp_oid_pointer", "=", "struct", "(", "Security", ",", "'CSSM_OID'", ")", "ocsp_oid", "=", "unwrap", "(", "ocsp_oid_pointer", ")", "ocsp_oid", ".", "Length", "=", "len", "(", "SecurityConst", ".", "APPLE_TP_REVOCATION_OCSP", ")", "ocsp_oid_buffer", "=", "buffer_from_bytes", "(", "SecurityConst", ".", "APPLE_TP_REVOCATION_OCSP", ")", "ocsp_oid", ".", "Data", "=", "cast", "(", "Security", ",", "'char *'", ",", "ocsp_oid_buffer", ")", "ocsp_search_ref_pointer", "=", "new", "(", "Security", ",", "'SecPolicySearchRef *'", ")", "result", "=", "Security", ".", "SecPolicySearchCreate", "(", "SecurityConst", ".", "CSSM_CERT_X_509v3", ",", "ocsp_oid_pointer", ",", "null", "(", ")", ",", "ocsp_search_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "ocsp_search_ref", "=", "unwrap", "(", "ocsp_search_ref_pointer", ")", "ocsp_policy_ref_pointer", "=", "new", "(", "Security", ",", "'SecPolicyRef *'", ")", "result", "=", "Security", ".", "SecPolicySearchCopyNext", "(", "ocsp_search_ref", ",", "ocsp_policy_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "ocsp_policy_ref", "=", "unwrap", "(", "ocsp_policy_ref_pointer", ")", "ocsp_struct_pointer", "=", "struct", "(", "Security", ",", "'CSSM_APPLE_TP_OCSP_OPTIONS'", ")", "ocsp_struct", "=", "unwrap", "(", "ocsp_struct_pointer", ")", "ocsp_struct", ".", "Version", "=", "SecurityConst", ".", "CSSM_APPLE_TP_OCSP_OPTS_VERSION", "ocsp_struct", ".", "Flags", "=", "(", "SecurityConst", ".", "CSSM_TP_ACTION_OCSP_DISABLE_NET", "|", "SecurityConst", ".", "CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE", ")", "ocsp_struct_bytes", "=", "struct_bytes", "(", "ocsp_struct_pointer", ")", "cssm_data_pointer", "=", "struct", "(", "Security", ",", "'CSSM_DATA'", ")", "cssm_data", "=", "unwrap", "(", "cssm_data_pointer", ")", "cssm_data", ".", "Length", "=", "len", "(", "ocsp_struct_bytes", ")", "ocsp_struct_buffer", "=", "buffer_from_bytes", "(", "ocsp_struct_bytes", ")", "cssm_data", ".", "Data", "=", "cast", "(", "Security", ",", "'char *'", ",", "ocsp_struct_buffer", ")", "result", "=", "Security", ".", "SecPolicySetValue", "(", "ocsp_policy_ref", ",", "cssm_data_pointer", ")", "handle_sec_error", "(", "result", ")", "# Create a new policy for CRL checking to disable it", "crl_oid_pointer", "=", "struct", "(", "Security", ",", "'CSSM_OID'", ")", "crl_oid", "=", "unwrap", "(", "crl_oid_pointer", ")", "crl_oid", ".", "Length", "=", "len", "(", "SecurityConst", ".", "APPLE_TP_REVOCATION_CRL", ")", "crl_oid_buffer", "=", "buffer_from_bytes", "(", "SecurityConst", ".", "APPLE_TP_REVOCATION_CRL", ")", "crl_oid", ".", "Data", "=", "cast", "(", "Security", ",", "'char *'", ",", "crl_oid_buffer", ")", "crl_search_ref_pointer", "=", "new", "(", "Security", ",", "'SecPolicySearchRef *'", ")", "result", "=", "Security", ".", "SecPolicySearchCreate", "(", "SecurityConst", ".", "CSSM_CERT_X_509v3", ",", "crl_oid_pointer", ",", "null", "(", ")", ",", "crl_search_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "crl_search_ref", "=", "unwrap", "(", "crl_search_ref_pointer", ")", "crl_policy_ref_pointer", "=", "new", "(", "Security", ",", "'SecPolicyRef *'", ")", "result", "=", "Security", ".", "SecPolicySearchCopyNext", "(", "crl_search_ref", ",", "crl_policy_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "crl_policy_ref", "=", "unwrap", "(", "crl_policy_ref_pointer", ")", "crl_struct_pointer", "=", "struct", "(", "Security", ",", "'CSSM_APPLE_TP_CRL_OPTIONS'", ")", "crl_struct", "=", "unwrap", "(", "crl_struct_pointer", ")", "crl_struct", ".", "Version", "=", "SecurityConst", ".", "CSSM_APPLE_TP_CRL_OPTS_VERSION", "crl_struct", ".", "CrlFlags", "=", "0", "crl_struct_bytes", "=", "struct_bytes", "(", "crl_struct_pointer", ")", "cssm_data_pointer", "=", "struct", "(", "Security", ",", "'CSSM_DATA'", ")", "cssm_data", "=", "unwrap", "(", "cssm_data_pointer", ")", "cssm_data", ".", "Length", "=", "len", "(", "crl_struct_bytes", ")", "crl_struct_buffer", "=", "buffer_from_bytes", "(", "crl_struct_bytes", ")", "cssm_data", ".", "Data", "=", "cast", "(", "Security", ",", "'char *'", ",", "crl_struct_buffer", ")", "result", "=", "Security", ".", "SecPolicySetValue", "(", "crl_policy_ref", ",", "cssm_data_pointer", ")", "handle_sec_error", "(", "result", ")", "policy_array_ref", "=", "CFHelpers", ".", "cf_array_from_list", "(", "[", "ssl_policy_ref", ",", "crl_policy_ref", ",", "ocsp_policy_ref", "]", ")", "result", "=", "Security", ".", "SecTrustSetPolicies", "(", "trust_ref", ",", "policy_array_ref", ")", "handle_sec_error", "(", "result", ")", "if", "self", ".", "_session", ".", "_extra_trust_roots", ":", "ca_cert_refs", "=", "[", "]", "ca_certs", "=", "[", "]", "for", "cert", "in", "self", ".", "_session", ".", "_extra_trust_roots", ":", "ca_cert", "=", "load_certificate", "(", "cert", ")", "ca_certs", ".", "append", "(", "ca_cert", ")", "ca_cert_refs", ".", "append", "(", "ca_cert", ".", "sec_certificate_ref", ")", "result", "=", "Security", ".", "SecTrustSetAnchorCertificatesOnly", "(", "trust_ref", ",", "False", ")", "handle_sec_error", "(", "result", ")", "array_ref", "=", "CFHelpers", ".", "cf_array_from_list", "(", "ca_cert_refs", ")", "result", "=", "Security", ".", "SecTrustSetAnchorCertificates", "(", "trust_ref", ",", "array_ref", ")", "handle_sec_error", "(", "result", ")", "result_pointer", "=", "new", "(", "Security", ",", "'SecTrustResultType *'", ")", "result", "=", "Security", ".", "SecTrustEvaluate", "(", "trust_ref", ",", "result_pointer", ")", "handle_sec_error", "(", "result", ")", "trust_result_code", "=", "deref", "(", "result_pointer", ")", "invalid_chain_error_codes", "=", "set", "(", "[", "SecurityConst", ".", "kSecTrustResultProceed", ",", "SecurityConst", ".", "kSecTrustResultUnspecified", "]", ")", "if", "trust_result_code", "not", "in", "invalid_chain_error_codes", ":", "handshake_result", "=", "SecurityConst", ".", "errSSLXCertChainInvalid", "else", ":", "handshake_result", "=", "Security", ".", "SSLHandshake", "(", "session_context", ")", "while", "handshake_result", "==", "SecurityConst", ".", "errSSLWouldBlock", ":", "handshake_result", "=", "Security", ".", "SSLHandshake", "(", "session_context", ")", "self", ".", "_done_handshake", "=", "True", "handshake_error_codes", "=", "set", "(", "[", "SecurityConst", ".", "errSSLXCertChainInvalid", ",", "SecurityConst", ".", "errSSLCertExpired", ",", "SecurityConst", ".", "errSSLCertNotYetValid", ",", "SecurityConst", ".", "errSSLUnknownRootCert", ",", "SecurityConst", ".", "errSSLNoRootCert", ",", "SecurityConst", ".", "errSSLHostNameMismatch", ",", "SecurityConst", ".", "errSSLInternal", ",", "]", ")", "# In testing, only errSSLXCertChainInvalid was ever returned for", "# all of these different situations, however we include the others", "# for completeness. To get the real reason we have to use the", "# certificate from the handshake and use the deprecated function", "# SecTrustGetCssmResultCode().", "if", "handshake_result", "in", "handshake_error_codes", ":", "trust_ref_pointer", "=", "new", "(", "Security", ",", "'SecTrustRef *'", ")", "result", "=", "Security", ".", "SSLCopyPeerTrust", "(", "session_context", ",", "trust_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "trust_ref", "=", "unwrap", "(", "trust_ref_pointer", ")", "result_code_pointer", "=", "new", "(", "Security", ",", "'OSStatus *'", ")", "result", "=", "Security", ".", "SecTrustGetCssmResultCode", "(", "trust_ref", ",", "result_code_pointer", ")", "result_code", "=", "deref", "(", "result_code_pointer", ")", "chain", "=", "extract_chain", "(", "self", ".", "_server_hello", ")", "self_signed", "=", "False", "revoked", "=", "False", "expired", "=", "False", "not_yet_valid", "=", "False", "no_issuer", "=", "False", "cert", "=", "None", "bad_hostname", "=", "False", "if", "chain", ":", "cert", "=", "chain", "[", "0", "]", "oscrypto_cert", "=", "load_certificate", "(", "cert", ")", "self_signed", "=", "oscrypto_cert", ".", "self_signed", "revoked", "=", "result_code", "==", "SecurityConst", ".", "CSSMERR_TP_CERT_REVOKED", "no_issuer", "=", "not", "self_signed", "and", "result_code", "==", "SecurityConst", ".", "CSSMERR_TP_NOT_TRUSTED", "expired", "=", "result_code", "==", "SecurityConst", ".", "CSSMERR_TP_CERT_EXPIRED", "not_yet_valid", "=", "result_code", "==", "SecurityConst", ".", "CSSMERR_TP_CERT_NOT_VALID_YET", "bad_hostname", "=", "result_code", "==", "SecurityConst", ".", "CSSMERR_APPLETP_HOSTNAME_MISMATCH", "# On macOS 10.12, some expired certificates return errSSLInternal", "if", "osx_version_info", ">=", "(", "10", ",", "12", ")", ":", "validity", "=", "cert", "[", "'tbs_certificate'", "]", "[", "'validity'", "]", "not_before", "=", "validity", "[", "'not_before'", "]", ".", "chosen", ".", "native", "not_after", "=", "validity", "[", "'not_after'", "]", ".", "chosen", ".", "native", "utcnow", "=", "datetime", ".", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "expired", "=", "not_after", "<", "utcnow", "not_yet_valid", "=", "not_before", ">", "utcnow", "if", "chain", "and", "chain", "[", "0", "]", ".", "hash_algo", "in", "set", "(", "[", "'md5'", ",", "'md2'", "]", ")", ":", "raise_weak_signature", "(", "chain", "[", "0", "]", ")", "if", "revoked", ":", "raise_revoked", "(", "cert", ")", "if", "bad_hostname", ":", "raise_hostname", "(", "cert", ",", "self", ".", "_hostname", ")", "elif", "expired", "or", "not_yet_valid", ":", "raise_expired_not_yet_valid", "(", "cert", ")", "elif", "no_issuer", ":", "raise_no_issuer", "(", "cert", ")", "elif", "self_signed", ":", "raise_self_signed", "(", "cert", ")", "if", "detect_client_auth_request", "(", "self", ".", "_server_hello", ")", ":", "raise_client_auth", "(", ")", "raise_verification", "(", "cert", ")", "if", "handshake_result", "==", "SecurityConst", ".", "errSSLPeerHandshakeFail", ":", "if", "detect_client_auth_request", "(", "self", ".", "_server_hello", ")", ":", "raise_client_auth", "(", ")", "raise_handshake", "(", ")", "if", "handshake_result", "==", "SecurityConst", ".", "errSSLWeakPeerEphemeralDHKey", ":", "raise_dh_params", "(", ")", "if", "handshake_result", "==", "SecurityConst", ".", "errSSLPeerProtocolVersion", ":", "raise_protocol_version", "(", ")", "if", "handshake_result", "in", "set", "(", "[", "SecurityConst", ".", "errSSLRecordOverflow", ",", "SecurityConst", ".", "errSSLProtocol", "]", ")", ":", "self", ".", "_server_hello", "+=", "_read_remaining", "(", "self", ".", "_socket", ")", "raise_protocol_error", "(", "self", ".", "_server_hello", ")", "if", "handshake_result", "in", "set", "(", "[", "SecurityConst", ".", "errSSLClosedNoNotify", ",", "SecurityConst", ".", "errSSLClosedAbort", "]", ")", ":", "if", "not", "self", ".", "_done_handshake", ":", "self", ".", "_server_hello", "+=", "_read_remaining", "(", "self", ".", "_socket", ")", "if", "detect_other_protocol", "(", "self", ".", "_server_hello", ")", ":", "raise_protocol_error", "(", "self", ".", "_server_hello", ")", "raise_disconnection", "(", ")", "if", "osx_version_info", "<", "(", "10", ",", "10", ")", ":", "dh_params_length", "=", "get_dh_params_length", "(", "self", ".", "_server_hello", ")", "if", "dh_params_length", "is", "not", "None", "and", "dh_params_length", "<", "1024", ":", "raise_dh_params", "(", ")", "would_block", "=", "handshake_result", "==", "SecurityConst", ".", "errSSLWouldBlock", "server_auth_complete", "=", "handshake_result", "==", "SecurityConst", ".", "errSSLServerAuthCompleted", "manual_validation", "=", "self", ".", "_session", ".", "_manual_validation", "and", "server_auth_complete", "if", "not", "would_block", "and", "not", "manual_validation", ":", "handle_sec_error", "(", "handshake_result", ",", "TLSError", ")", "self", ".", "_session_context", "=", "session_context", "protocol_const_pointer", "=", "new", "(", "Security", ",", "'SSLProtocol *'", ")", "result", "=", "Security", ".", "SSLGetNegotiatedProtocolVersion", "(", "session_context", ",", "protocol_const_pointer", ")", "handle_sec_error", "(", "result", ")", "protocol_const", "=", "deref", "(", "protocol_const_pointer", ")", "self", ".", "_protocol", "=", "_PROTOCOL_CONST_STRING_MAP", "[", "protocol_const", "]", "cipher_int_pointer", "=", "new", "(", "Security", ",", "'SSLCipherSuite *'", ")", "result", "=", "Security", ".", "SSLGetNegotiatedCipher", "(", "session_context", ",", "cipher_int_pointer", ")", "handle_sec_error", "(", "result", ")", "cipher_int", "=", "deref", "(", "cipher_int_pointer", ")", "cipher_bytes", "=", "int_to_bytes", "(", "cipher_int", ",", "width", "=", "2", ")", "self", ".", "_cipher_suite", "=", "CIPHER_SUITE_MAP", ".", "get", "(", "cipher_bytes", ",", "cipher_bytes", ")", "session_info", "=", "parse_session_info", "(", "self", ".", "_server_hello", ",", "self", ".", "_client_hello", ")", "self", ".", "_compression", "=", "session_info", "[", "'compression'", "]", "self", ".", "_session_id", "=", "session_info", "[", "'session_id'", "]", "self", ".", "_session_ticket", "=", "session_info", "[", "'session_ticket'", "]", "except", "(", "OSError", ",", "socket_", ".", "error", ")", ":", "if", "session_context", ":", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", ":", "result", "=", "Security", ".", "SSLDisposeContext", "(", "session_context", ")", "handle_sec_error", "(", "result", ")", "else", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "session_context", ")", "handle_cf_error", "(", "result", ")", "self", ".", "_session_context", "=", "None", "self", ".", "close", "(", ")", "raise", "finally", ":", "# Trying to release crl_search_ref or ocsp_search_ref results in", "# a segmentation fault, so we do not do that", "if", "ssl_policy_ref", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "ssl_policy_ref", ")", "handle_cf_error", "(", "result", ")", "ssl_policy_ref", "=", "None", "if", "crl_policy_ref", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "crl_policy_ref", ")", "handle_cf_error", "(", "result", ")", "crl_policy_ref", "=", "None", "if", "ocsp_policy_ref", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "ocsp_policy_ref", ")", "handle_cf_error", "(", "result", ")", "ocsp_policy_ref", "=", "None", "if", "policy_array_ref", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "policy_array_ref", ")", "handle_cf_error", "(", "result", ")", "policy_array_ref", "=", "None" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket.read
Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read
oscrypto/_osx/tls.py
def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read """ if not isinstance(max_length, int_types): raise TypeError(pretty_message( ''' max_length must be an integer, not %s ''', type_name(max_length) )) if self._session_context is None: # Even if the session is closed, we can use # buffered data to respond to read requests if self._decrypted_bytes != b'': output = self._decrypted_bytes self._decrypted_bytes = b'' return output self._raise_closed() buffered_length = len(self._decrypted_bytes) # If we already have enough buffered data, just use that if buffered_length >= max_length: output = self._decrypted_bytes[0:max_length] self._decrypted_bytes = self._decrypted_bytes[max_length:] return output # Don't block if we have buffered data available, since it is ok to # return less than the max_length if buffered_length > 0 and not self.select_read(0): output = self._decrypted_bytes self._decrypted_bytes = b'' return output # Only read enough to get the requested amount when # combined with buffered data to_read = max_length - len(self._decrypted_bytes) read_buffer = buffer_from_bytes(to_read) processed_pointer = new(Security, 'size_t *') result = Security.SSLRead( self._session_context, read_buffer, to_read, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception if result and result not in set([SecurityConst.errSSLWouldBlock, SecurityConst.errSSLClosedGraceful]): handle_sec_error(result, TLSError) if result and result == SecurityConst.errSSLClosedGraceful: self._gracefully_closed = True self._shutdown(False) self._raise_closed() bytes_read = deref(processed_pointer) output = self._decrypted_bytes + bytes_from_buffer(read_buffer, bytes_read) self._decrypted_bytes = output[max_length:] return output[0:max_length]
def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read """ if not isinstance(max_length, int_types): raise TypeError(pretty_message( ''' max_length must be an integer, not %s ''', type_name(max_length) )) if self._session_context is None: # Even if the session is closed, we can use # buffered data to respond to read requests if self._decrypted_bytes != b'': output = self._decrypted_bytes self._decrypted_bytes = b'' return output self._raise_closed() buffered_length = len(self._decrypted_bytes) # If we already have enough buffered data, just use that if buffered_length >= max_length: output = self._decrypted_bytes[0:max_length] self._decrypted_bytes = self._decrypted_bytes[max_length:] return output # Don't block if we have buffered data available, since it is ok to # return less than the max_length if buffered_length > 0 and not self.select_read(0): output = self._decrypted_bytes self._decrypted_bytes = b'' return output # Only read enough to get the requested amount when # combined with buffered data to_read = max_length - len(self._decrypted_bytes) read_buffer = buffer_from_bytes(to_read) processed_pointer = new(Security, 'size_t *') result = Security.SSLRead( self._session_context, read_buffer, to_read, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception if result and result not in set([SecurityConst.errSSLWouldBlock, SecurityConst.errSSLClosedGraceful]): handle_sec_error(result, TLSError) if result and result == SecurityConst.errSSLClosedGraceful: self._gracefully_closed = True self._shutdown(False) self._raise_closed() bytes_read = deref(processed_pointer) output = self._decrypted_bytes + bytes_from_buffer(read_buffer, bytes_read) self._decrypted_bytes = output[max_length:] return output[0:max_length]
[ "Reads", "data", "from", "the", "TLS", "-", "wrapped", "socket" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1006-L1087
[ "def", "read", "(", "self", ",", "max_length", ")", ":", "if", "not", "isinstance", "(", "max_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n max_length must be an integer, not %s\n '''", ",", "type_name", "(", "max_length", ")", ")", ")", "if", "self", ".", "_session_context", "is", "None", ":", "# Even if the session is closed, we can use", "# buffered data to respond to read requests", "if", "self", ".", "_decrypted_bytes", "!=", "b''", ":", "output", "=", "self", ".", "_decrypted_bytes", "self", ".", "_decrypted_bytes", "=", "b''", "return", "output", "self", ".", "_raise_closed", "(", ")", "buffered_length", "=", "len", "(", "self", ".", "_decrypted_bytes", ")", "# If we already have enough buffered data, just use that", "if", "buffered_length", ">=", "max_length", ":", "output", "=", "self", ".", "_decrypted_bytes", "[", "0", ":", "max_length", "]", "self", ".", "_decrypted_bytes", "=", "self", ".", "_decrypted_bytes", "[", "max_length", ":", "]", "return", "output", "# Don't block if we have buffered data available, since it is ok to", "# return less than the max_length", "if", "buffered_length", ">", "0", "and", "not", "self", ".", "select_read", "(", "0", ")", ":", "output", "=", "self", ".", "_decrypted_bytes", "self", ".", "_decrypted_bytes", "=", "b''", "return", "output", "# Only read enough to get the requested amount when", "# combined with buffered data", "to_read", "=", "max_length", "-", "len", "(", "self", ".", "_decrypted_bytes", ")", "read_buffer", "=", "buffer_from_bytes", "(", "to_read", ")", "processed_pointer", "=", "new", "(", "Security", ",", "'size_t *'", ")", "result", "=", "Security", ".", "SSLRead", "(", "self", ".", "_session_context", ",", "read_buffer", ",", "to_read", ",", "processed_pointer", ")", "if", "self", ".", "_exception", "is", "not", "None", ":", "exception", "=", "self", ".", "_exception", "self", ".", "_exception", "=", "None", "raise", "exception", "if", "result", "and", "result", "not", "in", "set", "(", "[", "SecurityConst", ".", "errSSLWouldBlock", ",", "SecurityConst", ".", "errSSLClosedGraceful", "]", ")", ":", "handle_sec_error", "(", "result", ",", "TLSError", ")", "if", "result", "and", "result", "==", "SecurityConst", ".", "errSSLClosedGraceful", ":", "self", ".", "_gracefully_closed", "=", "True", "self", ".", "_shutdown", "(", "False", ")", "self", ".", "_raise_closed", "(", ")", "bytes_read", "=", "deref", "(", "processed_pointer", ")", "output", "=", "self", ".", "_decrypted_bytes", "+", "bytes_from_buffer", "(", "read_buffer", ",", "bytes_read", ")", "self", ".", "_decrypted_bytes", "=", "output", "[", "max_length", ":", "]", "return", "output", "[", "0", ":", "max_length", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket.read_until
Reads data from the socket until a marker is found. Data read includes the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read, including the marker
oscrypto/_osx/tls.py
def read_until(self, marker): """ Reads data from the socket until a marker is found. Data read includes the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read, including the marker """ if not isinstance(marker, byte_cls) and not isinstance(marker, Pattern): raise TypeError(pretty_message( ''' marker must be a byte string or compiled regex object, not %s ''', type_name(marker) )) output = b'' is_regex = isinstance(marker, Pattern) while True: if len(self._decrypted_bytes) > 0: chunk = self._decrypted_bytes self._decrypted_bytes = b'' else: to_read = self._os_buffered_size() or 8192 chunk = self.read(to_read) offset = len(output) output += chunk if is_regex: match = marker.search(output) if match is not None: end = match.end() break else: # If the marker was not found last time, we have to start # at a position where the marker would have its final char # in the newly read chunk start = max(0, offset - len(marker) - 1) match = output.find(marker, start) if match != -1: end = match + len(marker) break self._decrypted_bytes = output[end:] + self._decrypted_bytes return output[0:end]
def read_until(self, marker): """ Reads data from the socket until a marker is found. Data read includes the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read, including the marker """ if not isinstance(marker, byte_cls) and not isinstance(marker, Pattern): raise TypeError(pretty_message( ''' marker must be a byte string or compiled regex object, not %s ''', type_name(marker) )) output = b'' is_regex = isinstance(marker, Pattern) while True: if len(self._decrypted_bytes) > 0: chunk = self._decrypted_bytes self._decrypted_bytes = b'' else: to_read = self._os_buffered_size() or 8192 chunk = self.read(to_read) offset = len(output) output += chunk if is_regex: match = marker.search(output) if match is not None: end = match.end() break else: # If the marker was not found last time, we have to start # at a position where the marker would have its final char # in the newly read chunk start = max(0, offset - len(marker) - 1) match = output.find(marker, start) if match != -1: end = match + len(marker) break self._decrypted_bytes = output[end:] + self._decrypted_bytes return output[0:end]
[ "Reads", "data", "from", "the", "socket", "until", "a", "marker", "is", "found", ".", "Data", "read", "includes", "the", "marker", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1109-L1163
[ "def", "read_until", "(", "self", ",", "marker", ")", ":", "if", "not", "isinstance", "(", "marker", ",", "byte_cls", ")", "and", "not", "isinstance", "(", "marker", ",", "Pattern", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n marker must be a byte string or compiled regex object, not %s\n '''", ",", "type_name", "(", "marker", ")", ")", ")", "output", "=", "b''", "is_regex", "=", "isinstance", "(", "marker", ",", "Pattern", ")", "while", "True", ":", "if", "len", "(", "self", ".", "_decrypted_bytes", ")", ">", "0", ":", "chunk", "=", "self", ".", "_decrypted_bytes", "self", ".", "_decrypted_bytes", "=", "b''", "else", ":", "to_read", "=", "self", ".", "_os_buffered_size", "(", ")", "or", "8192", "chunk", "=", "self", ".", "read", "(", "to_read", ")", "offset", "=", "len", "(", "output", ")", "output", "+=", "chunk", "if", "is_regex", ":", "match", "=", "marker", ".", "search", "(", "output", ")", "if", "match", "is", "not", "None", ":", "end", "=", "match", ".", "end", "(", ")", "break", "else", ":", "# If the marker was not found last time, we have to start", "# at a position where the marker would have its final char", "# in the newly read chunk", "start", "=", "max", "(", "0", ",", "offset", "-", "len", "(", "marker", ")", "-", "1", ")", "match", "=", "output", ".", "find", "(", "marker", ",", "start", ")", "if", "match", "!=", "-", "1", ":", "end", "=", "match", "+", "len", "(", "marker", ")", "break", "self", ".", "_decrypted_bytes", "=", "output", "[", "end", ":", "]", "+", "self", ".", "_decrypted_bytes", "return", "output", "[", "0", ":", "end", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket._os_buffered_size
Returns the number of bytes of decrypted data stored in the Secure Transport read buffer. This amount of data can be read from SSLRead() without calling self._socket.recv(). :return: An integer - the number of available bytes
oscrypto/_osx/tls.py
def _os_buffered_size(self): """ Returns the number of bytes of decrypted data stored in the Secure Transport read buffer. This amount of data can be read from SSLRead() without calling self._socket.recv(). :return: An integer - the number of available bytes """ num_bytes_pointer = new(Security, 'size_t *') result = Security.SSLGetBufferedReadSize( self._session_context, num_bytes_pointer ) handle_sec_error(result) return deref(num_bytes_pointer)
def _os_buffered_size(self): """ Returns the number of bytes of decrypted data stored in the Secure Transport read buffer. This amount of data can be read from SSLRead() without calling self._socket.recv(). :return: An integer - the number of available bytes """ num_bytes_pointer = new(Security, 'size_t *') result = Security.SSLGetBufferedReadSize( self._session_context, num_bytes_pointer ) handle_sec_error(result) return deref(num_bytes_pointer)
[ "Returns", "the", "number", "of", "bytes", "of", "decrypted", "data", "stored", "in", "the", "Secure", "Transport", "read", "buffer", ".", "This", "amount", "of", "data", "can", "be", "read", "from", "SSLRead", "()", "without", "calling", "self", ".", "_socket", ".", "recv", "()", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1165-L1182
[ "def", "_os_buffered_size", "(", "self", ")", ":", "num_bytes_pointer", "=", "new", "(", "Security", ",", "'size_t *'", ")", "result", "=", "Security", ".", "SSLGetBufferedReadSize", "(", "self", ".", "_session_context", ",", "num_bytes_pointer", ")", "handle_sec_error", "(", "result", ")", "return", "deref", "(", "num_bytes_pointer", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket.write
Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library
oscrypto/_osx/tls.py
def write(self, data): """ Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if self._session_context is None: self._raise_closed() processed_pointer = new(Security, 'size_t *') data_len = len(data) while data_len: write_buffer = buffer_from_bytes(data) result = Security.SSLWrite( self._session_context, write_buffer, data_len, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception handle_sec_error(result, TLSError) bytes_written = deref(processed_pointer) data = data[bytes_written:] data_len = len(data) if data_len > 0: self.select_write()
def write(self, data): """ Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if self._session_context is None: self._raise_closed() processed_pointer = new(Security, 'size_t *') data_len = len(data) while data_len: write_buffer = buffer_from_bytes(data) result = Security.SSLWrite( self._session_context, write_buffer, data_len, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception handle_sec_error(result, TLSError) bytes_written = deref(processed_pointer) data = data[bytes_written:] data_len = len(data) if data_len > 0: self.select_write()
[ "Writes", "data", "to", "the", "TLS", "-", "wrapped", "socket" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1214-L1255
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "self", ".", "_raise_closed", "(", ")", "processed_pointer", "=", "new", "(", "Security", ",", "'size_t *'", ")", "data_len", "=", "len", "(", "data", ")", "while", "data_len", ":", "write_buffer", "=", "buffer_from_bytes", "(", "data", ")", "result", "=", "Security", ".", "SSLWrite", "(", "self", ".", "_session_context", ",", "write_buffer", ",", "data_len", ",", "processed_pointer", ")", "if", "self", ".", "_exception", "is", "not", "None", ":", "exception", "=", "self", ".", "_exception", "self", ".", "_exception", "=", "None", "raise", "exception", "handle_sec_error", "(", "result", ",", "TLSError", ")", "bytes_written", "=", "deref", "(", "processed_pointer", ")", "data", "=", "data", "[", "bytes_written", ":", "]", "data_len", "=", "len", "(", "data", ")", "if", "data_len", ">", "0", ":", "self", ".", "select_write", "(", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket._shutdown
Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown
oscrypto/_osx/tls.py
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._session_context is None: return # Ignore error during close in case other end closed already result = Security.SSLClose(self._session_context) if osx_version_info < (10, 8): result = Security.SSLDisposeContext(self._session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(self._session_context) handle_cf_error(result) self._session_context = None if manual: self._local_closed = True try: self._socket.shutdown(socket_.SHUT_RDWR) except (socket_.error): pass
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._session_context is None: return # Ignore error during close in case other end closed already result = Security.SSLClose(self._session_context) if osx_version_info < (10, 8): result = Security.SSLDisposeContext(self._session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(self._session_context) handle_cf_error(result) self._session_context = None if manual: self._local_closed = True try: self._socket.shutdown(socket_.SHUT_RDWR) except (socket_.error): pass
[ "Shuts", "down", "the", "TLS", "session", "and", "then", "shuts", "down", "the", "underlying", "socket" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1273-L1302
[ "def", "_shutdown", "(", "self", ",", "manual", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "return", "# Ignore error during close in case other end closed already", "result", "=", "Security", ".", "SSLClose", "(", "self", ".", "_session_context", ")", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", ":", "result", "=", "Security", ".", "SSLDisposeContext", "(", "self", ".", "_session_context", ")", "handle_sec_error", "(", "result", ")", "else", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "self", ".", "_session_context", ")", "handle_cf_error", "(", "result", ")", "self", ".", "_session_context", "=", "None", "if", "manual", ":", "self", ".", "_local_closed", "=", "True", "try", ":", "self", ".", "_socket", ".", "shutdown", "(", "socket_", ".", "SHUT_RDWR", ")", "except", "(", "socket_", ".", "error", ")", ":", "pass" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket.close
Shuts down the TLS session and socket and forcibly closes it
oscrypto/_osx/tls.py
def close(self): """ Shuts down the TLS session and socket and forcibly closes it """ try: self.shutdown() finally: if self._socket: try: self._socket.close() except (socket_.error): pass self._socket = None if self._connection_id in _socket_refs: del _socket_refs[self._connection_id]
def close(self): """ Shuts down the TLS session and socket and forcibly closes it """ try: self.shutdown() finally: if self._socket: try: self._socket.close() except (socket_.error): pass self._socket = None if self._connection_id in _socket_refs: del _socket_refs[self._connection_id]
[ "Shuts", "down", "the", "TLS", "session", "and", "socket", "and", "forcibly", "closes", "it" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1311-L1328
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "shutdown", "(", ")", "finally", ":", "if", "self", ".", "_socket", ":", "try", ":", "self", ".", "_socket", ".", "close", "(", ")", "except", "(", "socket_", ".", "error", ")", ":", "pass", "self", ".", "_socket", "=", "None", "if", "self", ".", "_connection_id", "in", "_socket_refs", ":", "del", "_socket_refs", "[", "self", ".", "_connection_id", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket._read_certificates
Reads end-entity and intermediate certificate information from the TLS session
oscrypto/_osx/tls.py
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ trust_ref = None cf_data_ref = None result = None try: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( self._session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) number_certs = Security.SecTrustGetCertificateCount(trust_ref) self._intermediates = [] for index in range(0, number_certs): sec_certificate_ref = Security.SecTrustGetCertificateAtIndex( trust_ref, index ) cf_data_ref = Security.SecCertificateCopyData(sec_certificate_ref) cert_data = CFHelpers.cf_data_to_bytes(cf_data_ref) result = CoreFoundation.CFRelease(cf_data_ref) handle_cf_error(result) cf_data_ref = None cert = x509.Certificate.load(cert_data) if index == 0: self._certificate = cert else: self._intermediates.append(cert) finally: if trust_ref: result = CoreFoundation.CFRelease(trust_ref) handle_cf_error(result) if cf_data_ref: result = CoreFoundation.CFRelease(cf_data_ref) handle_cf_error(result)
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ trust_ref = None cf_data_ref = None result = None try: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( self._session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) number_certs = Security.SecTrustGetCertificateCount(trust_ref) self._intermediates = [] for index in range(0, number_certs): sec_certificate_ref = Security.SecTrustGetCertificateAtIndex( trust_ref, index ) cf_data_ref = Security.SecCertificateCopyData(sec_certificate_ref) cert_data = CFHelpers.cf_data_to_bytes(cf_data_ref) result = CoreFoundation.CFRelease(cf_data_ref) handle_cf_error(result) cf_data_ref = None cert = x509.Certificate.load(cert_data) if index == 0: self._certificate = cert else: self._intermediates.append(cert) finally: if trust_ref: result = CoreFoundation.CFRelease(trust_ref) handle_cf_error(result) if cf_data_ref: result = CoreFoundation.CFRelease(cf_data_ref) handle_cf_error(result)
[ "Reads", "end", "-", "entity", "and", "intermediate", "certificate", "information", "from", "the", "TLS", "session" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1330-L1380
[ "def", "_read_certificates", "(", "self", ")", ":", "trust_ref", "=", "None", "cf_data_ref", "=", "None", "result", "=", "None", "try", ":", "trust_ref_pointer", "=", "new", "(", "Security", ",", "'SecTrustRef *'", ")", "result", "=", "Security", ".", "SSLCopyPeerTrust", "(", "self", ".", "_session_context", ",", "trust_ref_pointer", ")", "handle_sec_error", "(", "result", ")", "trust_ref", "=", "unwrap", "(", "trust_ref_pointer", ")", "number_certs", "=", "Security", ".", "SecTrustGetCertificateCount", "(", "trust_ref", ")", "self", ".", "_intermediates", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "number_certs", ")", ":", "sec_certificate_ref", "=", "Security", ".", "SecTrustGetCertificateAtIndex", "(", "trust_ref", ",", "index", ")", "cf_data_ref", "=", "Security", ".", "SecCertificateCopyData", "(", "sec_certificate_ref", ")", "cert_data", "=", "CFHelpers", ".", "cf_data_to_bytes", "(", "cf_data_ref", ")", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "cf_data_ref", ")", "handle_cf_error", "(", "result", ")", "cf_data_ref", "=", "None", "cert", "=", "x509", ".", "Certificate", ".", "load", "(", "cert_data", ")", "if", "index", "==", "0", ":", "self", ".", "_certificate", "=", "cert", "else", ":", "self", ".", "_intermediates", ".", "append", "(", "cert", ")", "finally", ":", "if", "trust_ref", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "trust_ref", ")", "handle_cf_error", "(", "result", ")", "if", "cf_data_ref", ":", "result", "=", "CoreFoundation", ".", "CFRelease", "(", "cf_data_ref", ")", "handle_cf_error", "(", "result", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket.certificate
An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server
oscrypto/_osx/tls.py
def certificate(self): """ An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server """ if self._session_context is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._certificate
def certificate(self): """ An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server """ if self._session_context is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._certificate
[ "An", "asn1crypto", ".", "x509", ".", "Certificate", "object", "of", "the", "end", "-", "entity", "certificate", "presented", "by", "the", "server" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1396-L1408
[ "def", "certificate", "(", "self", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "self", ".", "_raise_closed", "(", ")", "if", "self", ".", "_certificate", "is", "None", ":", "self", ".", "_read_certificates", "(", ")", "return", "self", ".", "_certificate" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
TLSSocket.intermediates
A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server
oscrypto/_osx/tls.py
def intermediates(self): """ A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server """ if self._session_context is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._intermediates
def intermediates(self): """ A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server """ if self._session_context is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._intermediates
[ "A", "list", "of", "asn1crypto", ".", "x509", ".", "Certificate", "objects", "that", "were", "presented", "as", "intermediates", "by", "the", "server" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1411-L1423
[ "def", "intermediates", "(", "self", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "self", ".", "_raise_closed", "(", ")", "if", "self", ".", "_certificate", "is", "None", ":", "self", ".", "_read_certificates", "(", ")", "return", "self", ".", "_intermediates" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
get_path
Get the filesystem path to a file that contains OpenSSL-compatible CA certs. On OS X and Windows, there are extracted from the system certificate store and cached in a file on the filesystem. This path should not be writable by other users, otherwise they could inject CA certs into the trust list. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :param cache_length: The number of hours to cache the CA certs on OS X and Windows :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. This is only called on Windows and OS X when passed to this function. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: The full filesystem path to a CA certs file
oscrypto/trust_list.py
def get_path(temp_dir=None, cache_length=24, cert_callback=None): """ Get the filesystem path to a file that contains OpenSSL-compatible CA certs. On OS X and Windows, there are extracted from the system certificate store and cached in a file on the filesystem. This path should not be writable by other users, otherwise they could inject CA certs into the trust list. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :param cache_length: The number of hours to cache the CA certs on OS X and Windows :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. This is only called on Windows and OS X when passed to this function. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: The full filesystem path to a CA certs file """ ca_path, temp = _ca_path(temp_dir) # Windows and OS X if temp and _cached_path_needs_update(ca_path, cache_length): empty_set = set() any_purpose = '2.5.29.37.0' apple_ssl = '1.2.840.113635.100.1.3' win_server_auth = '1.3.6.1.5.5.7.3.1' with path_lock: if _cached_path_needs_update(ca_path, cache_length): with open(ca_path, 'wb') as f: for cert, trust_oids, reject_oids in extract_from_system(cert_callback, True): if sys.platform == 'darwin': if trust_oids != empty_set and any_purpose not in trust_oids \ and apple_ssl not in trust_oids: if cert_callback: cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS') continue if reject_oids != empty_set and (apple_ssl in reject_oids or any_purpose in reject_oids): if cert_callback: cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS') continue elif sys.platform == 'win32': if trust_oids != empty_set and any_purpose not in trust_oids \ and win_server_auth not in trust_oids: if cert_callback: cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS') continue if reject_oids != empty_set and (win_server_auth in reject_oids or any_purpose in reject_oids): if cert_callback: cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS') continue if cert_callback: cert_callback(Certificate.load(cert), None) f.write(armor('CERTIFICATE', cert)) if not ca_path: raise CACertsError('No CA certs found') return ca_path
def get_path(temp_dir=None, cache_length=24, cert_callback=None): """ Get the filesystem path to a file that contains OpenSSL-compatible CA certs. On OS X and Windows, there are extracted from the system certificate store and cached in a file on the filesystem. This path should not be writable by other users, otherwise they could inject CA certs into the trust list. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :param cache_length: The number of hours to cache the CA certs on OS X and Windows :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. This is only called on Windows and OS X when passed to this function. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: The full filesystem path to a CA certs file """ ca_path, temp = _ca_path(temp_dir) # Windows and OS X if temp and _cached_path_needs_update(ca_path, cache_length): empty_set = set() any_purpose = '2.5.29.37.0' apple_ssl = '1.2.840.113635.100.1.3' win_server_auth = '1.3.6.1.5.5.7.3.1' with path_lock: if _cached_path_needs_update(ca_path, cache_length): with open(ca_path, 'wb') as f: for cert, trust_oids, reject_oids in extract_from_system(cert_callback, True): if sys.platform == 'darwin': if trust_oids != empty_set and any_purpose not in trust_oids \ and apple_ssl not in trust_oids: if cert_callback: cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS') continue if reject_oids != empty_set and (apple_ssl in reject_oids or any_purpose in reject_oids): if cert_callback: cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS') continue elif sys.platform == 'win32': if trust_oids != empty_set and any_purpose not in trust_oids \ and win_server_auth not in trust_oids: if cert_callback: cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS') continue if reject_oids != empty_set and (win_server_auth in reject_oids or any_purpose in reject_oids): if cert_callback: cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS') continue if cert_callback: cert_callback(Certificate.load(cert), None) f.write(armor('CERTIFICATE', cert)) if not ca_path: raise CACertsError('No CA certs found') return ca_path
[ "Get", "the", "filesystem", "path", "to", "a", "file", "that", "contains", "OpenSSL", "-", "compatible", "CA", "certs", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L67-L140
[ "def", "get_path", "(", "temp_dir", "=", "None", ",", "cache_length", "=", "24", ",", "cert_callback", "=", "None", ")", ":", "ca_path", ",", "temp", "=", "_ca_path", "(", "temp_dir", ")", "# Windows and OS X", "if", "temp", "and", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "empty_set", "=", "set", "(", ")", "any_purpose", "=", "'2.5.29.37.0'", "apple_ssl", "=", "'1.2.840.113635.100.1.3'", "win_server_auth", "=", "'1.3.6.1.5.5.7.3.1'", "with", "path_lock", ":", "if", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "with", "open", "(", "ca_path", ",", "'wb'", ")", "as", "f", ":", "for", "cert", ",", "trust_oids", ",", "reject_oids", "in", "extract_from_system", "(", "cert_callback", ",", "True", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "if", "trust_oids", "!=", "empty_set", "and", "any_purpose", "not", "in", "trust_oids", "and", "apple_ssl", "not", "in", "trust_oids", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'implicitly distrusted for TLS'", ")", "continue", "if", "reject_oids", "!=", "empty_set", "and", "(", "apple_ssl", "in", "reject_oids", "or", "any_purpose", "in", "reject_oids", ")", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'explicitly distrusted for TLS'", ")", "continue", "elif", "sys", ".", "platform", "==", "'win32'", ":", "if", "trust_oids", "!=", "empty_set", "and", "any_purpose", "not", "in", "trust_oids", "and", "win_server_auth", "not", "in", "trust_oids", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'implicitly distrusted for TLS'", ")", "continue", "if", "reject_oids", "!=", "empty_set", "and", "(", "win_server_auth", "in", "reject_oids", "or", "any_purpose", "in", "reject_oids", ")", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'explicitly distrusted for TLS'", ")", "continue", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "None", ")", "f", ".", "write", "(", "armor", "(", "'CERTIFICATE'", ",", "cert", ")", ")", "if", "not", "ca_path", ":", "raise", "CACertsError", "(", "'No CA certs found'", ")", "return", "ca_path" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
get_list
Retrieves (and caches in memory) the list of CA certs from the OS. Includes trust information from the OS - purposes the certificate should be trusted or rejected for. Trust information is encoded via object identifiers (OIDs) that are sourced from various RFCs and vendors (Apple and Microsoft). This trust information augments what is in the certificate itself. Any OID that is in the set of trusted purposes indicates the certificate has been explicitly trusted for a purpose beyond the extended key purpose extension. Any OID in the reject set is a purpose that the certificate should not be trusted for, even if present in the extended key purpose extension. *A list of common trust OIDs can be found as part of the `KeyPurposeId()` class in the `asn1crypto.x509` module of the `asn1crypto` package.* :param cache_length: The number of hours to cache the CA certs in memory before they are refreshed :param map_vendor_oids: A bool indicating if the following mapping of OIDs should happen for trust information from the OS trust list: - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: A (copied) list of 3-element tuples containing CA certs from the OS trust ilst: - 0: an asn1crypto.x509.Certificate object - 1: a set of unicode strings of OIDs of trusted purposes - 2: a set of unicode strings of OIDs of rejected purposes
oscrypto/trust_list.py
def get_list(cache_length=24, map_vendor_oids=True, cert_callback=None): """ Retrieves (and caches in memory) the list of CA certs from the OS. Includes trust information from the OS - purposes the certificate should be trusted or rejected for. Trust information is encoded via object identifiers (OIDs) that are sourced from various RFCs and vendors (Apple and Microsoft). This trust information augments what is in the certificate itself. Any OID that is in the set of trusted purposes indicates the certificate has been explicitly trusted for a purpose beyond the extended key purpose extension. Any OID in the reject set is a purpose that the certificate should not be trusted for, even if present in the extended key purpose extension. *A list of common trust OIDs can be found as part of the `KeyPurposeId()` class in the `asn1crypto.x509` module of the `asn1crypto` package.* :param cache_length: The number of hours to cache the CA certs in memory before they are refreshed :param map_vendor_oids: A bool indicating if the following mapping of OIDs should happen for trust information from the OS trust list: - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: A (copied) list of 3-element tuples containing CA certs from the OS trust ilst: - 0: an asn1crypto.x509.Certificate object - 1: a set of unicode strings of OIDs of trusted purposes - 2: a set of unicode strings of OIDs of rejected purposes """ if not _in_memory_up_to_date(cache_length): with memory_lock: if not _in_memory_up_to_date(cache_length): certs = [] for cert_bytes, trust_oids, reject_oids in extract_from_system(cert_callback): if map_vendor_oids: trust_oids = _map_oids(trust_oids) reject_oids = _map_oids(reject_oids) certs.append((Certificate.load(cert_bytes), trust_oids, reject_oids)) _module_values['certs'] = certs _module_values['last_update'] = time.time() return list(_module_values['certs'])
def get_list(cache_length=24, map_vendor_oids=True, cert_callback=None): """ Retrieves (and caches in memory) the list of CA certs from the OS. Includes trust information from the OS - purposes the certificate should be trusted or rejected for. Trust information is encoded via object identifiers (OIDs) that are sourced from various RFCs and vendors (Apple and Microsoft). This trust information augments what is in the certificate itself. Any OID that is in the set of trusted purposes indicates the certificate has been explicitly trusted for a purpose beyond the extended key purpose extension. Any OID in the reject set is a purpose that the certificate should not be trusted for, even if present in the extended key purpose extension. *A list of common trust OIDs can be found as part of the `KeyPurposeId()` class in the `asn1crypto.x509` module of the `asn1crypto` package.* :param cache_length: The number of hours to cache the CA certs in memory before they are refreshed :param map_vendor_oids: A bool indicating if the following mapping of OIDs should happen for trust information from the OS trust list: - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: A (copied) list of 3-element tuples containing CA certs from the OS trust ilst: - 0: an asn1crypto.x509.Certificate object - 1: a set of unicode strings of OIDs of trusted purposes - 2: a set of unicode strings of OIDs of rejected purposes """ if not _in_memory_up_to_date(cache_length): with memory_lock: if not _in_memory_up_to_date(cache_length): certs = [] for cert_bytes, trust_oids, reject_oids in extract_from_system(cert_callback): if map_vendor_oids: trust_oids = _map_oids(trust_oids) reject_oids = _map_oids(reject_oids) certs.append((Certificate.load(cert_bytes), trust_oids, reject_oids)) _module_values['certs'] = certs _module_values['last_update'] = time.time() return list(_module_values['certs'])
[ "Retrieves", "(", "and", "caches", "in", "memory", ")", "the", "list", "of", "CA", "certs", "from", "the", "OS", ".", "Includes", "trust", "information", "from", "the", "OS", "-", "purposes", "the", "certificate", "should", "be", "trusted", "or", "rejected", "for", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L143-L209
[ "def", "get_list", "(", "cache_length", "=", "24", ",", "map_vendor_oids", "=", "True", ",", "cert_callback", "=", "None", ")", ":", "if", "not", "_in_memory_up_to_date", "(", "cache_length", ")", ":", "with", "memory_lock", ":", "if", "not", "_in_memory_up_to_date", "(", "cache_length", ")", ":", "certs", "=", "[", "]", "for", "cert_bytes", ",", "trust_oids", ",", "reject_oids", "in", "extract_from_system", "(", "cert_callback", ")", ":", "if", "map_vendor_oids", ":", "trust_oids", "=", "_map_oids", "(", "trust_oids", ")", "reject_oids", "=", "_map_oids", "(", "reject_oids", ")", "certs", ".", "append", "(", "(", "Certificate", ".", "load", "(", "cert_bytes", ")", ",", "trust_oids", ",", "reject_oids", ")", ")", "_module_values", "[", "'certs'", "]", "=", "certs", "_module_values", "[", "'last_update'", "]", "=", "time", ".", "time", "(", ")", "return", "list", "(", "_module_values", "[", "'certs'", "]", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
clear_cache
Clears any cached info that was exported from the OS trust store. This will ensure the latest changes are returned from calls to get_list() and get_path(), but at the expense of re-exporting and parsing all certificates. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. Must be the same value passed to get_path().
oscrypto/trust_list.py
def clear_cache(temp_dir=None): """ Clears any cached info that was exported from the OS trust store. This will ensure the latest changes are returned from calls to get_list() and get_path(), but at the expense of re-exporting and parsing all certificates. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. Must be the same value passed to get_path(). """ with memory_lock: _module_values['last_update'] = None _module_values['certs'] = None ca_path, temp = _ca_path(temp_dir) if temp: with path_lock: if os.path.exists(ca_path): os.remove(ca_path)
def clear_cache(temp_dir=None): """ Clears any cached info that was exported from the OS trust store. This will ensure the latest changes are returned from calls to get_list() and get_path(), but at the expense of re-exporting and parsing all certificates. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. Must be the same value passed to get_path(). """ with memory_lock: _module_values['last_update'] = None _module_values['certs'] = None ca_path, temp = _ca_path(temp_dir) if temp: with path_lock: if os.path.exists(ca_path): os.remove(ca_path)
[ "Clears", "any", "cached", "info", "that", "was", "exported", "from", "the", "OS", "trust", "store", ".", "This", "will", "ensure", "the", "latest", "changes", "are", "returned", "from", "calls", "to", "get_list", "()", "and", "get_path", "()", "but", "at", "the", "expense", "of", "re", "-", "exporting", "and", "parsing", "all", "certificates", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L212-L232
[ "def", "clear_cache", "(", "temp_dir", "=", "None", ")", ":", "with", "memory_lock", ":", "_module_values", "[", "'last_update'", "]", "=", "None", "_module_values", "[", "'certs'", "]", "=", "None", "ca_path", ",", "temp", "=", "_ca_path", "(", "temp_dir", ")", "if", "temp", ":", "with", "path_lock", ":", "if", "os", ".", "path", ".", "exists", "(", "ca_path", ")", ":", "os", ".", "remove", "(", "ca_path", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_ca_path
Returns the file path to the CA certs file :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :return: A 2-element tuple: - 0: A unicode string of the file path - 1: A bool if the file is a temporary file
oscrypto/trust_list.py
def _ca_path(temp_dir=None): """ Returns the file path to the CA certs file :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :return: A 2-element tuple: - 0: A unicode string of the file path - 1: A bool if the file is a temporary file """ ca_path = system_path() # Windows and OS X if ca_path is None: if temp_dir is None: temp_dir = tempfile.gettempdir() if not os.path.isdir(temp_dir): raise CACertsError(pretty_message( ''' The temp dir specified, "%s", is not a directory ''', temp_dir )) ca_path = os.path.join(temp_dir, 'oscrypto-ca-bundle.crt') return (ca_path, True) return (ca_path, False)
def _ca_path(temp_dir=None): """ Returns the file path to the CA certs file :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :return: A 2-element tuple: - 0: A unicode string of the file path - 1: A bool if the file is a temporary file """ ca_path = system_path() # Windows and OS X if ca_path is None: if temp_dir is None: temp_dir = tempfile.gettempdir() if not os.path.isdir(temp_dir): raise CACertsError(pretty_message( ''' The temp dir specified, "%s", is not a directory ''', temp_dir )) ca_path = os.path.join(temp_dir, 'oscrypto-ca-bundle.crt') return (ca_path, True) return (ca_path, False)
[ "Returns", "the", "file", "path", "to", "the", "CA", "certs", "file" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L235-L268
[ "def", "_ca_path", "(", "temp_dir", "=", "None", ")", ":", "ca_path", "=", "system_path", "(", ")", "# Windows and OS X", "if", "ca_path", "is", "None", ":", "if", "temp_dir", "is", "None", ":", "temp_dir", "=", "tempfile", ".", "gettempdir", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "temp_dir", ")", ":", "raise", "CACertsError", "(", "pretty_message", "(", "'''\n The temp dir specified, \"%s\", is not a directory\n '''", ",", "temp_dir", ")", ")", "ca_path", "=", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "'oscrypto-ca-bundle.crt'", ")", "return", "(", "ca_path", ",", "True", ")", "return", "(", "ca_path", ",", "False", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_map_oids
Takes a set of unicode string OIDs and converts vendor-specific OIDs into generics OIDs from RFCs. - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param oids: A set of unicode strings :return: The original set of OIDs with any mapped OIDs added
oscrypto/trust_list.py
def _map_oids(oids): """ Takes a set of unicode string OIDs and converts vendor-specific OIDs into generics OIDs from RFCs. - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param oids: A set of unicode strings :return: The original set of OIDs with any mapped OIDs added """ new_oids = set() for oid in oids: if oid in _oid_map: new_oids |= _oid_map[oid] return oids | new_oids
def _map_oids(oids): """ Takes a set of unicode string OIDs and converts vendor-specific OIDs into generics OIDs from RFCs. - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param oids: A set of unicode strings :return: The original set of OIDs with any mapped OIDs added """ new_oids = set() for oid in oids: if oid in _oid_map: new_oids |= _oid_map[oid] return oids | new_oids
[ "Takes", "a", "set", "of", "unicode", "string", "OIDs", "and", "converts", "vendor", "-", "specific", "OIDs", "into", "generics", "OIDs", "from", "RFCs", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L271-L300
[ "def", "_map_oids", "(", "oids", ")", ":", "new_oids", "=", "set", "(", ")", "for", "oid", "in", "oids", ":", "if", "oid", "in", "_oid_map", ":", "new_oids", "|=", "_oid_map", "[", "oid", "]", "return", "oids", "|", "new_oids" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_cached_path_needs_update
Checks to see if a cache file needs to be refreshed :param ca_path: A unicode string of the path to the cache file :param cache_length: An integer representing the number of hours the cache is valid for :return: A boolean - True if the cache needs to be updated, False if the file is up-to-date
oscrypto/trust_list.py
def _cached_path_needs_update(ca_path, cache_length): """ Checks to see if a cache file needs to be refreshed :param ca_path: A unicode string of the path to the cache file :param cache_length: An integer representing the number of hours the cache is valid for :return: A boolean - True if the cache needs to be updated, False if the file is up-to-date """ exists = os.path.exists(ca_path) if not exists: return True stats = os.stat(ca_path) if stats.st_mtime < time.time() - cache_length * 60 * 60: return True if stats.st_size == 0: return True return False
def _cached_path_needs_update(ca_path, cache_length): """ Checks to see if a cache file needs to be refreshed :param ca_path: A unicode string of the path to the cache file :param cache_length: An integer representing the number of hours the cache is valid for :return: A boolean - True if the cache needs to be updated, False if the file is up-to-date """ exists = os.path.exists(ca_path) if not exists: return True stats = os.stat(ca_path) if stats.st_mtime < time.time() - cache_length * 60 * 60: return True if stats.st_size == 0: return True return False
[ "Checks", "to", "see", "if", "a", "cache", "file", "needs", "to", "be", "refreshed" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L303-L330
[ "def", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "exists", "=", "os", ".", "path", ".", "exists", "(", "ca_path", ")", "if", "not", "exists", ":", "return", "True", "stats", "=", "os", ".", "stat", "(", "ca_path", ")", "if", "stats", ".", "st_mtime", "<", "time", ".", "time", "(", ")", "-", "cache_length", "*", "60", "*", "60", ":", "return", "True", "if", "stats", ".", "st_size", "==", "0", ":", "return", "True", "return", "False" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rand_bytes
Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by OpenSSL :return: A byte string
oscrypto/_rand.py
def rand_bytes(length): """ Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by OpenSSL :return: A byte string """ if not isinstance(length, int_types): raise TypeError(pretty_message( ''' length must be an integer, not %s ''', type_name(length) )) if length < 1: raise ValueError('length must be greater than 0') if length > 1024: raise ValueError('length must not be greater than 1024') return os.urandom(length)
def rand_bytes(length): """ Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by OpenSSL :return: A byte string """ if not isinstance(length, int_types): raise TypeError(pretty_message( ''' length must be an integer, not %s ''', type_name(length) )) if length < 1: raise ValueError('length must be greater than 0') if length > 1024: raise ValueError('length must not be greater than 1024') return os.urandom(length)
[ "Returns", "a", "number", "of", "random", "bytes", "suitable", "for", "cryptographic", "purposes" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_rand.py#L15-L45
[ "def", "rand_bytes", "(", "length", ")", ":", "if", "not", "isinstance", "(", "length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n length must be an integer, not %s\n '''", ",", "type_name", "(", "length", ")", ")", ")", "if", "length", "<", "1", ":", "raise", "ValueError", "(", "'length must be greater than 0'", ")", "if", "length", ">", "1024", ":", "raise", "ValueError", "(", "'length must not be greater than 1024'", ")", "return", "os", ".", "urandom", "(", "length", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
pbkdf2
Implements PBKDF2 from PKCS#5 v2.2 in pure Python :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :return: The derived key as a byte string
oscrypto/_pkcs5.py
def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ Implements PBKDF2 from PKCS#5 v2.2 in pure Python :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md5", "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) algo = getattr(hashlib, hash_algorithm) hash_length = { 'md5': 16, 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] blocks = int(math.ceil(key_length / hash_length)) original_hmac = hmac.new(password, None, algo) int_pack = struct.Struct(b'>I').pack output = b'' for block in range(1, blocks + 1): prf = original_hmac.copy() prf.update(salt + int_pack(block)) last = prf.digest() u = int_from_bytes(last) for _ in range(2, iterations + 1): prf = original_hmac.copy() prf.update(last) last = prf.digest() u ^= int_from_bytes(last) t = int_to_bytes(u) output += t return output[0:key_length]
def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ Implements PBKDF2 from PKCS#5 v2.2 in pure Python :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md5", "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) algo = getattr(hashlib, hash_algorithm) hash_length = { 'md5': 16, 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] blocks = int(math.ceil(key_length / hash_length)) original_hmac = hmac.new(password, None, algo) int_pack = struct.Struct(b'>I').pack output = b'' for block in range(1, blocks + 1): prf = original_hmac.copy() prf.update(salt + int_pack(block)) last = prf.digest() u = int_from_bytes(last) for _ in range(2, iterations + 1): prf = original_hmac.copy() prf.update(last) last = prf.digest() u ^= int_from_bytes(last) t = int_to_bytes(u) output += t return output[0:key_length]
[ "Implements", "PBKDF2", "from", "PKCS#5", "v2", ".", "2", "in", "pure", "Python" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_pkcs5.py#L28-L140
[ "def", "pbkdf2", "(", "hash_algorithm", ",", "password", ",", "salt", ",", "iterations", ",", "key_length", ")", ":", "if", "not", "isinstance", "(", "password", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n password must be a byte string, not %s\n '''", ",", "type_name", "(", "password", ")", ")", ")", "if", "not", "isinstance", "(", "salt", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n salt must be a byte string, not %s\n '''", ",", "type_name", "(", "salt", ")", ")", ")", "if", "not", "isinstance", "(", "iterations", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n iterations must be an integer, not %s\n '''", ",", "type_name", "(", "iterations", ")", ")", ")", "if", "iterations", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iterations must be greater than 0 - is %s\n '''", ",", "repr", "(", "iterations", ")", ")", ")", "if", "not", "isinstance", "(", "key_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n key_length must be an integer, not %s\n '''", ",", "type_name", "(", "key_length", ")", ")", ")", "if", "key_length", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key_length must be greater than 0 - is %s\n '''", ",", "repr", "(", "key_length", ")", ")", ")", "if", "hash_algorithm", "not", "in", "set", "(", "[", "'md5'", ",", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of \"md5\", \"sha1\", \"sha224\", \"sha256\",\n \"sha384\", \"sha512\", not %s\n '''", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "algo", "=", "getattr", "(", "hashlib", ",", "hash_algorithm", ")", "hash_length", "=", "{", "'md5'", ":", "16", ",", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", "[", "hash_algorithm", "]", "blocks", "=", "int", "(", "math", ".", "ceil", "(", "key_length", "/", "hash_length", ")", ")", "original_hmac", "=", "hmac", ".", "new", "(", "password", ",", "None", ",", "algo", ")", "int_pack", "=", "struct", ".", "Struct", "(", "b'>I'", ")", ".", "pack", "output", "=", "b''", "for", "block", "in", "range", "(", "1", ",", "blocks", "+", "1", ")", ":", "prf", "=", "original_hmac", ".", "copy", "(", ")", "prf", ".", "update", "(", "salt", "+", "int_pack", "(", "block", ")", ")", "last", "=", "prf", ".", "digest", "(", ")", "u", "=", "int_from_bytes", "(", "last", ")", "for", "_", "in", "range", "(", "2", ",", "iterations", "+", "1", ")", ":", "prf", "=", "original_hmac", ".", "copy", "(", ")", "prf", ".", "update", "(", "last", ")", "last", "=", "prf", ".", "digest", "(", ")", "u", "^=", "int_from_bytes", "(", "last", ")", "t", "=", "int_to_bytes", "(", "u", ")", "output", "+=", "t", "return", "output", "[", "0", ":", "key_length", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
generate_pair
Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump().
oscrypto/_osx/asymmetric.py
def generate_pair(algorithm, bit_size=None, curve=None): """ Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). """ if algorithm not in set(['rsa', 'dsa', 'ec']): raise ValueError(pretty_message( ''' algorithm must be one of "rsa", "dsa", "ec", not %s ''', repr(algorithm) )) if algorithm == 'rsa': if bit_size not in set([1024, 2048, 3072, 4096]): raise ValueError(pretty_message( ''' bit_size must be one of 1024, 2048, 3072, 4096, not %s ''', repr(bit_size) )) elif algorithm == 'dsa': if bit_size not in set([1024]): raise ValueError(pretty_message( ''' bit_size must be 1024, not %s ''', repr(bit_size) )) elif algorithm == 'ec': if curve not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s ''', repr(curve) )) cf_dict = None public_key_ref = None private_key_ref = None cf_data_public = None cf_data_private = None cf_string = None sec_access_ref = None try: key_type = { 'dsa': Security.kSecAttrKeyTypeDSA, 'ec': Security.kSecAttrKeyTypeECDSA, 'rsa': Security.kSecAttrKeyTypeRSA, }[algorithm] if algorithm == 'ec': key_size = { 'secp256r1': 256, 'secp384r1': 384, 'secp521r1': 521, }[curve] else: key_size = bit_size private_key_pointer = new(Security, 'SecKeyRef *') public_key_pointer = new(Security, 'SecKeyRef *') cf_string = CFHelpers.cf_string_from_unicode("Temporary key from oscrypto python library - safe to delete") # For some reason Apple decided that DSA keys were not a valid type of # key to be generated via SecKeyGeneratePair(), thus we have to use the # lower level, deprecated SecKeyCreatePair() if algorithm == 'dsa': sec_access_ref_pointer = new(Security, 'SecAccessRef *') result = Security.SecAccessCreate(cf_string, null(), sec_access_ref_pointer) sec_access_ref = unwrap(sec_access_ref_pointer) result = Security.SecKeyCreatePair( null(), SecurityConst.CSSM_ALGID_DSA, key_size, 0, SecurityConst.CSSM_KEYUSE_VERIFY, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, SecurityConst.CSSM_KEYUSE_SIGN, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, sec_access_ref, public_key_pointer, private_key_pointer ) handle_sec_error(result) else: cf_dict = CFHelpers.cf_dictionary_from_pairs([ (Security.kSecAttrKeyType, key_type), (Security.kSecAttrKeySizeInBits, CFHelpers.cf_number_from_integer(key_size)), (Security.kSecAttrLabel, cf_string) ]) result = Security.SecKeyGeneratePair(cf_dict, public_key_pointer, private_key_pointer) handle_sec_error(result) public_key_ref = unwrap(public_key_pointer) private_key_ref = unwrap(private_key_pointer) cf_data_public_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(public_key_ref, 0, 0, null(), cf_data_public_pointer) handle_sec_error(result) cf_data_public = unwrap(cf_data_public_pointer) public_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_public) cf_data_private_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(private_key_ref, 0, 0, null(), cf_data_private_pointer) handle_sec_error(result) cf_data_private = unwrap(cf_data_private_pointer) private_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_private) # Clean the new keys out of the keychain result = Security.SecKeychainItemDelete(public_key_ref) handle_sec_error(result) result = Security.SecKeychainItemDelete(private_key_ref) handle_sec_error(result) finally: if cf_dict: CoreFoundation.CFRelease(cf_dict) if public_key_ref: CoreFoundation.CFRelease(public_key_ref) if private_key_ref: CoreFoundation.CFRelease(private_key_ref) if cf_data_public: CoreFoundation.CFRelease(cf_data_public) if cf_data_private: CoreFoundation.CFRelease(cf_data_private) if cf_string: CoreFoundation.CFRelease(cf_string) if sec_access_ref: CoreFoundation.CFRelease(sec_access_ref) return (load_public_key(public_key_bytes), load_private_key(private_key_bytes))
def generate_pair(algorithm, bit_size=None, curve=None): """ Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). """ if algorithm not in set(['rsa', 'dsa', 'ec']): raise ValueError(pretty_message( ''' algorithm must be one of "rsa", "dsa", "ec", not %s ''', repr(algorithm) )) if algorithm == 'rsa': if bit_size not in set([1024, 2048, 3072, 4096]): raise ValueError(pretty_message( ''' bit_size must be one of 1024, 2048, 3072, 4096, not %s ''', repr(bit_size) )) elif algorithm == 'dsa': if bit_size not in set([1024]): raise ValueError(pretty_message( ''' bit_size must be 1024, not %s ''', repr(bit_size) )) elif algorithm == 'ec': if curve not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s ''', repr(curve) )) cf_dict = None public_key_ref = None private_key_ref = None cf_data_public = None cf_data_private = None cf_string = None sec_access_ref = None try: key_type = { 'dsa': Security.kSecAttrKeyTypeDSA, 'ec': Security.kSecAttrKeyTypeECDSA, 'rsa': Security.kSecAttrKeyTypeRSA, }[algorithm] if algorithm == 'ec': key_size = { 'secp256r1': 256, 'secp384r1': 384, 'secp521r1': 521, }[curve] else: key_size = bit_size private_key_pointer = new(Security, 'SecKeyRef *') public_key_pointer = new(Security, 'SecKeyRef *') cf_string = CFHelpers.cf_string_from_unicode("Temporary key from oscrypto python library - safe to delete") # For some reason Apple decided that DSA keys were not a valid type of # key to be generated via SecKeyGeneratePair(), thus we have to use the # lower level, deprecated SecKeyCreatePair() if algorithm == 'dsa': sec_access_ref_pointer = new(Security, 'SecAccessRef *') result = Security.SecAccessCreate(cf_string, null(), sec_access_ref_pointer) sec_access_ref = unwrap(sec_access_ref_pointer) result = Security.SecKeyCreatePair( null(), SecurityConst.CSSM_ALGID_DSA, key_size, 0, SecurityConst.CSSM_KEYUSE_VERIFY, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, SecurityConst.CSSM_KEYUSE_SIGN, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, sec_access_ref, public_key_pointer, private_key_pointer ) handle_sec_error(result) else: cf_dict = CFHelpers.cf_dictionary_from_pairs([ (Security.kSecAttrKeyType, key_type), (Security.kSecAttrKeySizeInBits, CFHelpers.cf_number_from_integer(key_size)), (Security.kSecAttrLabel, cf_string) ]) result = Security.SecKeyGeneratePair(cf_dict, public_key_pointer, private_key_pointer) handle_sec_error(result) public_key_ref = unwrap(public_key_pointer) private_key_ref = unwrap(private_key_pointer) cf_data_public_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(public_key_ref, 0, 0, null(), cf_data_public_pointer) handle_sec_error(result) cf_data_public = unwrap(cf_data_public_pointer) public_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_public) cf_data_private_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(private_key_ref, 0, 0, null(), cf_data_private_pointer) handle_sec_error(result) cf_data_private = unwrap(cf_data_private_pointer) private_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_private) # Clean the new keys out of the keychain result = Security.SecKeychainItemDelete(public_key_ref) handle_sec_error(result) result = Security.SecKeychainItemDelete(private_key_ref) handle_sec_error(result) finally: if cf_dict: CoreFoundation.CFRelease(cf_dict) if public_key_ref: CoreFoundation.CFRelease(public_key_ref) if private_key_ref: CoreFoundation.CFRelease(private_key_ref) if cf_data_public: CoreFoundation.CFRelease(cf_data_public) if cf_data_private: CoreFoundation.CFRelease(cf_data_private) if cf_string: CoreFoundation.CFRelease(cf_string) if sec_access_ref: CoreFoundation.CFRelease(sec_access_ref) return (load_public_key(public_key_bytes), load_private_key(private_key_bytes))
[ "Generates", "a", "public", "/", "private", "key", "pair" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L263-L420
[ "def", "generate_pair", "(", "algorithm", ",", "bit_size", "=", "None", ",", "curve", "=", "None", ")", ":", "if", "algorithm", "not", "in", "set", "(", "[", "'rsa'", ",", "'dsa'", ",", "'ec'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n algorithm must be one of \"rsa\", \"dsa\", \"ec\", not %s\n '''", ",", "repr", "(", "algorithm", ")", ")", ")", "if", "algorithm", "==", "'rsa'", ":", "if", "bit_size", "not", "in", "set", "(", "[", "1024", ",", "2048", ",", "3072", ",", "4096", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n bit_size must be one of 1024, 2048, 3072, 4096, not %s\n '''", ",", "repr", "(", "bit_size", ")", ")", ")", "elif", "algorithm", "==", "'dsa'", ":", "if", "bit_size", "not", "in", "set", "(", "[", "1024", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n bit_size must be 1024, not %s\n '''", ",", "repr", "(", "bit_size", ")", ")", ")", "elif", "algorithm", "==", "'ec'", ":", "if", "curve", "not", "in", "set", "(", "[", "'secp256r1'", ",", "'secp384r1'", ",", "'secp521r1'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n curve must be one of \"secp256r1\", \"secp384r1\", \"secp521r1\", not %s\n '''", ",", "repr", "(", "curve", ")", ")", ")", "cf_dict", "=", "None", "public_key_ref", "=", "None", "private_key_ref", "=", "None", "cf_data_public", "=", "None", "cf_data_private", "=", "None", "cf_string", "=", "None", "sec_access_ref", "=", "None", "try", ":", "key_type", "=", "{", "'dsa'", ":", "Security", ".", "kSecAttrKeyTypeDSA", ",", "'ec'", ":", "Security", ".", "kSecAttrKeyTypeECDSA", ",", "'rsa'", ":", "Security", ".", "kSecAttrKeyTypeRSA", ",", "}", "[", "algorithm", "]", "if", "algorithm", "==", "'ec'", ":", "key_size", "=", "{", "'secp256r1'", ":", "256", ",", "'secp384r1'", ":", "384", ",", "'secp521r1'", ":", "521", ",", "}", "[", "curve", "]", "else", ":", "key_size", "=", "bit_size", "private_key_pointer", "=", "new", "(", "Security", ",", "'SecKeyRef *'", ")", "public_key_pointer", "=", "new", "(", "Security", ",", "'SecKeyRef *'", ")", "cf_string", "=", "CFHelpers", ".", "cf_string_from_unicode", "(", "\"Temporary key from oscrypto python library - safe to delete\"", ")", "# For some reason Apple decided that DSA keys were not a valid type of", "# key to be generated via SecKeyGeneratePair(), thus we have to use the", "# lower level, deprecated SecKeyCreatePair()", "if", "algorithm", "==", "'dsa'", ":", "sec_access_ref_pointer", "=", "new", "(", "Security", ",", "'SecAccessRef *'", ")", "result", "=", "Security", ".", "SecAccessCreate", "(", "cf_string", ",", "null", "(", ")", ",", "sec_access_ref_pointer", ")", "sec_access_ref", "=", "unwrap", "(", "sec_access_ref_pointer", ")", "result", "=", "Security", ".", "SecKeyCreatePair", "(", "null", "(", ")", ",", "SecurityConst", ".", "CSSM_ALGID_DSA", ",", "key_size", ",", "0", ",", "SecurityConst", ".", "CSSM_KEYUSE_VERIFY", ",", "SecurityConst", ".", "CSSM_KEYATTR_EXTRACTABLE", "|", "SecurityConst", ".", "CSSM_KEYATTR_PERMANENT", ",", "SecurityConst", ".", "CSSM_KEYUSE_SIGN", ",", "SecurityConst", ".", "CSSM_KEYATTR_EXTRACTABLE", "|", "SecurityConst", ".", "CSSM_KEYATTR_PERMANENT", ",", "sec_access_ref", ",", "public_key_pointer", ",", "private_key_pointer", ")", "handle_sec_error", "(", "result", ")", "else", ":", "cf_dict", "=", "CFHelpers", ".", "cf_dictionary_from_pairs", "(", "[", "(", "Security", ".", "kSecAttrKeyType", ",", "key_type", ")", ",", "(", "Security", ".", "kSecAttrKeySizeInBits", ",", "CFHelpers", ".", "cf_number_from_integer", "(", "key_size", ")", ")", ",", "(", "Security", ".", "kSecAttrLabel", ",", "cf_string", ")", "]", ")", "result", "=", "Security", ".", "SecKeyGeneratePair", "(", "cf_dict", ",", "public_key_pointer", ",", "private_key_pointer", ")", "handle_sec_error", "(", "result", ")", "public_key_ref", "=", "unwrap", "(", "public_key_pointer", ")", "private_key_ref", "=", "unwrap", "(", "private_key_pointer", ")", "cf_data_public_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFDataRef *'", ")", "result", "=", "Security", ".", "SecItemExport", "(", "public_key_ref", ",", "0", ",", "0", ",", "null", "(", ")", ",", "cf_data_public_pointer", ")", "handle_sec_error", "(", "result", ")", "cf_data_public", "=", "unwrap", "(", "cf_data_public_pointer", ")", "public_key_bytes", "=", "CFHelpers", ".", "cf_data_to_bytes", "(", "cf_data_public", ")", "cf_data_private_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFDataRef *'", ")", "result", "=", "Security", ".", "SecItemExport", "(", "private_key_ref", ",", "0", ",", "0", ",", "null", "(", ")", ",", "cf_data_private_pointer", ")", "handle_sec_error", "(", "result", ")", "cf_data_private", "=", "unwrap", "(", "cf_data_private_pointer", ")", "private_key_bytes", "=", "CFHelpers", ".", "cf_data_to_bytes", "(", "cf_data_private", ")", "# Clean the new keys out of the keychain", "result", "=", "Security", ".", "SecKeychainItemDelete", "(", "public_key_ref", ")", "handle_sec_error", "(", "result", ")", "result", "=", "Security", ".", "SecKeychainItemDelete", "(", "private_key_ref", ")", "handle_sec_error", "(", "result", ")", "finally", ":", "if", "cf_dict", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_dict", ")", "if", "public_key_ref", ":", "CoreFoundation", ".", "CFRelease", "(", "public_key_ref", ")", "if", "private_key_ref", ":", "CoreFoundation", ".", "CFRelease", "(", "private_key_ref", ")", "if", "cf_data_public", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data_public", ")", "if", "cf_data_private", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data_private", ")", "if", "cf_string", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_string", ")", "if", "sec_access_ref", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_access_ref", ")", "return", "(", "load_public_key", "(", "public_key_bytes", ")", ",", "load_private_key", "(", "private_key_bytes", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
generate_dh_parameters
Generates DH parameters for use with Diffie-Hellman key exchange. Returns a structure in the format of DHParameter defined in PKCS#3, which is also used by the OpenSSL dhparam tool. THIS CAN BE VERY TIME CONSUMING! :param bit_size: The integer bit size of the parameters to generate. Must be between 512 and 4096, and divisible by 64. Recommended secure value as of early 2016 is 2048, with an absolute minimum of 1024. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: An asn1crypto.algos.DHParameters object. Use oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with web servers.
oscrypto/_osx/asymmetric.py
def generate_dh_parameters(bit_size): """ Generates DH parameters for use with Diffie-Hellman key exchange. Returns a structure in the format of DHParameter defined in PKCS#3, which is also used by the OpenSSL dhparam tool. THIS CAN BE VERY TIME CONSUMING! :param bit_size: The integer bit size of the parameters to generate. Must be between 512 and 4096, and divisible by 64. Recommended secure value as of early 2016 is 2048, with an absolute minimum of 1024. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: An asn1crypto.algos.DHParameters object. Use oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with web servers. """ if not isinstance(bit_size, int_types): raise TypeError(pretty_message( ''' bit_size must be an integer, not %s ''', type_name(bit_size) )) if bit_size < 512: raise ValueError('bit_size must be greater than or equal to 512') if bit_size > 4096: raise ValueError('bit_size must be less than or equal to 4096') if bit_size % 64 != 0: raise ValueError('bit_size must be a multiple of 64') public_key_ref = None private_key_ref = None cf_data_public = None cf_data_private = None cf_string = None sec_access_ref = None try: public_key_pointer = new(Security, 'SecKeyRef *') private_key_pointer = new(Security, 'SecKeyRef *') cf_string = CFHelpers.cf_string_from_unicode("Temporary key from oscrypto python library - safe to delete") sec_access_ref_pointer = new(Security, 'SecAccessRef *') result = Security.SecAccessCreate(cf_string, null(), sec_access_ref_pointer) sec_access_ref = unwrap(sec_access_ref_pointer) result = Security.SecKeyCreatePair( null(), SecurityConst.CSSM_ALGID_DH, bit_size, 0, 0, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, 0, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, sec_access_ref, public_key_pointer, private_key_pointer ) handle_sec_error(result) public_key_ref = unwrap(public_key_pointer) private_key_ref = unwrap(private_key_pointer) cf_data_private_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(private_key_ref, 0, 0, null(), cf_data_private_pointer) handle_sec_error(result) cf_data_private = unwrap(cf_data_private_pointer) private_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_private) # Clean the new keys out of the keychain result = Security.SecKeychainItemDelete(public_key_ref) handle_sec_error(result) result = Security.SecKeychainItemDelete(private_key_ref) handle_sec_error(result) return algos.KeyExchangeAlgorithm.load(private_key_bytes)['parameters'] finally: if public_key_ref: CoreFoundation.CFRelease(public_key_ref) if private_key_ref: CoreFoundation.CFRelease(private_key_ref) if cf_data_public: CoreFoundation.CFRelease(cf_data_public) if cf_data_private: CoreFoundation.CFRelease(cf_data_private) if cf_string: CoreFoundation.CFRelease(cf_string) if sec_access_ref: CoreFoundation.CFRelease(sec_access_ref)
def generate_dh_parameters(bit_size): """ Generates DH parameters for use with Diffie-Hellman key exchange. Returns a structure in the format of DHParameter defined in PKCS#3, which is also used by the OpenSSL dhparam tool. THIS CAN BE VERY TIME CONSUMING! :param bit_size: The integer bit size of the parameters to generate. Must be between 512 and 4096, and divisible by 64. Recommended secure value as of early 2016 is 2048, with an absolute minimum of 1024. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: An asn1crypto.algos.DHParameters object. Use oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with web servers. """ if not isinstance(bit_size, int_types): raise TypeError(pretty_message( ''' bit_size must be an integer, not %s ''', type_name(bit_size) )) if bit_size < 512: raise ValueError('bit_size must be greater than or equal to 512') if bit_size > 4096: raise ValueError('bit_size must be less than or equal to 4096') if bit_size % 64 != 0: raise ValueError('bit_size must be a multiple of 64') public_key_ref = None private_key_ref = None cf_data_public = None cf_data_private = None cf_string = None sec_access_ref = None try: public_key_pointer = new(Security, 'SecKeyRef *') private_key_pointer = new(Security, 'SecKeyRef *') cf_string = CFHelpers.cf_string_from_unicode("Temporary key from oscrypto python library - safe to delete") sec_access_ref_pointer = new(Security, 'SecAccessRef *') result = Security.SecAccessCreate(cf_string, null(), sec_access_ref_pointer) sec_access_ref = unwrap(sec_access_ref_pointer) result = Security.SecKeyCreatePair( null(), SecurityConst.CSSM_ALGID_DH, bit_size, 0, 0, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, 0, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, sec_access_ref, public_key_pointer, private_key_pointer ) handle_sec_error(result) public_key_ref = unwrap(public_key_pointer) private_key_ref = unwrap(private_key_pointer) cf_data_private_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(private_key_ref, 0, 0, null(), cf_data_private_pointer) handle_sec_error(result) cf_data_private = unwrap(cf_data_private_pointer) private_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_private) # Clean the new keys out of the keychain result = Security.SecKeychainItemDelete(public_key_ref) handle_sec_error(result) result = Security.SecKeychainItemDelete(private_key_ref) handle_sec_error(result) return algos.KeyExchangeAlgorithm.load(private_key_bytes)['parameters'] finally: if public_key_ref: CoreFoundation.CFRelease(public_key_ref) if private_key_ref: CoreFoundation.CFRelease(private_key_ref) if cf_data_public: CoreFoundation.CFRelease(cf_data_public) if cf_data_private: CoreFoundation.CFRelease(cf_data_private) if cf_string: CoreFoundation.CFRelease(cf_string) if sec_access_ref: CoreFoundation.CFRelease(sec_access_ref)
[ "Generates", "DH", "parameters", "for", "use", "with", "Diffie", "-", "Hellman", "key", "exchange", ".", "Returns", "a", "structure", "in", "the", "format", "of", "DHParameter", "defined", "in", "PKCS#3", "which", "is", "also", "used", "by", "the", "OpenSSL", "dhparam", "tool", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L426-L529
[ "def", "generate_dh_parameters", "(", "bit_size", ")", ":", "if", "not", "isinstance", "(", "bit_size", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n bit_size must be an integer, not %s\n '''", ",", "type_name", "(", "bit_size", ")", ")", ")", "if", "bit_size", "<", "512", ":", "raise", "ValueError", "(", "'bit_size must be greater than or equal to 512'", ")", "if", "bit_size", ">", "4096", ":", "raise", "ValueError", "(", "'bit_size must be less than or equal to 4096'", ")", "if", "bit_size", "%", "64", "!=", "0", ":", "raise", "ValueError", "(", "'bit_size must be a multiple of 64'", ")", "public_key_ref", "=", "None", "private_key_ref", "=", "None", "cf_data_public", "=", "None", "cf_data_private", "=", "None", "cf_string", "=", "None", "sec_access_ref", "=", "None", "try", ":", "public_key_pointer", "=", "new", "(", "Security", ",", "'SecKeyRef *'", ")", "private_key_pointer", "=", "new", "(", "Security", ",", "'SecKeyRef *'", ")", "cf_string", "=", "CFHelpers", ".", "cf_string_from_unicode", "(", "\"Temporary key from oscrypto python library - safe to delete\"", ")", "sec_access_ref_pointer", "=", "new", "(", "Security", ",", "'SecAccessRef *'", ")", "result", "=", "Security", ".", "SecAccessCreate", "(", "cf_string", ",", "null", "(", ")", ",", "sec_access_ref_pointer", ")", "sec_access_ref", "=", "unwrap", "(", "sec_access_ref_pointer", ")", "result", "=", "Security", ".", "SecKeyCreatePair", "(", "null", "(", ")", ",", "SecurityConst", ".", "CSSM_ALGID_DH", ",", "bit_size", ",", "0", ",", "0", ",", "SecurityConst", ".", "CSSM_KEYATTR_EXTRACTABLE", "|", "SecurityConst", ".", "CSSM_KEYATTR_PERMANENT", ",", "0", ",", "SecurityConst", ".", "CSSM_KEYATTR_EXTRACTABLE", "|", "SecurityConst", ".", "CSSM_KEYATTR_PERMANENT", ",", "sec_access_ref", ",", "public_key_pointer", ",", "private_key_pointer", ")", "handle_sec_error", "(", "result", ")", "public_key_ref", "=", "unwrap", "(", "public_key_pointer", ")", "private_key_ref", "=", "unwrap", "(", "private_key_pointer", ")", "cf_data_private_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFDataRef *'", ")", "result", "=", "Security", ".", "SecItemExport", "(", "private_key_ref", ",", "0", ",", "0", ",", "null", "(", ")", ",", "cf_data_private_pointer", ")", "handle_sec_error", "(", "result", ")", "cf_data_private", "=", "unwrap", "(", "cf_data_private_pointer", ")", "private_key_bytes", "=", "CFHelpers", ".", "cf_data_to_bytes", "(", "cf_data_private", ")", "# Clean the new keys out of the keychain", "result", "=", "Security", ".", "SecKeychainItemDelete", "(", "public_key_ref", ")", "handle_sec_error", "(", "result", ")", "result", "=", "Security", ".", "SecKeychainItemDelete", "(", "private_key_ref", ")", "handle_sec_error", "(", "result", ")", "return", "algos", ".", "KeyExchangeAlgorithm", ".", "load", "(", "private_key_bytes", ")", "[", "'parameters'", "]", "finally", ":", "if", "public_key_ref", ":", "CoreFoundation", ".", "CFRelease", "(", "public_key_ref", ")", "if", "private_key_ref", ":", "CoreFoundation", ".", "CFRelease", "(", "private_key_ref", ")", "if", "cf_data_public", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data_public", ")", "if", "cf_data_private", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data_private", ")", "if", "cf_string", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_string", ")", "if", "sec_access_ref", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_access_ref", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_load_x509
Loads an ASN.1 object of an x509 certificate into a Certificate object :param certificate: An asn1crypto.x509.Certificate object :return: A Certificate object
oscrypto/_osx/asymmetric.py
def _load_x509(certificate): """ Loads an ASN.1 object of an x509 certificate into a Certificate object :param certificate: An asn1crypto.x509.Certificate object :return: A Certificate object """ source = certificate.dump() cf_source = None try: cf_source = CFHelpers.cf_data_from_bytes(source) sec_key_ref = Security.SecCertificateCreateWithData(CoreFoundation.kCFAllocatorDefault, cf_source) return Certificate(sec_key_ref, certificate) finally: if cf_source: CoreFoundation.CFRelease(cf_source)
def _load_x509(certificate): """ Loads an ASN.1 object of an x509 certificate into a Certificate object :param certificate: An asn1crypto.x509.Certificate object :return: A Certificate object """ source = certificate.dump() cf_source = None try: cf_source = CFHelpers.cf_data_from_bytes(source) sec_key_ref = Security.SecCertificateCreateWithData(CoreFoundation.kCFAllocatorDefault, cf_source) return Certificate(sec_key_ref, certificate) finally: if cf_source: CoreFoundation.CFRelease(cf_source)
[ "Loads", "an", "ASN", ".", "1", "object", "of", "an", "x509", "certificate", "into", "a", "Certificate", "object" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L574-L595
[ "def", "_load_x509", "(", "certificate", ")", ":", "source", "=", "certificate", ".", "dump", "(", ")", "cf_source", "=", "None", "try", ":", "cf_source", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "source", ")", "sec_key_ref", "=", "Security", ".", "SecCertificateCreateWithData", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "cf_source", ")", "return", "Certificate", "(", "sec_key_ref", ",", "certificate", ")", "finally", ":", "if", "cf_source", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_source", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_load_key
Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PublicKey or PrivateKey object
oscrypto/_osx/asymmetric.py
def _load_key(key_object): """ Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PublicKey or PrivateKey object """ if key_object.algorithm == 'ec': curve_type, details = key_object.curve if curve_type != 'named': raise AsymmetricKeyError('OS X only supports EC keys using named curves') if details not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise AsymmetricKeyError(pretty_message( ''' OS X only supports EC keys using the named curves secp256r1, secp384r1 and secp521r1 ''' )) elif key_object.algorithm == 'dsa' and key_object.hash_algo == 'sha2': raise AsymmetricKeyError(pretty_message( ''' OS X only supports DSA keys based on SHA1 (2048 bits or less) - this key is based on SHA2 and is %s bits ''', key_object.bit_size )) elif key_object.algorithm == 'dsa' and key_object.hash_algo is None: raise IncompleteAsymmetricKeyError(pretty_message( ''' The DSA key does not contain the necessary p, q and g parameters and can not be used ''' )) if isinstance(key_object, keys.PublicKeyInfo): source = key_object.dump() key_class = Security.kSecAttrKeyClassPublic else: source = key_object.unwrap().dump() key_class = Security.kSecAttrKeyClassPrivate cf_source = None cf_dict = None cf_output = None try: cf_source = CFHelpers.cf_data_from_bytes(source) key_type = { 'dsa': Security.kSecAttrKeyTypeDSA, 'ec': Security.kSecAttrKeyTypeECDSA, 'rsa': Security.kSecAttrKeyTypeRSA, }[key_object.algorithm] cf_dict = CFHelpers.cf_dictionary_from_pairs([ (Security.kSecAttrKeyType, key_type), (Security.kSecAttrKeyClass, key_class), (Security.kSecAttrCanSign, CoreFoundation.kCFBooleanTrue), (Security.kSecAttrCanVerify, CoreFoundation.kCFBooleanTrue), ]) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_key_ref = Security.SecKeyCreateFromData(cf_dict, cf_source, error_pointer) handle_cf_error(error_pointer) if key_class == Security.kSecAttrKeyClassPublic: return PublicKey(sec_key_ref, key_object) if key_class == Security.kSecAttrKeyClassPrivate: return PrivateKey(sec_key_ref, key_object) finally: if cf_source: CoreFoundation.CFRelease(cf_source) if cf_dict: CoreFoundation.CFRelease(cf_dict) if cf_output: CoreFoundation.CFRelease(cf_output)
def _load_key(key_object): """ Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PublicKey or PrivateKey object """ if key_object.algorithm == 'ec': curve_type, details = key_object.curve if curve_type != 'named': raise AsymmetricKeyError('OS X only supports EC keys using named curves') if details not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise AsymmetricKeyError(pretty_message( ''' OS X only supports EC keys using the named curves secp256r1, secp384r1 and secp521r1 ''' )) elif key_object.algorithm == 'dsa' and key_object.hash_algo == 'sha2': raise AsymmetricKeyError(pretty_message( ''' OS X only supports DSA keys based on SHA1 (2048 bits or less) - this key is based on SHA2 and is %s bits ''', key_object.bit_size )) elif key_object.algorithm == 'dsa' and key_object.hash_algo is None: raise IncompleteAsymmetricKeyError(pretty_message( ''' The DSA key does not contain the necessary p, q and g parameters and can not be used ''' )) if isinstance(key_object, keys.PublicKeyInfo): source = key_object.dump() key_class = Security.kSecAttrKeyClassPublic else: source = key_object.unwrap().dump() key_class = Security.kSecAttrKeyClassPrivate cf_source = None cf_dict = None cf_output = None try: cf_source = CFHelpers.cf_data_from_bytes(source) key_type = { 'dsa': Security.kSecAttrKeyTypeDSA, 'ec': Security.kSecAttrKeyTypeECDSA, 'rsa': Security.kSecAttrKeyTypeRSA, }[key_object.algorithm] cf_dict = CFHelpers.cf_dictionary_from_pairs([ (Security.kSecAttrKeyType, key_type), (Security.kSecAttrKeyClass, key_class), (Security.kSecAttrCanSign, CoreFoundation.kCFBooleanTrue), (Security.kSecAttrCanVerify, CoreFoundation.kCFBooleanTrue), ]) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_key_ref = Security.SecKeyCreateFromData(cf_dict, cf_source, error_pointer) handle_cf_error(error_pointer) if key_class == Security.kSecAttrKeyClassPublic: return PublicKey(sec_key_ref, key_object) if key_class == Security.kSecAttrKeyClassPrivate: return PrivateKey(sec_key_ref, key_object) finally: if cf_source: CoreFoundation.CFRelease(cf_source) if cf_dict: CoreFoundation.CFRelease(cf_dict) if cf_output: CoreFoundation.CFRelease(cf_output)
[ "Common", "code", "to", "load", "public", "and", "private", "keys", "into", "PublicKey", "and", "PrivateKey", "objects" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L694-L782
[ "def", "_load_key", "(", "key_object", ")", ":", "if", "key_object", ".", "algorithm", "==", "'ec'", ":", "curve_type", ",", "details", "=", "key_object", ".", "curve", "if", "curve_type", "!=", "'named'", ":", "raise", "AsymmetricKeyError", "(", "'OS X only supports EC keys using named curves'", ")", "if", "details", "not", "in", "set", "(", "[", "'secp256r1'", ",", "'secp384r1'", ",", "'secp521r1'", "]", ")", ":", "raise", "AsymmetricKeyError", "(", "pretty_message", "(", "'''\n OS X only supports EC keys using the named curves secp256r1,\n secp384r1 and secp521r1\n '''", ")", ")", "elif", "key_object", ".", "algorithm", "==", "'dsa'", "and", "key_object", ".", "hash_algo", "==", "'sha2'", ":", "raise", "AsymmetricKeyError", "(", "pretty_message", "(", "'''\n OS X only supports DSA keys based on SHA1 (2048 bits or less) - this\n key is based on SHA2 and is %s bits\n '''", ",", "key_object", ".", "bit_size", ")", ")", "elif", "key_object", ".", "algorithm", "==", "'dsa'", "and", "key_object", ".", "hash_algo", "is", "None", ":", "raise", "IncompleteAsymmetricKeyError", "(", "pretty_message", "(", "'''\n The DSA key does not contain the necessary p, q and g parameters\n and can not be used\n '''", ")", ")", "if", "isinstance", "(", "key_object", ",", "keys", ".", "PublicKeyInfo", ")", ":", "source", "=", "key_object", ".", "dump", "(", ")", "key_class", "=", "Security", ".", "kSecAttrKeyClassPublic", "else", ":", "source", "=", "key_object", ".", "unwrap", "(", ")", ".", "dump", "(", ")", "key_class", "=", "Security", ".", "kSecAttrKeyClassPrivate", "cf_source", "=", "None", "cf_dict", "=", "None", "cf_output", "=", "None", "try", ":", "cf_source", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "source", ")", "key_type", "=", "{", "'dsa'", ":", "Security", ".", "kSecAttrKeyTypeDSA", ",", "'ec'", ":", "Security", ".", "kSecAttrKeyTypeECDSA", ",", "'rsa'", ":", "Security", ".", "kSecAttrKeyTypeRSA", ",", "}", "[", "key_object", ".", "algorithm", "]", "cf_dict", "=", "CFHelpers", ".", "cf_dictionary_from_pairs", "(", "[", "(", "Security", ".", "kSecAttrKeyType", ",", "key_type", ")", ",", "(", "Security", ".", "kSecAttrKeyClass", ",", "key_class", ")", ",", "(", "Security", ".", "kSecAttrCanSign", ",", "CoreFoundation", ".", "kCFBooleanTrue", ")", ",", "(", "Security", ".", "kSecAttrCanVerify", ",", "CoreFoundation", ".", "kCFBooleanTrue", ")", ",", "]", ")", "error_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFErrorRef *'", ")", "sec_key_ref", "=", "Security", ".", "SecKeyCreateFromData", "(", "cf_dict", ",", "cf_source", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "key_class", "==", "Security", ".", "kSecAttrKeyClassPublic", ":", "return", "PublicKey", "(", "sec_key_ref", ",", "key_object", ")", "if", "key_class", "==", "Security", ".", "kSecAttrKeyClassPrivate", ":", "return", "PrivateKey", "(", "sec_key_ref", ",", "key_object", ")", "finally", ":", "if", "cf_source", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_source", ")", "if", "cf_dict", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_dict", ")", "if", "cf_output", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_output", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rsa_pkcs1v15_encrypt
Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1 v1.5 padding. :param certificate_or_public_key: A PublicKey or Certificate object :param data: A byte string, with a maximum length 11 bytes less than the key length (in bytes) :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the encrypted data
oscrypto/_osx/asymmetric.py
def rsa_pkcs1v15_encrypt(certificate_or_public_key, data): """ Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1 v1.5 padding. :param certificate_or_public_key: A PublicKey or Certificate object :param data: A byte string, with a maximum length 11 bytes less than the key length (in bytes) :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the encrypted data """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) key_length = certificate_or_public_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyEncrypt( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length))
def rsa_pkcs1v15_encrypt(certificate_or_public_key, data): """ Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1 v1.5 padding. :param certificate_or_public_key: A PublicKey or Certificate object :param data: A byte string, with a maximum length 11 bytes less than the key length (in bytes) :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the encrypted data """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) key_length = certificate_or_public_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyEncrypt( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length))
[ "Encrypts", "a", "byte", "string", "using", "an", "RSA", "public", "key", "or", "certificate", ".", "Uses", "PKCS#1", "v1", ".", "5", "padding", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L846-L897
[ "def", "rsa_pkcs1v15_encrypt", "(", "certificate_or_public_key", ",", "data", ")", ":", "if", "not", "isinstance", "(", "certificate_or_public_key", ",", "(", "Certificate", ",", "PublicKey", ")", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n certificate_or_public_key must be an instance of the Certificate or\n PublicKey class, not %s\n '''", ",", "type_name", "(", "certificate_or_public_key", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "key_length", "=", "certificate_or_public_key", ".", "byte_size", "buffer", "=", "buffer_from_bytes", "(", "key_length", ")", "output_length", "=", "new", "(", "Security", ",", "'size_t *'", ",", "key_length", ")", "result", "=", "Security", ".", "SecKeyEncrypt", "(", "certificate_or_public_key", ".", "sec_key_ref", ",", "SecurityConst", ".", "kSecPaddingPKCS1", ",", "data", ",", "len", "(", "data", ")", ",", "buffer", ",", "output_length", ")", "handle_sec_error", "(", "result", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "output_length", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rsa_pkcs1v15_decrypt
Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext
oscrypto/_osx/asymmetric.py
def rsa_pkcs1v15_decrypt(private_key, ciphertext): """ Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(ciphertext) )) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) if osx_version_info < (10, 8): padding = SecurityConst.kSecPaddingNone else: padding = SecurityConst.kSecPaddingPKCS1 result = Security.SecKeyDecrypt( private_key.sec_key_ref, padding, ciphertext, len(ciphertext), buffer, output_length ) handle_sec_error(result) output = bytes_from_buffer(buffer, deref(output_length)) if osx_version_info < (10, 8): output = remove_pkcs1v15_encryption_padding(key_length, output) return output
def rsa_pkcs1v15_decrypt(private_key, ciphertext): """ Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(ciphertext) )) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) if osx_version_info < (10, 8): padding = SecurityConst.kSecPaddingNone else: padding = SecurityConst.kSecPaddingPKCS1 result = Security.SecKeyDecrypt( private_key.sec_key_ref, padding, ciphertext, len(ciphertext), buffer, output_length ) handle_sec_error(result) output = bytes_from_buffer(buffer, deref(output_length)) if osx_version_info < (10, 8): output = remove_pkcs1v15_encryption_padding(key_length, output) return output
[ "Decrypts", "a", "byte", "string", "using", "an", "RSA", "private", "key", ".", "Uses", "PKCS#1", "v1", ".", "5", "padding", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L900-L959
[ "def", "rsa_pkcs1v15_decrypt", "(", "private_key", ",", "ciphertext", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n private_key must an instance of the PrivateKey class, not %s\n '''", ",", "type_name", "(", "private_key", ")", ")", ")", "if", "not", "isinstance", "(", "ciphertext", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "ciphertext", ")", ")", ")", "key_length", "=", "private_key", ".", "byte_size", "buffer", "=", "buffer_from_bytes", "(", "key_length", ")", "output_length", "=", "new", "(", "Security", ",", "'size_t *'", ",", "key_length", ")", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", ":", "padding", "=", "SecurityConst", ".", "kSecPaddingNone", "else", ":", "padding", "=", "SecurityConst", ".", "kSecPaddingPKCS1", "result", "=", "Security", ".", "SecKeyDecrypt", "(", "private_key", ".", "sec_key_ref", ",", "padding", ",", "ciphertext", ",", "len", "(", "ciphertext", ")", ",", "buffer", ",", "output_length", ")", "handle_sec_error", "(", "result", ")", "output", "=", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "output_length", ")", ")", "if", "osx_version_info", "<", "(", "10", ",", "8", ")", ":", "output", "=", "remove_pkcs1v15_encryption_padding", "(", "key_length", ",", "output", ")", "return", "output" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_encrypt
Encrypts plaintext using an RSA public key or certificate :param certificate_or_public_key: A Certificate or PublicKey object :param data: The plaintext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext
oscrypto/_osx/asymmetric.py
def _encrypt(certificate_or_public_key, data, padding): """ Encrypts plaintext using an RSA public key or certificate :param certificate_or_public_key: A Certificate or PublicKey object :param data: The plaintext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if not padding: raise ValueError('padding must be specified') cf_data = None sec_transform = None try: cf_data = CFHelpers.cf_data_from_bytes(data) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecEncryptTransformCreate( certificate_or_public_key.sec_key_ref, error_pointer ) handle_cf_error(error_pointer) if padding: Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, padding, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) ciphertext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(ciphertext) finally: if cf_data: CoreFoundation.CFRelease(cf_data) if sec_transform: CoreFoundation.CFRelease(sec_transform)
def _encrypt(certificate_or_public_key, data, padding): """ Encrypts plaintext using an RSA public key or certificate :param certificate_or_public_key: A Certificate or PublicKey object :param data: The plaintext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if not padding: raise ValueError('padding must be specified') cf_data = None sec_transform = None try: cf_data = CFHelpers.cf_data_from_bytes(data) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecEncryptTransformCreate( certificate_or_public_key.sec_key_ref, error_pointer ) handle_cf_error(error_pointer) if padding: Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, padding, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) ciphertext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(ciphertext) finally: if cf_data: CoreFoundation.CFRelease(cf_data) if sec_transform: CoreFoundation.CFRelease(sec_transform)
[ "Encrypts", "plaintext", "using", "an", "RSA", "public", "key", "or", "certificate" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L1009-L1090
[ "def", "_encrypt", "(", "certificate_or_public_key", ",", "data", ",", "padding", ")", ":", "if", "not", "isinstance", "(", "certificate_or_public_key", ",", "(", "Certificate", ",", "PublicKey", ")", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n certificate_or_public_key must be an instance of the Certificate or\n PublicKey class, not %s\n '''", ",", "type_name", "(", "certificate_or_public_key", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "if", "not", "padding", ":", "raise", "ValueError", "(", "'padding must be specified'", ")", "cf_data", "=", "None", "sec_transform", "=", "None", "try", ":", "cf_data", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "data", ")", "error_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFErrorRef *'", ")", "sec_transform", "=", "Security", ".", "SecEncryptTransformCreate", "(", "certificate_or_public_key", ".", "sec_key_ref", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "padding", ":", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecPaddingKey", ",", "padding", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecTransformInputAttributeName", ",", "cf_data", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "ciphertext", "=", "Security", ".", "SecTransformExecute", "(", "sec_transform", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "return", "CFHelpers", ".", "cf_data_to_bytes", "(", "ciphertext", ")", "finally", ":", "if", "cf_data", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data", ")", "if", "sec_transform", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_transform", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_decrypt
Decrypts RSA ciphertext using a private key :param private_key: A PrivateKey object :param ciphertext: The ciphertext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/asymmetric.py
def _decrypt(private_key, ciphertext, padding): """ Decrypts RSA ciphertext using a private key :param private_key: A PrivateKey object :param ciphertext: The ciphertext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' ciphertext must be a byte string, not %s ''', type_name(ciphertext) )) if not padding: raise ValueError('padding must be specified') cf_data = None sec_transform = None try: cf_data = CFHelpers.cf_data_from_bytes(ciphertext) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecDecryptTransformCreate( private_key.sec_key_ref, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, padding, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) plaintext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(plaintext) finally: if cf_data: CoreFoundation.CFRelease(cf_data) if sec_transform: CoreFoundation.CFRelease(sec_transform)
def _decrypt(private_key, ciphertext, padding): """ Decrypts RSA ciphertext using a private key :param private_key: A PrivateKey object :param ciphertext: The ciphertext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' ciphertext must be a byte string, not %s ''', type_name(ciphertext) )) if not padding: raise ValueError('padding must be specified') cf_data = None sec_transform = None try: cf_data = CFHelpers.cf_data_from_bytes(ciphertext) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecDecryptTransformCreate( private_key.sec_key_ref, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, padding, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) plaintext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(plaintext) finally: if cf_data: CoreFoundation.CFRelease(cf_data) if sec_transform: CoreFoundation.CFRelease(sec_transform)
[ "Decrypts", "RSA", "ciphertext", "using", "a", "private", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L1093-L1172
[ "def", "_decrypt", "(", "private_key", ",", "ciphertext", ",", "padding", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n private_key must be an instance of the PrivateKey class, not %s\n '''", ",", "type_name", "(", "private_key", ")", ")", ")", "if", "not", "isinstance", "(", "ciphertext", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n ciphertext must be a byte string, not %s\n '''", ",", "type_name", "(", "ciphertext", ")", ")", ")", "if", "not", "padding", ":", "raise", "ValueError", "(", "'padding must be specified'", ")", "cf_data", "=", "None", "sec_transform", "=", "None", "try", ":", "cf_data", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "ciphertext", ")", "error_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFErrorRef *'", ")", "sec_transform", "=", "Security", ".", "SecDecryptTransformCreate", "(", "private_key", ".", "sec_key_ref", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecPaddingKey", ",", "padding", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecTransformInputAttributeName", ",", "cf_data", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "plaintext", "=", "Security", ".", "SecTransformExecute", "(", "sec_transform", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "return", "CFHelpers", ".", "cf_data_to_bytes", "(", "plaintext", ")", "finally", ":", "if", "cf_data", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data", ")", "if", "sec_transform", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_transform", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rsa_pss_verify
Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library
oscrypto/_osx/asymmetric.py
def rsa_pss_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if certificate_or_public_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA public key') hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) key_length = certificate_or_public_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyEncrypt( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingNone, signature, len(signature), buffer, output_length ) handle_sec_error(result) plaintext = bytes_from_buffer(buffer, deref(output_length)) if not verify_pss_padding(hash_algorithm, hash_length, certificate_or_public_key.bit_size, data, plaintext): raise SignatureError('Signature is invalid')
def rsa_pss_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if certificate_or_public_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA public key') hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) key_length = certificate_or_public_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyEncrypt( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingNone, signature, len(signature), buffer, output_length ) handle_sec_error(result) plaintext = bytes_from_buffer(buffer, deref(output_length)) if not verify_pss_padding(hash_algorithm, hash_length, certificate_or_public_key.bit_size, data, plaintext): raise SignatureError('Signature is invalid')
[ "Verifies", "an", "RSASSA", "-", "PSS", "signature", ".", "For", "the", "PSS", "padding", "the", "mask", "gen", "algorithm", "will", "be", "mgf1", "using", "the", "same", "hash", "algorithm", "as", "the", "signature", ".", "The", "salt", "length", "with", "be", "the", "length", "of", "the", "hash", "algorithm", "and", "the", "trailer", "field", "with", "be", "the", "standard", "0xBC", "byte", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L1209-L1278
[ "def", "rsa_pss_verify", "(", "certificate_or_public_key", ",", "signature", ",", "data", ",", "hash_algorithm", ")", ":", "if", "not", "isinstance", "(", "certificate_or_public_key", ",", "(", "Certificate", ",", "PublicKey", ")", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n certificate_or_public_key must be an instance of the Certificate or\n PublicKey class, not %s\n '''", ",", "type_name", "(", "certificate_or_public_key", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "if", "certificate_or_public_key", ".", "algorithm", "!=", "'rsa'", ":", "raise", "ValueError", "(", "'The key specified is not an RSA public key'", ")", "hash_length", "=", "{", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", ".", "get", "(", "hash_algorithm", ",", "0", ")", "key_length", "=", "certificate_or_public_key", ".", "byte_size", "buffer", "=", "buffer_from_bytes", "(", "key_length", ")", "output_length", "=", "new", "(", "Security", ",", "'size_t *'", ",", "key_length", ")", "result", "=", "Security", ".", "SecKeyEncrypt", "(", "certificate_or_public_key", ".", "sec_key_ref", ",", "SecurityConst", ".", "kSecPaddingNone", ",", "signature", ",", "len", "(", "signature", ")", ",", "buffer", ",", "output_length", ")", "handle_sec_error", "(", "result", ")", "plaintext", "=", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "output_length", ")", ")", "if", "not", "verify_pss_padding", "(", "hash_algorithm", ",", "hash_length", ",", "certificate_or_public_key", ".", "bit_size", ",", "data", ",", "plaintext", ")", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_verify
Verifies an RSA, DSA or ECDSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library
oscrypto/_osx/asymmetric.py
def _verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSA, DSA or ECDSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(signature, byte_cls): raise TypeError(pretty_message( ''' signature must be a byte string, not %s ''', type_name(signature) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']) if certificate_or_public_key.algorithm == 'rsa': valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"' if certificate_or_public_key.algorithm == 'rsa': valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if certificate_or_public_key.algorithm == 'rsa' and hash_algorithm == 'raw': if len(data) > certificate_or_public_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', certificate_or_public_key.byte_size, len(data) )) result = Security.SecKeyRawVerify( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), signature, len(signature) ) # errSSLCrypto is returned in some situations on macOS 10.12 if result == SecurityConst.errSecVerifyFailed or result == SecurityConst.errSSLCrypto: raise SignatureError('Signature is invalid') handle_sec_error(result) return cf_signature = None cf_data = None cf_hash_length = None sec_transform = None try: error_pointer = new(CoreFoundation, 'CFErrorRef *') cf_signature = CFHelpers.cf_data_from_bytes(signature) sec_transform = Security.SecVerifyTransformCreate( certificate_or_public_key.sec_key_ref, cf_signature, error_pointer ) handle_cf_error(error_pointer) hash_constant = { 'md5': Security.kSecDigestMD5, 'sha1': Security.kSecDigestSHA1, 'sha224': Security.kSecDigestSHA2, 'sha256': Security.kSecDigestSHA2, 'sha384': Security.kSecDigestSHA2, 'sha512': Security.kSecDigestSHA2 }[hash_algorithm] Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestTypeAttribute, hash_constant, error_pointer ) handle_cf_error(error_pointer) if hash_algorithm in set(['sha224', 'sha256', 'sha384', 'sha512']): hash_length = { 'sha224': 224, 'sha256': 256, 'sha384': 384, 'sha512': 512 }[hash_algorithm] cf_hash_length = CFHelpers.cf_number_from_integer(hash_length) Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestLengthAttribute, cf_hash_length, error_pointer ) handle_cf_error(error_pointer) if certificate_or_public_key.algorithm == 'rsa': Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, Security.kSecPaddingPKCS1Key, error_pointer ) handle_cf_error(error_pointer) cf_data = CFHelpers.cf_data_from_bytes(data) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) res = Security.SecTransformExecute(sec_transform, error_pointer) if not is_null(error_pointer): error = unwrap(error_pointer) if not is_null(error): raise SignatureError('Signature is invalid') res = bool(CoreFoundation.CFBooleanGetValue(res)) if not res: raise SignatureError('Signature is invalid') finally: if sec_transform: CoreFoundation.CFRelease(sec_transform) if cf_signature: CoreFoundation.CFRelease(cf_signature) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_hash_length: CoreFoundation.CFRelease(cf_hash_length)
def _verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSA, DSA or ECDSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(signature, byte_cls): raise TypeError(pretty_message( ''' signature must be a byte string, not %s ''', type_name(signature) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']) if certificate_or_public_key.algorithm == 'rsa': valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"' if certificate_or_public_key.algorithm == 'rsa': valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if certificate_or_public_key.algorithm == 'rsa' and hash_algorithm == 'raw': if len(data) > certificate_or_public_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', certificate_or_public_key.byte_size, len(data) )) result = Security.SecKeyRawVerify( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), signature, len(signature) ) # errSSLCrypto is returned in some situations on macOS 10.12 if result == SecurityConst.errSecVerifyFailed or result == SecurityConst.errSSLCrypto: raise SignatureError('Signature is invalid') handle_sec_error(result) return cf_signature = None cf_data = None cf_hash_length = None sec_transform = None try: error_pointer = new(CoreFoundation, 'CFErrorRef *') cf_signature = CFHelpers.cf_data_from_bytes(signature) sec_transform = Security.SecVerifyTransformCreate( certificate_or_public_key.sec_key_ref, cf_signature, error_pointer ) handle_cf_error(error_pointer) hash_constant = { 'md5': Security.kSecDigestMD5, 'sha1': Security.kSecDigestSHA1, 'sha224': Security.kSecDigestSHA2, 'sha256': Security.kSecDigestSHA2, 'sha384': Security.kSecDigestSHA2, 'sha512': Security.kSecDigestSHA2 }[hash_algorithm] Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestTypeAttribute, hash_constant, error_pointer ) handle_cf_error(error_pointer) if hash_algorithm in set(['sha224', 'sha256', 'sha384', 'sha512']): hash_length = { 'sha224': 224, 'sha256': 256, 'sha384': 384, 'sha512': 512 }[hash_algorithm] cf_hash_length = CFHelpers.cf_number_from_integer(hash_length) Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestLengthAttribute, cf_hash_length, error_pointer ) handle_cf_error(error_pointer) if certificate_or_public_key.algorithm == 'rsa': Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, Security.kSecPaddingPKCS1Key, error_pointer ) handle_cf_error(error_pointer) cf_data = CFHelpers.cf_data_from_bytes(data) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) res = Security.SecTransformExecute(sec_transform, error_pointer) if not is_null(error_pointer): error = unwrap(error_pointer) if not is_null(error): raise SignatureError('Signature is invalid') res = bool(CoreFoundation.CFBooleanGetValue(res)) if not res: raise SignatureError('Signature is invalid') finally: if sec_transform: CoreFoundation.CFRelease(sec_transform) if cf_signature: CoreFoundation.CFRelease(cf_signature) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_hash_length: CoreFoundation.CFRelease(cf_hash_length)
[ "Verifies", "an", "RSA", "DSA", "or", "ECDSA", "signature" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L1339-L1516
[ "def", "_verify", "(", "certificate_or_public_key", ",", "signature", ",", "data", ",", "hash_algorithm", ")", ":", "if", "not", "isinstance", "(", "certificate_or_public_key", ",", "(", "Certificate", ",", "PublicKey", ")", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n certificate_or_public_key must be an instance of the Certificate or\n PublicKey class, not %s\n '''", ",", "type_name", "(", "certificate_or_public_key", ")", ")", ")", "if", "not", "isinstance", "(", "signature", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n signature must be a byte string, not %s\n '''", ",", "type_name", "(", "signature", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "valid_hash_algorithms", "=", "set", "(", "[", "'md5'", ",", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", "if", "certificate_or_public_key", ".", "algorithm", "==", "'rsa'", ":", "valid_hash_algorithms", "|=", "set", "(", "[", "'raw'", "]", ")", "if", "hash_algorithm", "not", "in", "valid_hash_algorithms", ":", "valid_hash_algorithms_error", "=", "'\"md5\", \"sha1\", \"sha224\", \"sha256\", \"sha384\", \"sha512\"'", "if", "certificate_or_public_key", ".", "algorithm", "==", "'rsa'", ":", "valid_hash_algorithms_error", "+=", "', \"raw\"'", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of %s, not %s\n '''", ",", "valid_hash_algorithms_error", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "if", "certificate_or_public_key", ".", "algorithm", "==", "'rsa'", "and", "hash_algorithm", "==", "'raw'", ":", "if", "len", "(", "data", ")", ">", "certificate_or_public_key", ".", "byte_size", "-", "11", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n data must be 11 bytes shorter than the key size when\n hash_algorithm is \"raw\" - key size is %s bytes, but data\n is %s bytes long\n '''", ",", "certificate_or_public_key", ".", "byte_size", ",", "len", "(", "data", ")", ")", ")", "result", "=", "Security", ".", "SecKeyRawVerify", "(", "certificate_or_public_key", ".", "sec_key_ref", ",", "SecurityConst", ".", "kSecPaddingPKCS1", ",", "data", ",", "len", "(", "data", ")", ",", "signature", ",", "len", "(", "signature", ")", ")", "# errSSLCrypto is returned in some situations on macOS 10.12", "if", "result", "==", "SecurityConst", ".", "errSecVerifyFailed", "or", "result", "==", "SecurityConst", ".", "errSSLCrypto", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "handle_sec_error", "(", "result", ")", "return", "cf_signature", "=", "None", "cf_data", "=", "None", "cf_hash_length", "=", "None", "sec_transform", "=", "None", "try", ":", "error_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFErrorRef *'", ")", "cf_signature", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "signature", ")", "sec_transform", "=", "Security", ".", "SecVerifyTransformCreate", "(", "certificate_or_public_key", ".", "sec_key_ref", ",", "cf_signature", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "hash_constant", "=", "{", "'md5'", ":", "Security", ".", "kSecDigestMD5", ",", "'sha1'", ":", "Security", ".", "kSecDigestSHA1", ",", "'sha224'", ":", "Security", ".", "kSecDigestSHA2", ",", "'sha256'", ":", "Security", ".", "kSecDigestSHA2", ",", "'sha384'", ":", "Security", ".", "kSecDigestSHA2", ",", "'sha512'", ":", "Security", ".", "kSecDigestSHA2", "}", "[", "hash_algorithm", "]", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecDigestTypeAttribute", ",", "hash_constant", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "hash_algorithm", "in", "set", "(", "[", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", ":", "hash_length", "=", "{", "'sha224'", ":", "224", ",", "'sha256'", ":", "256", ",", "'sha384'", ":", "384", ",", "'sha512'", ":", "512", "}", "[", "hash_algorithm", "]", "cf_hash_length", "=", "CFHelpers", ".", "cf_number_from_integer", "(", "hash_length", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecDigestLengthAttribute", ",", "cf_hash_length", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "certificate_or_public_key", ".", "algorithm", "==", "'rsa'", ":", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecPaddingKey", ",", "Security", ".", "kSecPaddingPKCS1Key", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "cf_data", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "data", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecTransformInputAttributeName", ",", "cf_data", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "res", "=", "Security", ".", "SecTransformExecute", "(", "sec_transform", ",", "error_pointer", ")", "if", "not", "is_null", "(", "error_pointer", ")", ":", "error", "=", "unwrap", "(", "error_pointer", ")", "if", "not", "is_null", "(", "error", ")", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "res", "=", "bool", "(", "CoreFoundation", ".", "CFBooleanGetValue", "(", "res", ")", ")", "if", "not", "res", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "finally", ":", "if", "sec_transform", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_transform", ")", "if", "cf_signature", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_signature", ")", "if", "cf_data", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data", ")", "if", "cf_hash_length", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_hash_length", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rsa_pss_sign
Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature
oscrypto/_osx/asymmetric.py
def rsa_pss_sign(private_key, data, hash_algorithm): """ Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if private_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA private key') hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) encoded_data = add_pss_padding(hash_algorithm, hash_length, private_key.bit_size, data) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyDecrypt( private_key.sec_key_ref, SecurityConst.kSecPaddingNone, encoded_data, len(encoded_data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length))
def rsa_pss_sign(private_key, data, hash_algorithm): """ Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if private_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA private key') hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) encoded_data = add_pss_padding(hash_algorithm, hash_length, private_key.bit_size, data) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyDecrypt( private_key.sec_key_ref, SecurityConst.kSecPaddingNone, encoded_data, len(encoded_data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length))
[ "Generates", "an", "RSASSA", "-", "PSS", "signature", ".", "For", "the", "PSS", "padding", "the", "mask", "gen", "algorithm", "will", "be", "mgf1", "using", "the", "same", "hash", "algorithm", "as", "the", "signature", ".", "The", "salt", "length", "with", "be", "the", "length", "of", "the", "hash", "algorithm", "and", "the", "trailer", "field", "with", "be", "the", "standard", "0xBC", "byte", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L1553-L1621
[ "def", "rsa_pss_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n private_key must be an instance of the PrivateKey class, not %s\n '''", ",", "type_name", "(", "private_key", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "if", "private_key", ".", "algorithm", "!=", "'rsa'", ":", "raise", "ValueError", "(", "'The key specified is not an RSA private key'", ")", "hash_length", "=", "{", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", ".", "get", "(", "hash_algorithm", ",", "0", ")", "encoded_data", "=", "add_pss_padding", "(", "hash_algorithm", ",", "hash_length", ",", "private_key", ".", "bit_size", ",", "data", ")", "key_length", "=", "private_key", ".", "byte_size", "buffer", "=", "buffer_from_bytes", "(", "key_length", ")", "output_length", "=", "new", "(", "Security", ",", "'size_t *'", ",", "key_length", ")", "result", "=", "Security", ".", "SecKeyDecrypt", "(", "private_key", ".", "sec_key_ref", ",", "SecurityConst", ".", "kSecPaddingNone", ",", "encoded_data", ",", "len", "(", "encoded_data", ")", ",", "buffer", ",", "output_length", ")", "handle_sec_error", "(", "result", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "output_length", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_sign
Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature
oscrypto/_osx/asymmetric.py
def _sign(private_key, data, hash_algorithm): """ Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of PrivateKey, not %s ''', type_name(private_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']) if private_key.algorithm == 'rsa': valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"' if private_key.algorithm == 'rsa': valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if private_key.algorithm == 'rsa' and hash_algorithm == 'raw': if len(data) > private_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', private_key.byte_size, len(data) )) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyRawSign( private_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length)) cf_signature = None cf_data = None cf_hash_length = None sec_transform = None try: error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecSignTransformCreate(private_key.sec_key_ref, error_pointer) handle_cf_error(error_pointer) hash_constant = { 'md5': Security.kSecDigestMD5, 'sha1': Security.kSecDigestSHA1, 'sha224': Security.kSecDigestSHA2, 'sha256': Security.kSecDigestSHA2, 'sha384': Security.kSecDigestSHA2, 'sha512': Security.kSecDigestSHA2 }[hash_algorithm] Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestTypeAttribute, hash_constant, error_pointer ) handle_cf_error(error_pointer) if hash_algorithm in set(['sha224', 'sha256', 'sha384', 'sha512']): hash_length = { 'sha224': 224, 'sha256': 256, 'sha384': 384, 'sha512': 512 }[hash_algorithm] cf_hash_length = CFHelpers.cf_number_from_integer(hash_length) Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestLengthAttribute, cf_hash_length, error_pointer ) handle_cf_error(error_pointer) if private_key.algorithm == 'rsa': Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, Security.kSecPaddingPKCS1Key, error_pointer ) handle_cf_error(error_pointer) cf_data = CFHelpers.cf_data_from_bytes(data) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) cf_signature = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(cf_signature) finally: if sec_transform: CoreFoundation.CFRelease(sec_transform) if cf_signature: CoreFoundation.CFRelease(cf_signature) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_hash_length: CoreFoundation.CFRelease(cf_hash_length)
def _sign(private_key, data, hash_algorithm): """ Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of PrivateKey, not %s ''', type_name(private_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']) if private_key.algorithm == 'rsa': valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"' if private_key.algorithm == 'rsa': valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if private_key.algorithm == 'rsa' and hash_algorithm == 'raw': if len(data) > private_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', private_key.byte_size, len(data) )) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyRawSign( private_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length)) cf_signature = None cf_data = None cf_hash_length = None sec_transform = None try: error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecSignTransformCreate(private_key.sec_key_ref, error_pointer) handle_cf_error(error_pointer) hash_constant = { 'md5': Security.kSecDigestMD5, 'sha1': Security.kSecDigestSHA1, 'sha224': Security.kSecDigestSHA2, 'sha256': Security.kSecDigestSHA2, 'sha384': Security.kSecDigestSHA2, 'sha512': Security.kSecDigestSHA2 }[hash_algorithm] Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestTypeAttribute, hash_constant, error_pointer ) handle_cf_error(error_pointer) if hash_algorithm in set(['sha224', 'sha256', 'sha384', 'sha512']): hash_length = { 'sha224': 224, 'sha256': 256, 'sha384': 384, 'sha512': 512 }[hash_algorithm] cf_hash_length = CFHelpers.cf_number_from_integer(hash_length) Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestLengthAttribute, cf_hash_length, error_pointer ) handle_cf_error(error_pointer) if private_key.algorithm == 'rsa': Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, Security.kSecPaddingPKCS1Key, error_pointer ) handle_cf_error(error_pointer) cf_data = CFHelpers.cf_data_from_bytes(data) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) cf_signature = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(cf_signature) finally: if sec_transform: CoreFoundation.CFRelease(sec_transform) if cf_signature: CoreFoundation.CFRelease(cf_signature) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_hash_length: CoreFoundation.CFRelease(cf_hash_length)
[ "Generates", "an", "RSA", "DSA", "or", "ECDSA", "signature" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L1682-L1840
[ "def", "_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n private_key must be an instance of PrivateKey, not %s\n '''", ",", "type_name", "(", "private_key", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "valid_hash_algorithms", "=", "set", "(", "[", "'md5'", ",", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", "if", "private_key", ".", "algorithm", "==", "'rsa'", ":", "valid_hash_algorithms", "|=", "set", "(", "[", "'raw'", "]", ")", "if", "hash_algorithm", "not", "in", "valid_hash_algorithms", ":", "valid_hash_algorithms_error", "=", "'\"md5\", \"sha1\", \"sha224\", \"sha256\", \"sha384\", \"sha512\"'", "if", "private_key", ".", "algorithm", "==", "'rsa'", ":", "valid_hash_algorithms_error", "+=", "', \"raw\"'", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of %s, not %s\n '''", ",", "valid_hash_algorithms_error", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "if", "private_key", ".", "algorithm", "==", "'rsa'", "and", "hash_algorithm", "==", "'raw'", ":", "if", "len", "(", "data", ")", ">", "private_key", ".", "byte_size", "-", "11", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n data must be 11 bytes shorter than the key size when\n hash_algorithm is \"raw\" - key size is %s bytes, but\n data is %s bytes long\n '''", ",", "private_key", ".", "byte_size", ",", "len", "(", "data", ")", ")", ")", "key_length", "=", "private_key", ".", "byte_size", "buffer", "=", "buffer_from_bytes", "(", "key_length", ")", "output_length", "=", "new", "(", "Security", ",", "'size_t *'", ",", "key_length", ")", "result", "=", "Security", ".", "SecKeyRawSign", "(", "private_key", ".", "sec_key_ref", ",", "SecurityConst", ".", "kSecPaddingPKCS1", ",", "data", ",", "len", "(", "data", ")", ",", "buffer", ",", "output_length", ")", "handle_sec_error", "(", "result", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "output_length", ")", ")", "cf_signature", "=", "None", "cf_data", "=", "None", "cf_hash_length", "=", "None", "sec_transform", "=", "None", "try", ":", "error_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFErrorRef *'", ")", "sec_transform", "=", "Security", ".", "SecSignTransformCreate", "(", "private_key", ".", "sec_key_ref", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "hash_constant", "=", "{", "'md5'", ":", "Security", ".", "kSecDigestMD5", ",", "'sha1'", ":", "Security", ".", "kSecDigestSHA1", ",", "'sha224'", ":", "Security", ".", "kSecDigestSHA2", ",", "'sha256'", ":", "Security", ".", "kSecDigestSHA2", ",", "'sha384'", ":", "Security", ".", "kSecDigestSHA2", ",", "'sha512'", ":", "Security", ".", "kSecDigestSHA2", "}", "[", "hash_algorithm", "]", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecDigestTypeAttribute", ",", "hash_constant", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "hash_algorithm", "in", "set", "(", "[", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", ":", "hash_length", "=", "{", "'sha224'", ":", "224", ",", "'sha256'", ":", "256", ",", "'sha384'", ":", "384", ",", "'sha512'", ":", "512", "}", "[", "hash_algorithm", "]", "cf_hash_length", "=", "CFHelpers", ".", "cf_number_from_integer", "(", "hash_length", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecDigestLengthAttribute", ",", "cf_hash_length", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "private_key", ".", "algorithm", "==", "'rsa'", ":", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecPaddingKey", ",", "Security", ".", "kSecPaddingPKCS1Key", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "cf_data", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "data", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecTransformInputAttributeName", ",", "cf_data", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "cf_signature", "=", "Security", ".", "SecTransformExecute", "(", "sec_transform", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "return", "CFHelpers", ".", "cf_data_to_bytes", "(", "cf_signature", ")", "finally", ":", "if", "sec_transform", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_transform", ")", "if", "cf_signature", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_signature", ")", "if", "cf_data", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data", ")", "if", "cf_hash_length", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_hash_length", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
Certificate.public_key
:return: The PublicKey object for the public key this certificate contains
oscrypto/_osx/asymmetric.py
def public_key(self): """ :return: The PublicKey object for the public key this certificate contains """ if not self._public_key and self.sec_certificate_ref: sec_public_key_ref_pointer = new(Security, 'SecKeyRef *') res = Security.SecCertificateCopyPublicKey(self.sec_certificate_ref, sec_public_key_ref_pointer) handle_sec_error(res) sec_public_key_ref = unwrap(sec_public_key_ref_pointer) self._public_key = PublicKey(sec_public_key_ref, self.asn1['tbs_certificate']['subject_public_key_info']) return self._public_key
def public_key(self): """ :return: The PublicKey object for the public key this certificate contains """ if not self._public_key and self.sec_certificate_ref: sec_public_key_ref_pointer = new(Security, 'SecKeyRef *') res = Security.SecCertificateCopyPublicKey(self.sec_certificate_ref, sec_public_key_ref_pointer) handle_sec_error(res) sec_public_key_ref = unwrap(sec_public_key_ref_pointer) self._public_key = PublicKey(sec_public_key_ref, self.asn1['tbs_certificate']['subject_public_key_info']) return self._public_key
[ ":", "return", ":", "The", "PublicKey", "object", "for", "the", "public", "key", "this", "certificate", "contains" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/asymmetric.py#L196-L209
[ "def", "public_key", "(", "self", ")", ":", "if", "not", "self", ".", "_public_key", "and", "self", ".", "sec_certificate_ref", ":", "sec_public_key_ref_pointer", "=", "new", "(", "Security", ",", "'SecKeyRef *'", ")", "res", "=", "Security", ".", "SecCertificateCopyPublicKey", "(", "self", ".", "sec_certificate_ref", ",", "sec_public_key_ref_pointer", ")", "handle_sec_error", "(", "res", ")", "sec_public_key_ref", "=", "unwrap", "(", "sec_public_key_ref_pointer", ")", "self", ".", "_public_key", "=", "PublicKey", "(", "sec_public_key_ref", ",", "self", ".", "asn1", "[", "'tbs_certificate'", "]", "[", "'subject_public_key_info'", "]", ")", "return", "self", ".", "_public_key" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
backend
:return: A unicode string of the backend being used: "openssl", "osx", "win", "winlegacy"
oscrypto/__init__.py
def backend(): """ :return: A unicode string of the backend being used: "openssl", "osx", "win", "winlegacy" """ if _module_values['backend'] is not None: return _module_values['backend'] with _backend_lock: if _module_values['backend'] is not None: return _module_values['backend'] if sys.platform == 'win32': # Windows XP was major version 5, Vista was 6 if sys.getwindowsversion()[0] < 6: _module_values['backend'] = 'winlegacy' else: _module_values['backend'] = 'win' elif sys.platform == 'darwin': _module_values['backend'] = 'osx' else: _module_values['backend'] = 'openssl' return _module_values['backend']
def backend(): """ :return: A unicode string of the backend being used: "openssl", "osx", "win", "winlegacy" """ if _module_values['backend'] is not None: return _module_values['backend'] with _backend_lock: if _module_values['backend'] is not None: return _module_values['backend'] if sys.platform == 'win32': # Windows XP was major version 5, Vista was 6 if sys.getwindowsversion()[0] < 6: _module_values['backend'] = 'winlegacy' else: _module_values['backend'] = 'win' elif sys.platform == 'darwin': _module_values['backend'] = 'osx' else: _module_values['backend'] = 'openssl' return _module_values['backend']
[ ":", "return", ":", "A", "unicode", "string", "of", "the", "backend", "being", "used", ":", "openssl", "osx", "win", "winlegacy" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/__init__.py#L30-L55
[ "def", "backend", "(", ")", ":", "if", "_module_values", "[", "'backend'", "]", "is", "not", "None", ":", "return", "_module_values", "[", "'backend'", "]", "with", "_backend_lock", ":", "if", "_module_values", "[", "'backend'", "]", "is", "not", "None", ":", "return", "_module_values", "[", "'backend'", "]", "if", "sys", ".", "platform", "==", "'win32'", ":", "# Windows XP was major version 5, Vista was 6", "if", "sys", ".", "getwindowsversion", "(", ")", "[", "0", "]", "<", "6", ":", "_module_values", "[", "'backend'", "]", "=", "'winlegacy'", "else", ":", "_module_values", "[", "'backend'", "]", "=", "'win'", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "_module_values", "[", "'backend'", "]", "=", "'osx'", "else", ":", "_module_values", "[", "'backend'", "]", "=", "'openssl'", "return", "_module_values", "[", "'backend'", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
use_openssl
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll), or using a specific dynamic library on Linux/BSD (.so). This can also be used to configure oscrypto to use LibreSSL dynamic libraries. This method must be called before any oscrypto submodules are imported. :param libcrypto_path: A unicode string of the file path to the OpenSSL/LibreSSL libcrypto dynamic library. :param libssl_path: A unicode string of the file path to the OpenSSL/LibreSSL libssl dynamic library. :param trust_list_path: An optional unicode string of the path to a file containing OpenSSL-compatible CA certificates in PEM format. If this is not provided and the platform is OS X or Windows, the system trust roots will be exported from the OS and used for all TLS connections. :raises: ValueError - when one of the paths is not a unicode string OSError - when the trust_list_path does not exist on the filesystem oscrypto.errors.LibraryNotFoundError - when one of the path does not exist on the filesystem RuntimeError - when this function is called after another part of oscrypto has been imported
oscrypto/__init__.py
def use_openssl(libcrypto_path, libssl_path, trust_list_path=None): """ Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll), or using a specific dynamic library on Linux/BSD (.so). This can also be used to configure oscrypto to use LibreSSL dynamic libraries. This method must be called before any oscrypto submodules are imported. :param libcrypto_path: A unicode string of the file path to the OpenSSL/LibreSSL libcrypto dynamic library. :param libssl_path: A unicode string of the file path to the OpenSSL/LibreSSL libssl dynamic library. :param trust_list_path: An optional unicode string of the path to a file containing OpenSSL-compatible CA certificates in PEM format. If this is not provided and the platform is OS X or Windows, the system trust roots will be exported from the OS and used for all TLS connections. :raises: ValueError - when one of the paths is not a unicode string OSError - when the trust_list_path does not exist on the filesystem oscrypto.errors.LibraryNotFoundError - when one of the path does not exist on the filesystem RuntimeError - when this function is called after another part of oscrypto has been imported """ if not isinstance(libcrypto_path, str_cls): raise ValueError('libcrypto_path must be a unicode string, not %s' % type_name(libcrypto_path)) if not isinstance(libssl_path, str_cls): raise ValueError('libssl_path must be a unicode string, not %s' % type_name(libssl_path)) if not os.path.exists(libcrypto_path): raise LibraryNotFoundError('libcrypto does not exist at %s' % libcrypto_path) if not os.path.exists(libssl_path): raise LibraryNotFoundError('libssl does not exist at %s' % libssl_path) if trust_list_path is not None: if not isinstance(trust_list_path, str_cls): raise ValueError('trust_list_path must be a unicode string, not %s' % type_name(trust_list_path)) if not os.path.exists(trust_list_path): raise OSError('trust_list_path does not exist at %s' % trust_list_path) with _backend_lock: if _module_values['backend'] is not None: raise RuntimeError('Another part of oscrypto has already been imported, unable to force use of OpenSSL') _module_values['backend'] = 'openssl' _module_values['backend_config'] = { 'libcrypto_path': libcrypto_path, 'libssl_path': libssl_path, 'trust_list_path': trust_list_path, }
def use_openssl(libcrypto_path, libssl_path, trust_list_path=None): """ Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll), or using a specific dynamic library on Linux/BSD (.so). This can also be used to configure oscrypto to use LibreSSL dynamic libraries. This method must be called before any oscrypto submodules are imported. :param libcrypto_path: A unicode string of the file path to the OpenSSL/LibreSSL libcrypto dynamic library. :param libssl_path: A unicode string of the file path to the OpenSSL/LibreSSL libssl dynamic library. :param trust_list_path: An optional unicode string of the path to a file containing OpenSSL-compatible CA certificates in PEM format. If this is not provided and the platform is OS X or Windows, the system trust roots will be exported from the OS and used for all TLS connections. :raises: ValueError - when one of the paths is not a unicode string OSError - when the trust_list_path does not exist on the filesystem oscrypto.errors.LibraryNotFoundError - when one of the path does not exist on the filesystem RuntimeError - when this function is called after another part of oscrypto has been imported """ if not isinstance(libcrypto_path, str_cls): raise ValueError('libcrypto_path must be a unicode string, not %s' % type_name(libcrypto_path)) if not isinstance(libssl_path, str_cls): raise ValueError('libssl_path must be a unicode string, not %s' % type_name(libssl_path)) if not os.path.exists(libcrypto_path): raise LibraryNotFoundError('libcrypto does not exist at %s' % libcrypto_path) if not os.path.exists(libssl_path): raise LibraryNotFoundError('libssl does not exist at %s' % libssl_path) if trust_list_path is not None: if not isinstance(trust_list_path, str_cls): raise ValueError('trust_list_path must be a unicode string, not %s' % type_name(trust_list_path)) if not os.path.exists(trust_list_path): raise OSError('trust_list_path does not exist at %s' % trust_list_path) with _backend_lock: if _module_values['backend'] is not None: raise RuntimeError('Another part of oscrypto has already been imported, unable to force use of OpenSSL') _module_values['backend'] = 'openssl' _module_values['backend_config'] = { 'libcrypto_path': libcrypto_path, 'libssl_path': libssl_path, 'trust_list_path': trust_list_path, }
[ "Forces", "using", "OpenSSL", "dynamic", "libraries", "on", "OS", "X", "(", ".", "dylib", ")", "or", "Windows", "(", ".", "dll", ")", "or", "using", "a", "specific", "dynamic", "library", "on", "Linux", "/", "BSD", "(", ".", "so", ")", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/__init__.py#L81-L139
[ "def", "use_openssl", "(", "libcrypto_path", ",", "libssl_path", ",", "trust_list_path", "=", "None", ")", ":", "if", "not", "isinstance", "(", "libcrypto_path", ",", "str_cls", ")", ":", "raise", "ValueError", "(", "'libcrypto_path must be a unicode string, not %s'", "%", "type_name", "(", "libcrypto_path", ")", ")", "if", "not", "isinstance", "(", "libssl_path", ",", "str_cls", ")", ":", "raise", "ValueError", "(", "'libssl_path must be a unicode string, not %s'", "%", "type_name", "(", "libssl_path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "libcrypto_path", ")", ":", "raise", "LibraryNotFoundError", "(", "'libcrypto does not exist at %s'", "%", "libcrypto_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "libssl_path", ")", ":", "raise", "LibraryNotFoundError", "(", "'libssl does not exist at %s'", "%", "libssl_path", ")", "if", "trust_list_path", "is", "not", "None", ":", "if", "not", "isinstance", "(", "trust_list_path", ",", "str_cls", ")", ":", "raise", "ValueError", "(", "'trust_list_path must be a unicode string, not %s'", "%", "type_name", "(", "trust_list_path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "trust_list_path", ")", ":", "raise", "OSError", "(", "'trust_list_path does not exist at %s'", "%", "trust_list_path", ")", "with", "_backend_lock", ":", "if", "_module_values", "[", "'backend'", "]", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Another part of oscrypto has already been imported, unable to force use of OpenSSL'", ")", "_module_values", "[", "'backend'", "]", "=", "'openssl'", "_module_values", "[", "'backend_config'", "]", "=", "{", "'libcrypto_path'", ":", "libcrypto_path", ",", "'libssl_path'", ":", "libssl_path", ",", "'trust_list_path'", ":", "trust_list_path", ",", "}" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
use_winlegacy
Forces use of the legacy Windows CryptoAPI. This should only be used on Windows XP or for testing. It is less full-featured than the Cryptography Next Generation (CNG) API, and as a result the elliptic curve and PSS padding features are implemented in pure Python. This isn't ideal, but it a shim for end-user client code. No one is going to run a server on Windows XP anyway, right?! :raises: EnvironmentError - when this function is called on an operating system other than Windows RuntimeError - when this function is called after another part of oscrypto has been imported
oscrypto/__init__.py
def use_winlegacy(): """ Forces use of the legacy Windows CryptoAPI. This should only be used on Windows XP or for testing. It is less full-featured than the Cryptography Next Generation (CNG) API, and as a result the elliptic curve and PSS padding features are implemented in pure Python. This isn't ideal, but it a shim for end-user client code. No one is going to run a server on Windows XP anyway, right?! :raises: EnvironmentError - when this function is called on an operating system other than Windows RuntimeError - when this function is called after another part of oscrypto has been imported """ if sys.platform != 'win32': plat = platform.system() or sys.platform if plat == 'Darwin': plat = 'OS X' raise EnvironmentError('The winlegacy backend can only be used on Windows, not %s' % plat) with _backend_lock: if _module_values['backend'] is not None: raise RuntimeError( 'Another part of oscrypto has already been imported, unable to force use of Windows legacy CryptoAPI' ) _module_values['backend'] = 'winlegacy'
def use_winlegacy(): """ Forces use of the legacy Windows CryptoAPI. This should only be used on Windows XP or for testing. It is less full-featured than the Cryptography Next Generation (CNG) API, and as a result the elliptic curve and PSS padding features are implemented in pure Python. This isn't ideal, but it a shim for end-user client code. No one is going to run a server on Windows XP anyway, right?! :raises: EnvironmentError - when this function is called on an operating system other than Windows RuntimeError - when this function is called after another part of oscrypto has been imported """ if sys.platform != 'win32': plat = platform.system() or sys.platform if plat == 'Darwin': plat = 'OS X' raise EnvironmentError('The winlegacy backend can only be used on Windows, not %s' % plat) with _backend_lock: if _module_values['backend'] is not None: raise RuntimeError( 'Another part of oscrypto has already been imported, unable to force use of Windows legacy CryptoAPI' ) _module_values['backend'] = 'winlegacy'
[ "Forces", "use", "of", "the", "legacy", "Windows", "CryptoAPI", ".", "This", "should", "only", "be", "used", "on", "Windows", "XP", "or", "for", "testing", ".", "It", "is", "less", "full", "-", "featured", "than", "the", "Cryptography", "Next", "Generation", "(", "CNG", ")", "API", "and", "as", "a", "result", "the", "elliptic", "curve", "and", "PSS", "padding", "features", "are", "implemented", "in", "pure", "Python", ".", "This", "isn", "t", "ideal", "but", "it", "a", "shim", "for", "end", "-", "user", "client", "code", ".", "No", "one", "is", "going", "to", "run", "a", "server", "on", "Windows", "XP", "anyway", "right?!" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/__init__.py#L142-L167
[ "def", "use_winlegacy", "(", ")", ":", "if", "sys", ".", "platform", "!=", "'win32'", ":", "plat", "=", "platform", ".", "system", "(", ")", "or", "sys", ".", "platform", "if", "plat", "==", "'Darwin'", ":", "plat", "=", "'OS X'", "raise", "EnvironmentError", "(", "'The winlegacy backend can only be used on Windows, not %s'", "%", "plat", ")", "with", "_backend_lock", ":", "if", "_module_values", "[", "'backend'", "]", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Another part of oscrypto has already been imported, unable to force use of Windows legacy CryptoAPI'", ")", "_module_values", "[", "'backend'", "]", "=", "'winlegacy'" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
pkcs12_kdf
KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :param id_: The ID of the usage - 1 for key, 2 for iv, 3 for mac :return: The derived key as a byte string
oscrypto/_pkcs12.py
def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_): """ KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :param id_: The ID of the usage - 1 for key, 2 for iv, 3 for mac :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md5", "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) if id_ not in set([1, 2, 3]): raise ValueError(pretty_message( ''' id_ must be one of 1, 2, 3, not %s ''', repr(id_) )) utf16_password = password.decode('utf-8').encode('utf-16be') + b'\x00\x00' algo = getattr(hashlib, hash_algorithm) # u and v values are bytes (not bits as in the RFC) u = { 'md5': 16, 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] if hash_algorithm in ['sha384', 'sha512']: v = 128 else: v = 64 # Step 1 d = chr_cls(id_) * v # Step 2 s = b'' if salt != b'': s_len = v * int(math.ceil(float(len(salt)) / v)) while len(s) < s_len: s += salt s = s[0:s_len] # Step 3 p = b'' if utf16_password != b'': p_len = v * int(math.ceil(float(len(utf16_password)) / v)) while len(p) < p_len: p += utf16_password p = p[0:p_len] # Step 4 i = s + p # Step 5 c = int(math.ceil(float(key_length) / u)) a = b'\x00' * (c * u) for num in range(1, c + 1): # Step 6A a2 = algo(d + i).digest() for _ in range(2, iterations + 1): a2 = algo(a2).digest() if num < c: # Step 6B b = b'' while len(b) < v: b += a2 b = int_from_bytes(b[0:v]) + 1 # Step 6C for num2 in range(0, len(i) // v): start = num2 * v end = (num2 + 1) * v i_num2 = i[start:end] i_num2 = int_to_bytes(int_from_bytes(i_num2) + b) # Ensure the new slice is the right size i_num2_l = len(i_num2) if i_num2_l > v: i_num2 = i_num2[i_num2_l - v:] i = i[0:start] + i_num2 + i[end:] # Step 7 (one peice at a time) begin = (num - 1) * u to_copy = min(key_length, u) a = a[0:begin] + a2[0:to_copy] + a[begin + to_copy:] return a[0:key_length]
def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_): """ KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :param id_: The ID of the usage - 1 for key, 2 for iv, 3 for mac :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md5", "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) if id_ not in set([1, 2, 3]): raise ValueError(pretty_message( ''' id_ must be one of 1, 2, 3, not %s ''', repr(id_) )) utf16_password = password.decode('utf-8').encode('utf-16be') + b'\x00\x00' algo = getattr(hashlib, hash_algorithm) # u and v values are bytes (not bits as in the RFC) u = { 'md5': 16, 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] if hash_algorithm in ['sha384', 'sha512']: v = 128 else: v = 64 # Step 1 d = chr_cls(id_) * v # Step 2 s = b'' if salt != b'': s_len = v * int(math.ceil(float(len(salt)) / v)) while len(s) < s_len: s += salt s = s[0:s_len] # Step 3 p = b'' if utf16_password != b'': p_len = v * int(math.ceil(float(len(utf16_password)) / v)) while len(p) < p_len: p += utf16_password p = p[0:p_len] # Step 4 i = s + p # Step 5 c = int(math.ceil(float(key_length) / u)) a = b'\x00' * (c * u) for num in range(1, c + 1): # Step 6A a2 = algo(d + i).digest() for _ in range(2, iterations + 1): a2 = algo(a2).digest() if num < c: # Step 6B b = b'' while len(b) < v: b += a2 b = int_from_bytes(b[0:v]) + 1 # Step 6C for num2 in range(0, len(i) // v): start = num2 * v end = (num2 + 1) * v i_num2 = i[start:end] i_num2 = int_to_bytes(int_from_bytes(i_num2) + b) # Ensure the new slice is the right size i_num2_l = len(i_num2) if i_num2_l > v: i_num2 = i_num2[i_num2_l - v:] i = i[0:start] + i_num2 + i[end:] # Step 7 (one peice at a time) begin = (num - 1) * u to_copy = min(key_length, u) a = a[0:begin] + a2[0:to_copy] + a[begin + to_copy:] return a[0:key_length]
[ "KDF", "from", "RFC7292", "appendix", "b", ".", "2", "-", "https", ":", "//", "tools", ".", "ietf", ".", "org", "/", "html", "/", "rfc7292#page", "-", "19" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_pkcs12.py#L26-L198
[ "def", "pkcs12_kdf", "(", "hash_algorithm", ",", "password", ",", "salt", ",", "iterations", ",", "key_length", ",", "id_", ")", ":", "if", "not", "isinstance", "(", "password", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n password must be a byte string, not %s\n '''", ",", "type_name", "(", "password", ")", ")", ")", "if", "not", "isinstance", "(", "salt", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n salt must be a byte string, not %s\n '''", ",", "type_name", "(", "salt", ")", ")", ")", "if", "not", "isinstance", "(", "iterations", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n iterations must be an integer, not %s\n '''", ",", "type_name", "(", "iterations", ")", ")", ")", "if", "iterations", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iterations must be greater than 0 - is %s\n '''", ",", "repr", "(", "iterations", ")", ")", ")", "if", "not", "isinstance", "(", "key_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n key_length must be an integer, not %s\n '''", ",", "type_name", "(", "key_length", ")", ")", ")", "if", "key_length", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key_length must be greater than 0 - is %s\n '''", ",", "repr", "(", "key_length", ")", ")", ")", "if", "hash_algorithm", "not", "in", "set", "(", "[", "'md5'", ",", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of \"md5\", \"sha1\", \"sha224\", \"sha256\",\n \"sha384\", \"sha512\", not %s\n '''", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "if", "id_", "not", "in", "set", "(", "[", "1", ",", "2", ",", "3", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n id_ must be one of 1, 2, 3, not %s\n '''", ",", "repr", "(", "id_", ")", ")", ")", "utf16_password", "=", "password", ".", "decode", "(", "'utf-8'", ")", ".", "encode", "(", "'utf-16be'", ")", "+", "b'\\x00\\x00'", "algo", "=", "getattr", "(", "hashlib", ",", "hash_algorithm", ")", "# u and v values are bytes (not bits as in the RFC)", "u", "=", "{", "'md5'", ":", "16", ",", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", "[", "hash_algorithm", "]", "if", "hash_algorithm", "in", "[", "'sha384'", ",", "'sha512'", "]", ":", "v", "=", "128", "else", ":", "v", "=", "64", "# Step 1", "d", "=", "chr_cls", "(", "id_", ")", "*", "v", "# Step 2", "s", "=", "b''", "if", "salt", "!=", "b''", ":", "s_len", "=", "v", "*", "int", "(", "math", ".", "ceil", "(", "float", "(", "len", "(", "salt", ")", ")", "/", "v", ")", ")", "while", "len", "(", "s", ")", "<", "s_len", ":", "s", "+=", "salt", "s", "=", "s", "[", "0", ":", "s_len", "]", "# Step 3", "p", "=", "b''", "if", "utf16_password", "!=", "b''", ":", "p_len", "=", "v", "*", "int", "(", "math", ".", "ceil", "(", "float", "(", "len", "(", "utf16_password", ")", ")", "/", "v", ")", ")", "while", "len", "(", "p", ")", "<", "p_len", ":", "p", "+=", "utf16_password", "p", "=", "p", "[", "0", ":", "p_len", "]", "# Step 4", "i", "=", "s", "+", "p", "# Step 5", "c", "=", "int", "(", "math", ".", "ceil", "(", "float", "(", "key_length", ")", "/", "u", ")", ")", "a", "=", "b'\\x00'", "*", "(", "c", "*", "u", ")", "for", "num", "in", "range", "(", "1", ",", "c", "+", "1", ")", ":", "# Step 6A", "a2", "=", "algo", "(", "d", "+", "i", ")", ".", "digest", "(", ")", "for", "_", "in", "range", "(", "2", ",", "iterations", "+", "1", ")", ":", "a2", "=", "algo", "(", "a2", ")", ".", "digest", "(", ")", "if", "num", "<", "c", ":", "# Step 6B", "b", "=", "b''", "while", "len", "(", "b", ")", "<", "v", ":", "b", "+=", "a2", "b", "=", "int_from_bytes", "(", "b", "[", "0", ":", "v", "]", ")", "+", "1", "# Step 6C", "for", "num2", "in", "range", "(", "0", ",", "len", "(", "i", ")", "//", "v", ")", ":", "start", "=", "num2", "*", "v", "end", "=", "(", "num2", "+", "1", ")", "*", "v", "i_num2", "=", "i", "[", "start", ":", "end", "]", "i_num2", "=", "int_to_bytes", "(", "int_from_bytes", "(", "i_num2", ")", "+", "b", ")", "# Ensure the new slice is the right size", "i_num2_l", "=", "len", "(", "i_num2", ")", "if", "i_num2_l", ">", "v", ":", "i_num2", "=", "i_num2", "[", "i_num2_l", "-", "v", ":", "]", "i", "=", "i", "[", "0", ":", "start", "]", "+", "i_num2", "+", "i", "[", "end", ":", "]", "# Step 7 (one peice at a time)", "begin", "=", "(", "num", "-", "1", ")", "*", "u", "to_copy", "=", "min", "(", "key_length", ",", "u", ")", "a", "=", "a", "[", "0", ":", "begin", "]", "+", "a2", "[", "0", ":", "to_copy", "]", "+", "a", "[", "begin", "+", "to_copy", ":", "]", "return", "a", "[", "0", ":", "key_length", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
pbkdf2_iteration_calculator
Runs pbkdf2() twice to determine the approximate number of iterations to use to hit a desired time per run. Use this on a production machine to dynamically adjust the number of iterations as high as you can. :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param key_length: The length of the desired key in bytes :param target_ms: The number of milliseconds the derivation should take :param quiet: If no output should be printed as attempts are made :return: An integer number of iterations of PBKDF2 using the specified hash that will take at least target_ms
oscrypto/kdf.py
def pbkdf2_iteration_calculator(hash_algorithm, key_length, target_ms=100, quiet=False): """ Runs pbkdf2() twice to determine the approximate number of iterations to use to hit a desired time per run. Use this on a production machine to dynamically adjust the number of iterations as high as you can. :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param key_length: The length of the desired key in bytes :param target_ms: The number of milliseconds the derivation should take :param quiet: If no output should be printed as attempts are made :return: An integer number of iterations of PBKDF2 using the specified hash that will take at least target_ms """ if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if not isinstance(target_ms, int_types): raise TypeError(pretty_message( ''' target_ms must be an integer, not %s ''', type_name(target_ms) )) if target_ms < 1: raise ValueError(pretty_message( ''' target_ms must be greater than 0 - is %s ''', repr(target_ms) )) if pbkdf2.pure_python: raise OSError(pretty_message( ''' Only a very slow, pure-python version of PBKDF2 is available, making this function useless ''' )) iterations = 10000 password = 'this is a test'.encode('utf-8') salt = rand_bytes(key_length) def _measure(): start = _get_start() pbkdf2(hash_algorithm, password, salt, iterations, key_length) observed_ms = _get_elapsed(start) if not quiet: print('%s iterations in %sms' % (iterations, observed_ms)) return 1.0 / target_ms * observed_ms # Measure the initial guess, then estimate how many iterations it would # take to reach 1/2 of the target ms and try it to get a good final number fraction = _measure() iterations = int(iterations / fraction / 2.0) fraction = _measure() iterations = iterations / fraction # < 20,000 round to 1000 # 20,000-100,000 round to 5,000 # > 100,000 round to 10,000 round_factor = -3 if iterations < 100000 else -4 result = int(round(iterations, round_factor)) if result > 20000: result = (result // 5000) * 5000 return result
def pbkdf2_iteration_calculator(hash_algorithm, key_length, target_ms=100, quiet=False): """ Runs pbkdf2() twice to determine the approximate number of iterations to use to hit a desired time per run. Use this on a production machine to dynamically adjust the number of iterations as high as you can. :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param key_length: The length of the desired key in bytes :param target_ms: The number of milliseconds the derivation should take :param quiet: If no output should be printed as attempts are made :return: An integer number of iterations of PBKDF2 using the specified hash that will take at least target_ms """ if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if not isinstance(target_ms, int_types): raise TypeError(pretty_message( ''' target_ms must be an integer, not %s ''', type_name(target_ms) )) if target_ms < 1: raise ValueError(pretty_message( ''' target_ms must be greater than 0 - is %s ''', repr(target_ms) )) if pbkdf2.pure_python: raise OSError(pretty_message( ''' Only a very slow, pure-python version of PBKDF2 is available, making this function useless ''' )) iterations = 10000 password = 'this is a test'.encode('utf-8') salt = rand_bytes(key_length) def _measure(): start = _get_start() pbkdf2(hash_algorithm, password, salt, iterations, key_length) observed_ms = _get_elapsed(start) if not quiet: print('%s iterations in %sms' % (iterations, observed_ms)) return 1.0 / target_ms * observed_ms # Measure the initial guess, then estimate how many iterations it would # take to reach 1/2 of the target ms and try it to get a good final number fraction = _measure() iterations = int(iterations / fraction / 2.0) fraction = _measure() iterations = iterations / fraction # < 20,000 round to 1000 # 20,000-100,000 round to 5,000 # > 100,000 round to 10,000 round_factor = -3 if iterations < 100000 else -4 result = int(round(iterations, round_factor)) if result > 20000: result = (result // 5000) * 5000 return result
[ "Runs", "pbkdf2", "()", "twice", "to", "determine", "the", "approximate", "number", "of", "iterations", "to", "use", "to", "hit", "a", "desired", "time", "per", "run", ".", "Use", "this", "on", "a", "production", "machine", "to", "dynamically", "adjust", "the", "number", "of", "iterations", "as", "high", "as", "you", "can", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/kdf.py#L57-L157
[ "def", "pbkdf2_iteration_calculator", "(", "hash_algorithm", ",", "key_length", ",", "target_ms", "=", "100", ",", "quiet", "=", "False", ")", ":", "if", "hash_algorithm", "not", "in", "set", "(", "[", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of \"sha1\", \"sha224\", \"sha256\", \"sha384\",\n \"sha512\", not %s\n '''", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "if", "not", "isinstance", "(", "key_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n key_length must be an integer, not %s\n '''", ",", "type_name", "(", "key_length", ")", ")", ")", "if", "key_length", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key_length must be greater than 0 - is %s\n '''", ",", "repr", "(", "key_length", ")", ")", ")", "if", "not", "isinstance", "(", "target_ms", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n target_ms must be an integer, not %s\n '''", ",", "type_name", "(", "target_ms", ")", ")", ")", "if", "target_ms", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n target_ms must be greater than 0 - is %s\n '''", ",", "repr", "(", "target_ms", ")", ")", ")", "if", "pbkdf2", ".", "pure_python", ":", "raise", "OSError", "(", "pretty_message", "(", "'''\n Only a very slow, pure-python version of PBKDF2 is available,\n making this function useless\n '''", ")", ")", "iterations", "=", "10000", "password", "=", "'this is a test'", ".", "encode", "(", "'utf-8'", ")", "salt", "=", "rand_bytes", "(", "key_length", ")", "def", "_measure", "(", ")", ":", "start", "=", "_get_start", "(", ")", "pbkdf2", "(", "hash_algorithm", ",", "password", ",", "salt", ",", "iterations", ",", "key_length", ")", "observed_ms", "=", "_get_elapsed", "(", "start", ")", "if", "not", "quiet", ":", "print", "(", "'%s iterations in %sms'", "%", "(", "iterations", ",", "observed_ms", ")", ")", "return", "1.0", "/", "target_ms", "*", "observed_ms", "# Measure the initial guess, then estimate how many iterations it would", "# take to reach 1/2 of the target ms and try it to get a good final number", "fraction", "=", "_measure", "(", ")", "iterations", "=", "int", "(", "iterations", "/", "fraction", "/", "2.0", ")", "fraction", "=", "_measure", "(", ")", "iterations", "=", "iterations", "/", "fraction", "# < 20,000 round to 1000", "# 20,000-100,000 round to 5,000", "# > 100,000 round to 10,000", "round_factor", "=", "-", "3", "if", "iterations", "<", "100000", "else", "-", "4", "result", "=", "int", "(", "round", "(", "iterations", ",", "round_factor", ")", ")", "if", "result", ">", "20000", ":", "result", "=", "(", "result", "//", "5000", ")", "*", "5000", "return", "result" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
pbkdf1
An implementation of PBKDF1 - should only be used for interop with legacy systems, not new architectures :param hash_algorithm: The string name of the hash algorithm to use: "md2", "md5", "sha1" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :return: The derived key as a byte string
oscrypto/kdf.py
def pbkdf1(hash_algorithm, password, salt, iterations, key_length): """ An implementation of PBKDF1 - should only be used for interop with legacy systems, not new architectures :param hash_algorithm: The string name of the hash algorithm to use: "md2", "md5", "sha1" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', (type_name(password)) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', (type_name(salt)) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', (type_name(iterations)) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', (type_name(key_length)) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md2', 'md5', 'sha1']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md2", "md5", "sha1", not %s ''', repr(hash_algorithm) )) if key_length > 16 and hash_algorithm in set(['md2', 'md5']): raise ValueError(pretty_message( ''' key_length can not be longer than 16 for %s - is %s ''', (hash_algorithm, repr(key_length)) )) if key_length > 20 and hash_algorithm == 'sha1': raise ValueError(pretty_message( ''' key_length can not be longer than 20 for sha1 - is %s ''', repr(key_length) )) algo = getattr(hashlib, hash_algorithm) output = algo(password + salt).digest() for _ in range(2, iterations + 1): output = algo(output).digest() return output[:key_length]
def pbkdf1(hash_algorithm, password, salt, iterations, key_length): """ An implementation of PBKDF1 - should only be used for interop with legacy systems, not new architectures :param hash_algorithm: The string name of the hash algorithm to use: "md2", "md5", "sha1" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', (type_name(password)) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', (type_name(salt)) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', (type_name(iterations)) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', (type_name(key_length)) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md2', 'md5', 'sha1']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md2", "md5", "sha1", not %s ''', repr(hash_algorithm) )) if key_length > 16 and hash_algorithm in set(['md2', 'md5']): raise ValueError(pretty_message( ''' key_length can not be longer than 16 for %s - is %s ''', (hash_algorithm, repr(key_length)) )) if key_length > 20 and hash_algorithm == 'sha1': raise ValueError(pretty_message( ''' key_length can not be longer than 20 for sha1 - is %s ''', repr(key_length) )) algo = getattr(hashlib, hash_algorithm) output = algo(password + salt).digest() for _ in range(2, iterations + 1): output = algo(output).digest() return output[:key_length]
[ "An", "implementation", "of", "PBKDF1", "-", "should", "only", "be", "used", "for", "interop", "with", "legacy", "systems", "not", "new", "architectures" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/kdf.py#L160-L261
[ "def", "pbkdf1", "(", "hash_algorithm", ",", "password", ",", "salt", ",", "iterations", ",", "key_length", ")", ":", "if", "not", "isinstance", "(", "password", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n password must be a byte string, not %s\n '''", ",", "(", "type_name", "(", "password", ")", ")", ")", ")", "if", "not", "isinstance", "(", "salt", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n salt must be a byte string, not %s\n '''", ",", "(", "type_name", "(", "salt", ")", ")", ")", ")", "if", "not", "isinstance", "(", "iterations", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n iterations must be an integer, not %s\n '''", ",", "(", "type_name", "(", "iterations", ")", ")", ")", ")", "if", "iterations", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iterations must be greater than 0 - is %s\n '''", ",", "repr", "(", "iterations", ")", ")", ")", "if", "not", "isinstance", "(", "key_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n key_length must be an integer, not %s\n '''", ",", "(", "type_name", "(", "key_length", ")", ")", ")", ")", "if", "key_length", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key_length must be greater than 0 - is %s\n '''", ",", "repr", "(", "key_length", ")", ")", ")", "if", "hash_algorithm", "not", "in", "set", "(", "[", "'md2'", ",", "'md5'", ",", "'sha1'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of \"md2\", \"md5\", \"sha1\", not %s\n '''", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "if", "key_length", ">", "16", "and", "hash_algorithm", "in", "set", "(", "[", "'md2'", ",", "'md5'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key_length can not be longer than 16 for %s - is %s\n '''", ",", "(", "hash_algorithm", ",", "repr", "(", "key_length", ")", ")", ")", ")", "if", "key_length", ">", "20", "and", "hash_algorithm", "==", "'sha1'", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key_length can not be longer than 20 for sha1 - is %s\n '''", ",", "repr", "(", "key_length", ")", ")", ")", "algo", "=", "getattr", "(", "hashlib", ",", "hash_algorithm", ")", "output", "=", "algo", "(", "password", "+", "salt", ")", ".", "digest", "(", ")", "for", "_", "in", "range", "(", "2", ",", "iterations", "+", "1", ")", ":", "output", "=", "algo", "(", "output", ")", ".", "digest", "(", ")", "return", "output", "[", ":", "key_length", "]" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
handle_error
Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message
oscrypto/_win/_advapi32.py
def handle_error(result): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message """ if result: return code, error_string = get_error() if code == Advapi32Const.NTE_BAD_SIGNATURE: raise SignatureError('Signature is invalid') if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) raise OSError(error_string)
def handle_error(result): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message """ if result: return code, error_string = get_error() if code == Advapi32Const.NTE_BAD_SIGNATURE: raise SignatureError('Signature is invalid') if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) raise OSError(error_string)
[ "Extracts", "the", "last", "Windows", "error", "message", "into", "a", "python", "unicode", "string" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/_advapi32.py#L72-L94
[ "def", "handle_error", "(", "result", ")", ":", "if", "result", ":", "return", "code", ",", "error_string", "=", "get_error", "(", ")", "if", "code", "==", "Advapi32Const", ".", "NTE_BAD_SIGNATURE", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "if", "not", "isinstance", "(", "error_string", ",", "str_cls", ")", ":", "error_string", "=", "_try_decode", "(", "error_string", ")", "raise", "OSError", "(", "error_string", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
aes_cbc_no_padding_encrypt
Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext)
oscrypto/_osx/symmetric.py
def aes_cbc_no_padding_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) if len(data) % 16 != 0: raise ValueError(pretty_message( ''' data must be a multiple of 16 bytes long - is %s ''', len(data) )) return (iv, _encrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingNoneKey))
def aes_cbc_no_padding_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) if len(data) % 16 != 0: raise ValueError(pretty_message( ''' data must be a multiple of 16 bytes long - is %s ''', len(data) )) return (iv, _encrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingNoneKey))
[ "Encrypts", "plaintext", "using", "AES", "in", "CBC", "mode", "with", "a", "128", "192", "or", "256", "bit", "key", "and", "no", "padding", ".", "This", "means", "the", "ciphertext", "must", "be", "an", "exact", "multiple", "of", "16", "bytes", "long", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L28-L79
[ "def", "aes_cbc_no_padding_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "not", "iv", ":", "iv", "=", "rand_bytes", "(", "16", ")", "elif", "len", "(", "iv", ")", "!=", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 16 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "if", "len", "(", "data", ")", "%", "16", "!=", "0", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n data must be a multiple of 16 bytes long - is %s\n '''", ",", "len", "(", "data", ")", ")", ")", "return", "(", "iv", ",", "_encrypt", "(", "Security", ".", "kSecAttrKeyTypeAES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingNoneKey", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
aes_cbc_no_padding_decrypt
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/symmetric.py
def aes_cbc_no_padding_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingNoneKey)
def aes_cbc_no_padding_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingNoneKey)
[ "Decrypts", "AES", "ciphertext", "in", "CBC", "mode", "using", "a", "128", "192", "or", "256", "bit", "key", "and", "no", "padding", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L82-L121
[ "def", "aes_cbc_no_padding_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "len", "(", "iv", ")", "!=", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 16 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "_decrypt", "(", "Security", ".", "kSecAttrKeyTypeAES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingNoneKey", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
aes_cbc_pkcs7_encrypt
Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and PKCS#7 padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext)
oscrypto/_osx/symmetric.py
def aes_cbc_pkcs7_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and PKCS#7 padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return (iv, _encrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key))
def aes_cbc_pkcs7_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and PKCS#7 padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return (iv, _encrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key))
[ "Encrypts", "plaintext", "using", "AES", "in", "CBC", "mode", "with", "a", "128", "192", "or", "256", "bit", "key", "and", "PKCS#7", "padding", "." ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L124-L166
[ "def", "aes_cbc_pkcs7_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "not", "iv", ":", "iv", "=", "rand_bytes", "(", "16", ")", "elif", "len", "(", "iv", ")", "!=", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 16 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "(", "iv", ",", "_encrypt", "(", "Security", ".", "kSecAttrKeyTypeAES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS7Key", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
aes_cbc_pkcs7_decrypt
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/symmetric.py
def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key)
def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key)
[ "Decrypts", "AES", "ciphertext", "in", "CBC", "mode", "using", "a", "128", "192", "or", "256", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L169-L208
[ "def", "aes_cbc_pkcs7_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either 16, 24 or 32 bytes (128, 192 or 256 bits)\n long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "len", "(", "iv", ")", "!=", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 16 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "_decrypt", "(", "Security", ".", "kSecAttrKeyTypeAES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS7Key", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rc4_encrypt
Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext
oscrypto/_osx/symmetric.py
def rc4_encrypt(key, data): """ Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _encrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None)
def rc4_encrypt(key, data): """ Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _encrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None)
[ "Encrypts", "plaintext", "using", "RC4", "with", "a", "40", "-", "128", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L211-L238
[ "def", "rc4_encrypt", "(", "key", ",", "data", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 bytes (40 to 128 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "return", "_encrypt", "(", "Security", ".", "kSecAttrKeyTypeRC4", ",", "key", ",", "data", ",", "None", ",", "None", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rc4_decrypt
Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/symmetric.py
def rc4_decrypt(key, data): """ Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _decrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None)
def rc4_decrypt(key, data): """ Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _decrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None)
[ "Decrypts", "RC4", "ciphertext", "using", "a", "40", "-", "128", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L241-L268
[ "def", "rc4_decrypt", "(", "key", ",", "data", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 bytes (40 to 128 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "return", "_decrypt", "(", "Security", ".", "kSecAttrKeyTypeRC4", ",", "key", ",", "data", ",", "None", ",", "None", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rc2_cbc_pkcs5_encrypt
Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext)
oscrypto/_osx/symmetric.py
def rc2_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return (iv, _encrypt(Security.kSecAttrKeyTypeRC2, key, data, iv, Security.kSecPaddingPKCS5Key))
def rc2_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return (iv, _encrypt(Security.kSecAttrKeyTypeRC2, key, data, iv, Security.kSecPaddingPKCS5Key))
[ "Encrypts", "plaintext", "using", "RC2", "with", "a", "64", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L271-L312
[ "def", "rc2_cbc_pkcs5_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 bytes (40 to 128 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "not", "iv", ":", "iv", "=", "rand_bytes", "(", "8", ")", "elif", "len", "(", "iv", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 8 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "(", "iv", ",", "_encrypt", "(", "Security", ".", "kSecAttrKeyTypeRC2", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS5Key", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
rc2_cbc_pkcs5_decrypt
Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/symmetric.py
def rc2_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeRC2, key, data, iv, Security.kSecPaddingPKCS5Key)
def rc2_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeRC2, key, data, iv, Security.kSecPaddingPKCS5Key)
[ "Decrypts", "RC2", "ciphertext", "using", "a", "64", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L315-L353
[ "def", "rc2_cbc_pkcs5_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 bytes (40 to 128 bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "len", "(", "iv", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 8 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "_decrypt", "(", "Security", ".", "kSecAttrKeyTypeRC2", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS5Key", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
tripledes_cbc_pkcs5_encrypt
Encrypts plaintext using 3DES in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext)
oscrypto/_osx/symmetric.py
def tripledes_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using 3DES in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - %s ''', len(iv) )) # Expand 2-key to actual 24 byte byte string used by cipher if len(key) == 16: key = key + key[0:8] return (iv, _encrypt(Security.kSecAttrKeyType3DES, key, data, iv, Security.kSecPaddingPKCS5Key))
def tripledes_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using 3DES in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - %s ''', len(iv) )) # Expand 2-key to actual 24 byte byte string used by cipher if len(key) == 16: key = key + key[0:8] return (iv, _encrypt(Security.kSecAttrKeyType3DES, key, data, iv, Security.kSecPaddingPKCS5Key))
[ "Encrypts", "plaintext", "using", "3DES", "in", "either", "2", "or", "3", "key", "mode" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L356-L401
[ "def", "tripledes_cbc_pkcs5_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "!=", "16", "and", "len", "(", "key", ")", "!=", "24", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 16 bytes (2 key) or 24 bytes (3 key) long - %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "not", "iv", ":", "iv", "=", "rand_bytes", "(", "8", ")", "elif", "len", "(", "iv", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 8 bytes long - %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "# Expand 2-key to actual 24 byte byte string used by cipher", "if", "len", "(", "key", ")", "==", "16", ":", "key", "=", "key", "+", "key", "[", "0", ":", "8", "]", "return", "(", "iv", ",", "_encrypt", "(", "Security", ".", "kSecAttrKeyType3DES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS5Key", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
tripledes_cbc_pkcs5_decrypt
Decrypts 3DES ciphertext in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/symmetric.py
def tripledes_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts 3DES ciphertext in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) # Expand 2-key to actual 24 byte byte string used by cipher if len(key) == 16: key = key + key[0:8] return _decrypt(Security.kSecAttrKeyType3DES, key, data, iv, Security.kSecPaddingPKCS5Key)
def tripledes_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts 3DES ciphertext in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) # Expand 2-key to actual 24 byte byte string used by cipher if len(key) == 16: key = key + key[0:8] return _decrypt(Security.kSecAttrKeyType3DES, key, data, iv, Security.kSecPaddingPKCS5Key)
[ "Decrypts", "3DES", "ciphertext", "in", "either", "2", "or", "3", "key", "mode" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L404-L446
[ "def", "tripledes_cbc_pkcs5_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "!=", "16", "and", "len", "(", "key", ")", "!=", "24", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "len", "(", "iv", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 8 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "# Expand 2-key to actual 24 byte byte string used by cipher", "if", "len", "(", "key", ")", "==", "16", ":", "key", "=", "key", "+", "key", "[", "0", ":", "8", "]", "return", "_decrypt", "(", "Security", ".", "kSecAttrKeyType3DES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS5Key", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
des_cbc_pkcs5_encrypt
Encrypts plaintext using DES with a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext)
oscrypto/_osx/symmetric.py
def des_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using DES with a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return (iv, _encrypt(Security.kSecAttrKeyTypeDES, key, data, iv, Security.kSecPaddingPKCS5Key))
def des_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using DES with a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return (iv, _encrypt(Security.kSecAttrKeyTypeDES, key, data, iv, Security.kSecPaddingPKCS5Key))
[ "Encrypts", "plaintext", "using", "DES", "with", "a", "56", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L449-L490
[ "def", "des_cbc_pkcs5_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 8 bytes (56 bits + 8 parity bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "not", "iv", ":", "iv", "=", "rand_bytes", "(", "8", ")", "elif", "len", "(", "iv", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 8 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "(", "iv", ",", "_encrypt", "(", "Security", ".", "kSecAttrKeyTypeDES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS5Key", ")", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
des_cbc_pkcs5_decrypt
Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
oscrypto/_osx/symmetric.py
def des_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeDES, key, data, iv, Security.kSecPaddingPKCS5Key)
def des_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeDES, key, data, iv, Security.kSecPaddingPKCS5Key)
[ "Decrypts", "DES", "ciphertext", "using", "a", "56", "bit", "key" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L493-L531
[ "def", "des_cbc_pkcs5_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 8 bytes (56 bits + 8 parity bits) long - is %s\n '''", ",", "len", "(", "key", ")", ")", ")", "if", "len", "(", "iv", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n iv must be 8 bytes long - is %s\n '''", ",", "len", "(", "iv", ")", ")", ")", "return", "_decrypt", "(", "Security", ".", "kSecAttrKeyTypeDES", ",", "key", ",", "data", ",", "iv", ",", "Security", ".", "kSecPaddingPKCS5Key", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
_encrypt
Encrypts plaintext :param cipher: A kSecAttrKeyType* value that specifies the cipher to use :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: The padding mode to use, specified as a kSecPadding*Key value - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext
oscrypto/_osx/symmetric.py
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A kSecAttrKeyType* value that specifies the cipher to use :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: The padding mode to use, specified as a kSecPadding*Key value - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(key, byte_cls): raise TypeError(pretty_message( ''' key must be a byte string, not %s ''', type_name(key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if cipher != Security.kSecAttrKeyTypeRC4 and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher != Security.kSecAttrKeyTypeRC4 and not padding: raise ValueError('padding must be specified') cf_dict = None cf_key = None cf_data = None cf_iv = None sec_key = None sec_transform = None try: cf_dict = CFHelpers.cf_dictionary_from_pairs([(Security.kSecAttrKeyType, cipher)]) cf_key = CFHelpers.cf_data_from_bytes(key) cf_data = CFHelpers.cf_data_from_bytes(data) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_key = Security.SecKeyCreateFromData(cf_dict, cf_key, error_pointer) handle_cf_error(error_pointer) sec_transform = Security.SecEncryptTransformCreate(sec_key, error_pointer) handle_cf_error(error_pointer) if cipher != Security.kSecAttrKeyTypeRC4: Security.SecTransformSetAttribute(sec_transform, Security.kSecModeCBCKey, null(), error_pointer) handle_cf_error(error_pointer) Security.SecTransformSetAttribute(sec_transform, Security.kSecPaddingKey, padding, error_pointer) handle_cf_error(error_pointer) cf_iv = CFHelpers.cf_data_from_bytes(iv) Security.SecTransformSetAttribute(sec_transform, Security.kSecIVKey, cf_iv, error_pointer) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) ciphertext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(ciphertext) finally: if cf_dict: CoreFoundation.CFRelease(cf_dict) if cf_key: CoreFoundation.CFRelease(cf_key) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_iv: CoreFoundation.CFRelease(cf_iv) if sec_key: CoreFoundation.CFRelease(sec_key) if sec_transform: CoreFoundation.CFRelease(sec_transform)
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A kSecAttrKeyType* value that specifies the cipher to use :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: The padding mode to use, specified as a kSecPadding*Key value - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(key, byte_cls): raise TypeError(pretty_message( ''' key must be a byte string, not %s ''', type_name(key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if cipher != Security.kSecAttrKeyTypeRC4 and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher != Security.kSecAttrKeyTypeRC4 and not padding: raise ValueError('padding must be specified') cf_dict = None cf_key = None cf_data = None cf_iv = None sec_key = None sec_transform = None try: cf_dict = CFHelpers.cf_dictionary_from_pairs([(Security.kSecAttrKeyType, cipher)]) cf_key = CFHelpers.cf_data_from_bytes(key) cf_data = CFHelpers.cf_data_from_bytes(data) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_key = Security.SecKeyCreateFromData(cf_dict, cf_key, error_pointer) handle_cf_error(error_pointer) sec_transform = Security.SecEncryptTransformCreate(sec_key, error_pointer) handle_cf_error(error_pointer) if cipher != Security.kSecAttrKeyTypeRC4: Security.SecTransformSetAttribute(sec_transform, Security.kSecModeCBCKey, null(), error_pointer) handle_cf_error(error_pointer) Security.SecTransformSetAttribute(sec_transform, Security.kSecPaddingKey, padding, error_pointer) handle_cf_error(error_pointer) cf_iv = CFHelpers.cf_data_from_bytes(iv) Security.SecTransformSetAttribute(sec_transform, Security.kSecIVKey, cf_iv, error_pointer) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) ciphertext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(ciphertext) finally: if cf_dict: CoreFoundation.CFRelease(cf_dict) if cf_key: CoreFoundation.CFRelease(cf_key) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_iv: CoreFoundation.CFRelease(cf_iv) if sec_key: CoreFoundation.CFRelease(sec_key) if sec_transform: CoreFoundation.CFRelease(sec_transform)
[ "Encrypts", "plaintext" ]
wbond/oscrypto
python
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L534-L644
[ "def", "_encrypt", "(", "cipher", ",", "key", ",", "data", ",", "iv", ",", "padding", ")", ":", "if", "not", "isinstance", "(", "key", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n key must be a byte string, not %s\n '''", ",", "type_name", "(", "key", ")", ")", ")", "if", "not", "isinstance", "(", "data", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n data must be a byte string, not %s\n '''", ",", "type_name", "(", "data", ")", ")", ")", "if", "cipher", "!=", "Security", ".", "kSecAttrKeyTypeRC4", "and", "not", "isinstance", "(", "iv", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n iv must be a byte string, not %s\n '''", ",", "type_name", "(", "iv", ")", ")", ")", "if", "cipher", "!=", "Security", ".", "kSecAttrKeyTypeRC4", "and", "not", "padding", ":", "raise", "ValueError", "(", "'padding must be specified'", ")", "cf_dict", "=", "None", "cf_key", "=", "None", "cf_data", "=", "None", "cf_iv", "=", "None", "sec_key", "=", "None", "sec_transform", "=", "None", "try", ":", "cf_dict", "=", "CFHelpers", ".", "cf_dictionary_from_pairs", "(", "[", "(", "Security", ".", "kSecAttrKeyType", ",", "cipher", ")", "]", ")", "cf_key", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "key", ")", "cf_data", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "data", ")", "error_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFErrorRef *'", ")", "sec_key", "=", "Security", ".", "SecKeyCreateFromData", "(", "cf_dict", ",", "cf_key", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "sec_transform", "=", "Security", ".", "SecEncryptTransformCreate", "(", "sec_key", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "if", "cipher", "!=", "Security", ".", "kSecAttrKeyTypeRC4", ":", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecModeCBCKey", ",", "null", "(", ")", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecPaddingKey", ",", "padding", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "cf_iv", "=", "CFHelpers", ".", "cf_data_from_bytes", "(", "iv", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecIVKey", ",", "cf_iv", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "Security", ".", "SecTransformSetAttribute", "(", "sec_transform", ",", "Security", ".", "kSecTransformInputAttributeName", ",", "cf_data", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "ciphertext", "=", "Security", ".", "SecTransformExecute", "(", "sec_transform", ",", "error_pointer", ")", "handle_cf_error", "(", "error_pointer", ")", "return", "CFHelpers", ".", "cf_data_to_bytes", "(", "ciphertext", ")", "finally", ":", "if", "cf_dict", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_dict", ")", "if", "cf_key", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_key", ")", "if", "cf_data", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_data", ")", "if", "cf_iv", ":", "CoreFoundation", ".", "CFRelease", "(", "cf_iv", ")", "if", "sec_key", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_key", ")", "if", "sec_transform", ":", "CoreFoundation", ".", "CFRelease", "(", "sec_transform", ")" ]
af778bf1c88bf6c4a7342f5353b130686a5bbe1c
valid
Service.version
Create a new version under this service.
fastly/models.py
def version(self): """ Create a new version under this service. """ ver = Version() ver.conn = self.conn ver.attrs = { # Parent params 'service_id': self.attrs['id'], } ver.save() return ver
def version(self): """ Create a new version under this service. """ ver = Version() ver.conn = self.conn ver.attrs = { # Parent params 'service_id': self.attrs['id'], } ver.save() return ver
[ "Create", "a", "new", "version", "under", "this", "service", "." ]
fastly/fastly-py
python
https://github.com/fastly/fastly-py/blob/f336551c368b3ae44d6b5690913f9e6799d1a83f/fastly/models.py#L85-L97
[ "def", "version", "(", "self", ")", ":", "ver", "=", "Version", "(", ")", "ver", ".", "conn", "=", "self", ".", "conn", "ver", ".", "attrs", "=", "{", "# Parent params", "'service_id'", ":", "self", ".", "attrs", "[", "'id'", "]", ",", "}", "ver", ".", "save", "(", ")", "return", "ver" ]
f336551c368b3ae44d6b5690913f9e6799d1a83f
valid
Version.vcl
Create a new VCL under this version.
fastly/models.py
def vcl(self, name, content): """ Create a new VCL under this version. """ vcl = VCL() vcl.conn = self.conn vcl.attrs = { # Parent params 'service_id': self.attrs['service_id'], 'version': self.attrs['number'], # New instance params 'name': name, 'content': content, } vcl.save() return vcl
def vcl(self, name, content): """ Create a new VCL under this version. """ vcl = VCL() vcl.conn = self.conn vcl.attrs = { # Parent params 'service_id': self.attrs['service_id'], 'version': self.attrs['number'], # New instance params 'name': name, 'content': content, } vcl.save() return vcl
[ "Create", "a", "new", "VCL", "under", "this", "version", "." ]
fastly/fastly-py
python
https://github.com/fastly/fastly-py/blob/f336551c368b3ae44d6b5690913f9e6799d1a83f/fastly/models.py#L135-L152
[ "def", "vcl", "(", "self", ",", "name", ",", "content", ")", ":", "vcl", "=", "VCL", "(", ")", "vcl", ".", "conn", "=", "self", ".", "conn", "vcl", ".", "attrs", "=", "{", "# Parent params", "'service_id'", ":", "self", ".", "attrs", "[", "'service_id'", "]", ",", "'version'", ":", "self", ".", "attrs", "[", "'number'", "]", ",", "# New instance params", "'name'", ":", "name", ",", "'content'", ":", "content", ",", "}", "vcl", ".", "save", "(", ")", "return", "vcl" ]
f336551c368b3ae44d6b5690913f9e6799d1a83f
valid
BaseColumn.to_dict
Converts the column to a dictionary representation accepted by the Citrination server. :return: Dictionary with basic options, plus any column type specific options held under the "options" key :rtype: dict
citrination_client/models/columns/base.py
def to_dict(self): """ Converts the column to a dictionary representation accepted by the Citrination server. :return: Dictionary with basic options, plus any column type specific options held under the "options" key :rtype: dict """ return { "type": self.type, "name": self.name, "group_by_key": self.group_by_key, "role": self.role, "units": self.units, "options": self.build_options() }
def to_dict(self): """ Converts the column to a dictionary representation accepted by the Citrination server. :return: Dictionary with basic options, plus any column type specific options held under the "options" key :rtype: dict """ return { "type": self.type, "name": self.name, "group_by_key": self.group_by_key, "role": self.role, "units": self.units, "options": self.build_options() }
[ "Converts", "the", "column", "to", "a", "dictionary", "representation", "accepted", "by", "the", "Citrination", "server", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/columns/base.py#L33-L49
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"name\"", ":", "self", ".", "name", ",", "\"group_by_key\"", ":", "self", ".", "group_by_key", ",", "\"role\"", ":", "self", ".", "role", ",", "\"units\"", ":", "self", ".", "units", ",", "\"options\"", ":", "self", ".", "build_options", "(", ")", "}" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewBuilder.add_descriptor
Add a descriptor column. :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.) :param role: Specify a role (input, output, latentVariable, or ignore) :param group_by_key: Whether or not to group by this key during cross validation
citrination_client/views/data_view_builder.py
def add_descriptor(self, descriptor, role='ignore', group_by_key=False): """ Add a descriptor column. :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.) :param role: Specify a role (input, output, latentVariable, or ignore) :param group_by_key: Whether or not to group by this key during cross validation """ descriptor.validate() if descriptor.key in self.configuration["roles"]: raise ValueError("Cannot add a descriptor with the same name twice") self.configuration['descriptors'].append(descriptor.as_dict()) self.configuration["roles"][descriptor.key] = role if group_by_key: self.configuration["group_by"].append(descriptor.key)
def add_descriptor(self, descriptor, role='ignore', group_by_key=False): """ Add a descriptor column. :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.) :param role: Specify a role (input, output, latentVariable, or ignore) :param group_by_key: Whether or not to group by this key during cross validation """ descriptor.validate() if descriptor.key in self.configuration["roles"]: raise ValueError("Cannot add a descriptor with the same name twice") self.configuration['descriptors'].append(descriptor.as_dict()) self.configuration["roles"][descriptor.key] = role if group_by_key: self.configuration["group_by"].append(descriptor.key)
[ "Add", "a", "descriptor", "column", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/data_view_builder.py#L33-L51
[ "def", "add_descriptor", "(", "self", ",", "descriptor", ",", "role", "=", "'ignore'", ",", "group_by_key", "=", "False", ")", ":", "descriptor", ".", "validate", "(", ")", "if", "descriptor", ".", "key", "in", "self", ".", "configuration", "[", "\"roles\"", "]", ":", "raise", "ValueError", "(", "\"Cannot add a descriptor with the same name twice\"", ")", "self", ".", "configuration", "[", "'descriptors'", "]", ".", "append", "(", "descriptor", ".", "as_dict", "(", ")", ")", "self", ".", "configuration", "[", "\"roles\"", "]", "[", "descriptor", ".", "key", "]", "=", "role", "if", "group_by_key", ":", "self", ".", "configuration", "[", "\"group_by\"", "]", ".", "append", "(", "descriptor", ".", "key", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
BaseClient._get
Execute a post request and return the result :param headers: :return:
citrination_client/base/base_client.py
def _get(self, route, headers=None, failure_message=None): """ Execute a post request and return the result :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.get(self._get_qualified_route(route), headers=headers, verify=False, proxies=self.proxies) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _get(self, route, headers=None, failure_message=None): """ Execute a post request and return the result :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.get(self._get_qualified_route(route), headers=headers, verify=False, proxies=self.proxies) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
[ "Execute", "a", "post", "request", "and", "return", "the", "result", ":", "param", "headers", ":", ":", "return", ":" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L80-L91
[ "def", "_get", "(", "self", ",", "route", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ".", "get", "(", "self", ".", "_get_qualified_route", "(", "route", ")", ",", "headers", "=", "headers", ",", "verify", "=", "False", ",", "proxies", "=", "self", ".", "proxies", ")", ")", "response", "=", "check_for_rate_limiting", "(", "response_lambda", "(", ")", ",", "response_lambda", ")", "return", "self", ".", "_handle_response", "(", "response", ",", "failure_message", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
BaseClient._post
Execute a post request and return the result :param data: :param headers: :return:
citrination_client/base/base_client.py
def _post(self, route, data, headers=None, failure_message=None): """ Execute a post request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.post( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _post(self, route, data, headers=None, failure_message=None): """ Execute a post request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.post( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
[ "Execute", "a", "post", "request", "and", "return", "the", "result", ":", "param", "data", ":", ":", "param", "headers", ":", ":", "return", ":" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L96-L110
[ "def", "_post", "(", "self", ",", "route", ",", "data", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ".", "post", "(", "self", ".", "_get_qualified_route", "(", "route", ")", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "verify", "=", "False", ",", "proxies", "=", "self", ".", "proxies", ")", ")", "response", "=", "check_for_rate_limiting", "(", "response_lambda", "(", ")", ",", "response_lambda", ")", "return", "self", ".", "_handle_response", "(", "response", ",", "failure_message", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
BaseClient._put
Execute a put request and return the result :param data: :param headers: :return:
citrination_client/base/base_client.py
def _put(self, route, data, headers=None, failure_message=None): """ Execute a put request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.put( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _put(self, route, data, headers=None, failure_message=None): """ Execute a put request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.put( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
[ "Execute", "a", "put", "request", "and", "return", "the", "result", ":", "param", "data", ":", ":", "param", "headers", ":", ":", "return", ":" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L115-L129
[ "def", "_put", "(", "self", ",", "route", ",", "data", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ".", "put", "(", "self", ".", "_get_qualified_route", "(", "route", ")", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "verify", "=", "False", ",", "proxies", "=", "self", ".", "proxies", ")", ")", "response", "=", "check_for_rate_limiting", "(", "response_lambda", "(", ")", ",", "response_lambda", ")", "return", "self", ".", "_handle_response", "(", "response", ",", "failure_message", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
BaseClient._patch
Execute a patch request and return the result
citrination_client/base/base_client.py
def _patch(self, route, data, headers=None, failure_message=None): """ Execute a patch request and return the result """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.patch( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _patch(self, route, data, headers=None, failure_message=None): """ Execute a patch request and return the result """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.patch( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
[ "Execute", "a", "patch", "request", "and", "return", "the", "result" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L134-L145
[ "def", "_patch", "(", "self", ",", "route", ",", "data", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ".", "patch", "(", "self", ".", "_get_qualified_route", "(", "route", ")", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "verify", "=", "False", ",", "proxies", "=", "self", ".", "proxies", ")", ")", "response", "=", "check_for_rate_limiting", "(", "response_lambda", "(", ")", ",", "response_lambda", ")", "return", "self", ".", "_handle_response", "(", "response", ",", "failure_message", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
BaseClient._delete
Execute a delete request and return the result :param headers: :return:
citrination_client/base/base_client.py
def _delete(self, route, headers=None, failure_message=None): """ Execute a delete request and return the result :param headers: :return: """ headers = self._get_headers(headers) response_lambda = (lambda: requests.delete( self._get_qualified_route(route), headers=headers, verify=False, proxies=self.proxies) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _delete(self, route, headers=None, failure_message=None): """ Execute a delete request and return the result :param headers: :return: """ headers = self._get_headers(headers) response_lambda = (lambda: requests.delete( self._get_qualified_route(route), headers=headers, verify=False, proxies=self.proxies) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
[ "Execute", "a", "delete", "request", "and", "return", "the", "result", ":", "param", "headers", ":", ":", "return", ":" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L147-L158
[ "def", "_delete", "(", "self", ",", "route", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ".", "delete", "(", "self", ".", "_get_qualified_route", "(", "route", ")", ",", "headers", "=", "headers", ",", "verify", "=", "False", ",", "proxies", "=", "self", ".", "proxies", ")", ")", "response", "=", "check_for_rate_limiting", "(", "response_lambda", "(", ")", ",", "response_lambda", ")", "return", "self", ".", "_handle_response", "(", "response", ",", "failure_message", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
SearchClient._validate_search_query
Checks to see that the query will not exceed the max query depth :param returning_query: The PIF system or Dataset query to execute. :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery`
citrination_client/search/client.py
def _validate_search_query(self, returning_query): """ Checks to see that the query will not exceed the max query depth :param returning_query: The PIF system or Dataset query to execute. :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery` """ start_index = returning_query.from_index or 0 size = returning_query.size or 0 if start_index < 0: raise CitrinationClientError( "start_index cannot be negative. Please enter a value greater than or equal to zero") if size < 0: raise CitrinationClientError("Size cannot be negative. Please enter a value greater than or equal to zero") if start_index + size > MAX_QUERY_DEPTH: raise CitrinationClientError( "Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}".format( MAX_QUERY_DEPTH))
def _validate_search_query(self, returning_query): """ Checks to see that the query will not exceed the max query depth :param returning_query: The PIF system or Dataset query to execute. :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery` """ start_index = returning_query.from_index or 0 size = returning_query.size or 0 if start_index < 0: raise CitrinationClientError( "start_index cannot be negative. Please enter a value greater than or equal to zero") if size < 0: raise CitrinationClientError("Size cannot be negative. Please enter a value greater than or equal to zero") if start_index + size > MAX_QUERY_DEPTH: raise CitrinationClientError( "Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}".format( MAX_QUERY_DEPTH))
[ "Checks", "to", "see", "that", "the", "query", "will", "not", "exceed", "the", "max", "query", "depth" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L35-L54
[ "def", "_validate_search_query", "(", "self", ",", "returning_query", ")", ":", "start_index", "=", "returning_query", ".", "from_index", "or", "0", "size", "=", "returning_query", ".", "size", "or", "0", "if", "start_index", "<", "0", ":", "raise", "CitrinationClientError", "(", "\"start_index cannot be negative. Please enter a value greater than or equal to zero\"", ")", "if", "size", "<", "0", ":", "raise", "CitrinationClientError", "(", "\"Size cannot be negative. Please enter a value greater than or equal to zero\"", ")", "if", "start_index", "+", "size", ">", "MAX_QUERY_DEPTH", ":", "raise", "CitrinationClientError", "(", "\"Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}\"", ".", "format", "(", "MAX_QUERY_DEPTH", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
SearchClient.pif_search
Run a PIF query against Citrination. :param pif_system_returning_query: The PIF system query to execute. :type pif_system_returning_query: :class:`PifSystemReturningQuery` :return: :class:`PifSearchResult` object with the results of the query. :rtype: :class:`PifSearchResult`
citrination_client/search/client.py
def pif_search(self, pif_system_returning_query): """ Run a PIF query against Citrination. :param pif_system_returning_query: The PIF system query to execute. :type pif_system_returning_query: :class:`PifSystemReturningQuery` :return: :class:`PifSearchResult` object with the results of the query. :rtype: :class:`PifSearchResult` """ self._validate_search_query(pif_system_returning_query) return self._execute_search_query( pif_system_returning_query, PifSearchResult )
def pif_search(self, pif_system_returning_query): """ Run a PIF query against Citrination. :param pif_system_returning_query: The PIF system query to execute. :type pif_system_returning_query: :class:`PifSystemReturningQuery` :return: :class:`PifSearchResult` object with the results of the query. :rtype: :class:`PifSearchResult` """ self._validate_search_query(pif_system_returning_query) return self._execute_search_query( pif_system_returning_query, PifSearchResult )
[ "Run", "a", "PIF", "query", "against", "Citrination", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L56-L70
[ "def", "pif_search", "(", "self", ",", "pif_system_returning_query", ")", ":", "self", ".", "_validate_search_query", "(", "pif_system_returning_query", ")", "return", "self", ".", "_execute_search_query", "(", "pif_system_returning_query", ",", "PifSearchResult", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
SearchClient.dataset_search
Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the results of the query. :rtype: :class:`DatasetSearchResult`
citrination_client/search/client.py
def dataset_search(self, dataset_returning_query): """ Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the results of the query. :rtype: :class:`DatasetSearchResult` """ self._validate_search_query(dataset_returning_query) return self._execute_search_query( dataset_returning_query, DatasetSearchResult )
def dataset_search(self, dataset_returning_query): """ Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the results of the query. :rtype: :class:`DatasetSearchResult` """ self._validate_search_query(dataset_returning_query) return self._execute_search_query( dataset_returning_query, DatasetSearchResult )
[ "Run", "a", "dataset", "query", "against", "Citrination", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L72-L86
[ "def", "dataset_search", "(", "self", ",", "dataset_returning_query", ")", ":", "self", ".", "_validate_search_query", "(", "dataset_returning_query", ")", "return", "self", ".", "_execute_search_query", "(", "dataset_returning_query", ",", "DatasetSearchResult", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
SearchClient._execute_search_query
Run a PIF query against Citrination. :param returning_query: :class:`BaseReturningQuery` to execute. :param result_class: The class of the result to return. :return: ``result_class`` object with the results of the query.
citrination_client/search/client.py
def _execute_search_query(self, returning_query, result_class): """ Run a PIF query against Citrination. :param returning_query: :class:`BaseReturningQuery` to execute. :param result_class: The class of the result to return. :return: ``result_class`` object with the results of the query. """ if returning_query.from_index: from_index = returning_query.from_index else: from_index = 0 if returning_query.size != None: size = min(returning_query.size, client_config.max_query_size) else: size = client_config.max_query_size if (size == client_config.max_query_size and size != returning_query.size): self._warn("Query size greater than max system size - only {} results will be returned".format(size)) time = 0.0; hits = []; while True: sub_query = deepcopy(returning_query) sub_query.from_index = from_index + len(hits) partial_results = self._search_internal(sub_query, result_class) total = partial_results.total_num_hits time += partial_results.took if partial_results.hits is not None: hits.extend(partial_results.hits) if len(hits) >= size or len(hits) >= total or sub_query.from_index >= total: break return result_class(hits=hits, total_num_hits=total, took=time)
def _execute_search_query(self, returning_query, result_class): """ Run a PIF query against Citrination. :param returning_query: :class:`BaseReturningQuery` to execute. :param result_class: The class of the result to return. :return: ``result_class`` object with the results of the query. """ if returning_query.from_index: from_index = returning_query.from_index else: from_index = 0 if returning_query.size != None: size = min(returning_query.size, client_config.max_query_size) else: size = client_config.max_query_size if (size == client_config.max_query_size and size != returning_query.size): self._warn("Query size greater than max system size - only {} results will be returned".format(size)) time = 0.0; hits = []; while True: sub_query = deepcopy(returning_query) sub_query.from_index = from_index + len(hits) partial_results = self._search_internal(sub_query, result_class) total = partial_results.total_num_hits time += partial_results.took if partial_results.hits is not None: hits.extend(partial_results.hits) if len(hits) >= size or len(hits) >= total or sub_query.from_index >= total: break return result_class(hits=hits, total_num_hits=total, took=time)
[ "Run", "a", "PIF", "query", "against", "Citrination", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L88-L123
[ "def", "_execute_search_query", "(", "self", ",", "returning_query", ",", "result_class", ")", ":", "if", "returning_query", ".", "from_index", ":", "from_index", "=", "returning_query", ".", "from_index", "else", ":", "from_index", "=", "0", "if", "returning_query", ".", "size", "!=", "None", ":", "size", "=", "min", "(", "returning_query", ".", "size", ",", "client_config", ".", "max_query_size", ")", "else", ":", "size", "=", "client_config", ".", "max_query_size", "if", "(", "size", "==", "client_config", ".", "max_query_size", "and", "size", "!=", "returning_query", ".", "size", ")", ":", "self", ".", "_warn", "(", "\"Query size greater than max system size - only {} results will be returned\"", ".", "format", "(", "size", ")", ")", "time", "=", "0.0", "hits", "=", "[", "]", "while", "True", ":", "sub_query", "=", "deepcopy", "(", "returning_query", ")", "sub_query", ".", "from_index", "=", "from_index", "+", "len", "(", "hits", ")", "partial_results", "=", "self", ".", "_search_internal", "(", "sub_query", ",", "result_class", ")", "total", "=", "partial_results", ".", "total_num_hits", "time", "+=", "partial_results", ".", "took", "if", "partial_results", ".", "hits", "is", "not", "None", ":", "hits", ".", "extend", "(", "partial_results", ".", "hits", ")", "if", "len", "(", "hits", ")", ">=", "size", "or", "len", "(", "hits", ")", ">=", "total", "or", "sub_query", ".", "from_index", ">=", "total", ":", "break", "return", "result_class", "(", "hits", "=", "hits", ",", "total_num_hits", "=", "total", ",", "took", "=", "time", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
SearchClient.pif_multi_search
Run each in a list of PIF queries against Citrination. :param multi_query: :class:`MultiQuery` object to execute. :return: :class:`PifMultiSearchResult` object with the results of the query.
citrination_client/search/client.py
def pif_multi_search(self, multi_query): """ Run each in a list of PIF queries against Citrination. :param multi_query: :class:`MultiQuery` object to execute. :return: :class:`PifMultiSearchResult` object with the results of the query. """ failure_message = "Error while making PIF multi search request" response_dict = self._get_success_json( self._post(routes.pif_multi_search, data=json.dumps(multi_query, cls=QueryEncoder), failure_message=failure_message)) return PifMultiSearchResult(**keys_to_snake_case(response_dict['results']))
def pif_multi_search(self, multi_query): """ Run each in a list of PIF queries against Citrination. :param multi_query: :class:`MultiQuery` object to execute. :return: :class:`PifMultiSearchResult` object with the results of the query. """ failure_message = "Error while making PIF multi search request" response_dict = self._get_success_json( self._post(routes.pif_multi_search, data=json.dumps(multi_query, cls=QueryEncoder), failure_message=failure_message)) return PifMultiSearchResult(**keys_to_snake_case(response_dict['results']))
[ "Run", "each", "in", "a", "list", "of", "PIF", "queries", "against", "Citrination", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L140-L152
[ "def", "pif_multi_search", "(", "self", ",", "multi_query", ")", ":", "failure_message", "=", "\"Error while making PIF multi search request\"", "response_dict", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post", "(", "routes", ".", "pif_multi_search", ",", "data", "=", "json", ".", "dumps", "(", "multi_query", ",", "cls", "=", "QueryEncoder", ")", ",", "failure_message", "=", "failure_message", ")", ")", "return", "PifMultiSearchResult", "(", "*", "*", "keys_to_snake_case", "(", "response_dict", "[", "'results'", "]", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
SearchClient.generate_simple_chemical_query
This method generates a :class:`PifSystemReturningQuery` object using the supplied arguments. All arguments that accept lists have logical OR's on the queries that they generate. This means that, for example, simple_chemical_search(name=['A', 'B']) will match records that have name equal to 'A' or 'B'. Results will be pulled into the extracted field of the :class:`PifSearchHit` objects that are returned. The name will appear under the key "name", chemical formula under "chemical_formula", property name under "property_name", value of the property under "property_value", units of the property under "property_units", and reference DOI under "reference_doi". This method is only meant for execution of very simple queries. More complex queries must use the search method that accepts a :class:`PifSystemReturningQuery` object. :param name: One or more strings with the names of the chemical system to match. :type name: str or list of str :param chemical_formula: One or more strings with the chemical formulas to match. :type chemical_formula: str or list of str :param property_name: One or more strings with the names of the property to match. :type property_name: str or list of str :param property_value: One or more strings or numbers with the exact values to match. :type property_value: str or int or float or list of str or int or float :param property_min: A single string or number with the minimum value to match. :type property_min: str or int or float :param property_max: A single string or number with the maximum value to match. :type property_max: str or int or float :param property_units: One or more strings with the property units to match. :type property_units: str or list of str :param reference_doi: One or more strings with the DOI to match. :type reference_doin: str or list of str :param include_datasets: One or more integers with dataset IDs to match. :type include_datasets: int or list of int :param exclude_datasets: One or more integers with dataset IDs that must not match. :type exclude_datasets: int or list of int :param from_index: Index of the first record to match. :type from_index: int :param size: Total number of records to return. :type size: int :return: A query to to be submitted with the pif_search method :rtype: :class:`PifSystemReturningQuery`
citrination_client/search/client.py
def generate_simple_chemical_query(self, name=None, chemical_formula=None, property_name=None, property_value=None, property_min=None, property_max=None, property_units=None, reference_doi=None, include_datasets=[], exclude_datasets=[], from_index=None, size=None): """ This method generates a :class:`PifSystemReturningQuery` object using the supplied arguments. All arguments that accept lists have logical OR's on the queries that they generate. This means that, for example, simple_chemical_search(name=['A', 'B']) will match records that have name equal to 'A' or 'B'. Results will be pulled into the extracted field of the :class:`PifSearchHit` objects that are returned. The name will appear under the key "name", chemical formula under "chemical_formula", property name under "property_name", value of the property under "property_value", units of the property under "property_units", and reference DOI under "reference_doi". This method is only meant for execution of very simple queries. More complex queries must use the search method that accepts a :class:`PifSystemReturningQuery` object. :param name: One or more strings with the names of the chemical system to match. :type name: str or list of str :param chemical_formula: One or more strings with the chemical formulas to match. :type chemical_formula: str or list of str :param property_name: One or more strings with the names of the property to match. :type property_name: str or list of str :param property_value: One or more strings or numbers with the exact values to match. :type property_value: str or int or float or list of str or int or float :param property_min: A single string or number with the minimum value to match. :type property_min: str or int or float :param property_max: A single string or number with the maximum value to match. :type property_max: str or int or float :param property_units: One or more strings with the property units to match. :type property_units: str or list of str :param reference_doi: One or more strings with the DOI to match. :type reference_doin: str or list of str :param include_datasets: One or more integers with dataset IDs to match. :type include_datasets: int or list of int :param exclude_datasets: One or more integers with dataset IDs that must not match. :type exclude_datasets: int or list of int :param from_index: Index of the first record to match. :type from_index: int :param size: Total number of records to return. :type size: int :return: A query to to be submitted with the pif_search method :rtype: :class:`PifSystemReturningQuery` """ pif_system_query = PifSystemQuery() pif_system_query.names = FieldQuery( extract_as='name', filter=[Filter(equal=i) for i in self._get_list(name)]) pif_system_query.chemical_formula = ChemicalFieldQuery( extract_as='chemical_formula', filter=[ChemicalFilter(equal=i) for i in self._get_list(chemical_formula)]) pif_system_query.references = ReferenceQuery(doi=FieldQuery( extract_as='reference_doi', filter=[Filter(equal=i) for i in self._get_list(reference_doi)])) # Generate the parts of the property query property_name_query = FieldQuery( extract_as='property_name', filter=[Filter(equal=i) for i in self._get_list(property_name)]) property_units_query = FieldQuery( extract_as='property_units', filter=[Filter(equal=i) for i in self._get_list(property_units)]) property_value_query = FieldQuery( extract_as='property_value', filter=[]) for i in self._get_list(property_value): property_value_query.filter.append(Filter(equal=i)) if property_min is not None or property_max is not None: property_value_query.filter.append(Filter(min=property_min, max=property_max)) # Generate the full property query pif_system_query.properties = PropertyQuery( name=property_name_query, value=property_value_query, units=property_units_query) # Generate the dataset query dataset_query = list() if include_datasets: dataset_query.append(DatasetQuery(logic='MUST', id=[Filter(equal=i) for i in include_datasets])) if exclude_datasets: dataset_query.append(DatasetQuery(logic='MUST_NOT', id=[Filter(equal=i) for i in exclude_datasets])) # Run the query pif_system_returning_query = PifSystemReturningQuery( query=DataQuery( system=pif_system_query, dataset=dataset_query), from_index=from_index, size=size, score_relevance=True) return pif_system_returning_query
def generate_simple_chemical_query(self, name=None, chemical_formula=None, property_name=None, property_value=None, property_min=None, property_max=None, property_units=None, reference_doi=None, include_datasets=[], exclude_datasets=[], from_index=None, size=None): """ This method generates a :class:`PifSystemReturningQuery` object using the supplied arguments. All arguments that accept lists have logical OR's on the queries that they generate. This means that, for example, simple_chemical_search(name=['A', 'B']) will match records that have name equal to 'A' or 'B'. Results will be pulled into the extracted field of the :class:`PifSearchHit` objects that are returned. The name will appear under the key "name", chemical formula under "chemical_formula", property name under "property_name", value of the property under "property_value", units of the property under "property_units", and reference DOI under "reference_doi". This method is only meant for execution of very simple queries. More complex queries must use the search method that accepts a :class:`PifSystemReturningQuery` object. :param name: One or more strings with the names of the chemical system to match. :type name: str or list of str :param chemical_formula: One or more strings with the chemical formulas to match. :type chemical_formula: str or list of str :param property_name: One or more strings with the names of the property to match. :type property_name: str or list of str :param property_value: One or more strings or numbers with the exact values to match. :type property_value: str or int or float or list of str or int or float :param property_min: A single string or number with the minimum value to match. :type property_min: str or int or float :param property_max: A single string or number with the maximum value to match. :type property_max: str or int or float :param property_units: One or more strings with the property units to match. :type property_units: str or list of str :param reference_doi: One or more strings with the DOI to match. :type reference_doin: str or list of str :param include_datasets: One or more integers with dataset IDs to match. :type include_datasets: int or list of int :param exclude_datasets: One or more integers with dataset IDs that must not match. :type exclude_datasets: int or list of int :param from_index: Index of the first record to match. :type from_index: int :param size: Total number of records to return. :type size: int :return: A query to to be submitted with the pif_search method :rtype: :class:`PifSystemReturningQuery` """ pif_system_query = PifSystemQuery() pif_system_query.names = FieldQuery( extract_as='name', filter=[Filter(equal=i) for i in self._get_list(name)]) pif_system_query.chemical_formula = ChemicalFieldQuery( extract_as='chemical_formula', filter=[ChemicalFilter(equal=i) for i in self._get_list(chemical_formula)]) pif_system_query.references = ReferenceQuery(doi=FieldQuery( extract_as='reference_doi', filter=[Filter(equal=i) for i in self._get_list(reference_doi)])) # Generate the parts of the property query property_name_query = FieldQuery( extract_as='property_name', filter=[Filter(equal=i) for i in self._get_list(property_name)]) property_units_query = FieldQuery( extract_as='property_units', filter=[Filter(equal=i) for i in self._get_list(property_units)]) property_value_query = FieldQuery( extract_as='property_value', filter=[]) for i in self._get_list(property_value): property_value_query.filter.append(Filter(equal=i)) if property_min is not None or property_max is not None: property_value_query.filter.append(Filter(min=property_min, max=property_max)) # Generate the full property query pif_system_query.properties = PropertyQuery( name=property_name_query, value=property_value_query, units=property_units_query) # Generate the dataset query dataset_query = list() if include_datasets: dataset_query.append(DatasetQuery(logic='MUST', id=[Filter(equal=i) for i in include_datasets])) if exclude_datasets: dataset_query.append(DatasetQuery(logic='MUST_NOT', id=[Filter(equal=i) for i in exclude_datasets])) # Run the query pif_system_returning_query = PifSystemReturningQuery( query=DataQuery( system=pif_system_query, dataset=dataset_query), from_index=from_index, size=size, score_relevance=True) return pif_system_returning_query
[ "This", "method", "generates", "a", ":", "class", ":", "PifSystemReturningQuery", "object", "using", "the", "supplied", "arguments", ".", "All", "arguments", "that", "accept", "lists", "have", "logical", "OR", "s", "on", "the", "queries", "that", "they", "generate", ".", "This", "means", "that", "for", "example", "simple_chemical_search", "(", "name", "=", "[", "A", "B", "]", ")", "will", "match", "records", "that", "have", "name", "equal", "to", "A", "or", "B", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L154-L246
[ "def", "generate_simple_chemical_query", "(", "self", ",", "name", "=", "None", ",", "chemical_formula", "=", "None", ",", "property_name", "=", "None", ",", "property_value", "=", "None", ",", "property_min", "=", "None", ",", "property_max", "=", "None", ",", "property_units", "=", "None", ",", "reference_doi", "=", "None", ",", "include_datasets", "=", "[", "]", ",", "exclude_datasets", "=", "[", "]", ",", "from_index", "=", "None", ",", "size", "=", "None", ")", ":", "pif_system_query", "=", "PifSystemQuery", "(", ")", "pif_system_query", ".", "names", "=", "FieldQuery", "(", "extract_as", "=", "'name'", ",", "filter", "=", "[", "Filter", "(", "equal", "=", "i", ")", "for", "i", "in", "self", ".", "_get_list", "(", "name", ")", "]", ")", "pif_system_query", ".", "chemical_formula", "=", "ChemicalFieldQuery", "(", "extract_as", "=", "'chemical_formula'", ",", "filter", "=", "[", "ChemicalFilter", "(", "equal", "=", "i", ")", "for", "i", "in", "self", ".", "_get_list", "(", "chemical_formula", ")", "]", ")", "pif_system_query", ".", "references", "=", "ReferenceQuery", "(", "doi", "=", "FieldQuery", "(", "extract_as", "=", "'reference_doi'", ",", "filter", "=", "[", "Filter", "(", "equal", "=", "i", ")", "for", "i", "in", "self", ".", "_get_list", "(", "reference_doi", ")", "]", ")", ")", "# Generate the parts of the property query", "property_name_query", "=", "FieldQuery", "(", "extract_as", "=", "'property_name'", ",", "filter", "=", "[", "Filter", "(", "equal", "=", "i", ")", "for", "i", "in", "self", ".", "_get_list", "(", "property_name", ")", "]", ")", "property_units_query", "=", "FieldQuery", "(", "extract_as", "=", "'property_units'", ",", "filter", "=", "[", "Filter", "(", "equal", "=", "i", ")", "for", "i", "in", "self", ".", "_get_list", "(", "property_units", ")", "]", ")", "property_value_query", "=", "FieldQuery", "(", "extract_as", "=", "'property_value'", ",", "filter", "=", "[", "]", ")", "for", "i", "in", "self", ".", "_get_list", "(", "property_value", ")", ":", "property_value_query", ".", "filter", ".", "append", "(", "Filter", "(", "equal", "=", "i", ")", ")", "if", "property_min", "is", "not", "None", "or", "property_max", "is", "not", "None", ":", "property_value_query", ".", "filter", ".", "append", "(", "Filter", "(", "min", "=", "property_min", ",", "max", "=", "property_max", ")", ")", "# Generate the full property query", "pif_system_query", ".", "properties", "=", "PropertyQuery", "(", "name", "=", "property_name_query", ",", "value", "=", "property_value_query", ",", "units", "=", "property_units_query", ")", "# Generate the dataset query", "dataset_query", "=", "list", "(", ")", "if", "include_datasets", ":", "dataset_query", ".", "append", "(", "DatasetQuery", "(", "logic", "=", "'MUST'", ",", "id", "=", "[", "Filter", "(", "equal", "=", "i", ")", "for", "i", "in", "include_datasets", "]", ")", ")", "if", "exclude_datasets", ":", "dataset_query", ".", "append", "(", "DatasetQuery", "(", "logic", "=", "'MUST_NOT'", ",", "id", "=", "[", "Filter", "(", "equal", "=", "i", ")", "for", "i", "in", "exclude_datasets", "]", ")", ")", "# Run the query", "pif_system_returning_query", "=", "PifSystemReturningQuery", "(", "query", "=", "DataQuery", "(", "system", "=", "pif_system_query", ",", "dataset", "=", "dataset_query", ")", ",", "from_index", "=", "from_index", ",", "size", "=", "size", ",", "score_relevance", "=", "True", ")", "return", "pif_system_returning_query" ]
409984fc65ce101a620f069263f155303492465c
valid
check_for_rate_limiting
Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered. If more than 3 attempts are made, a RateLimitingException is raised :param response: A response from Citrination :type response: requests.Response :param response_lambda: a callable that runs the request that returned the response :type response_lambda: function :param timeout: the time to wait before retrying :type timeout: int :param attempts: the number of the retry being executed :type attempts: int
citrination_client/base/response_handling.py
def check_for_rate_limiting(response, response_lambda, timeout=1, attempts=0): """ Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered. If more than 3 attempts are made, a RateLimitingException is raised :param response: A response from Citrination :type response: requests.Response :param response_lambda: a callable that runs the request that returned the response :type response_lambda: function :param timeout: the time to wait before retrying :type timeout: int :param attempts: the number of the retry being executed :type attempts: int """ if attempts >= 3: raise RateLimitingException() if response.status_code == 429: sleep(timeout) new_timeout = timeout + 1 new_attempts = attempts + 1 return check_for_rate_limiting(response_lambda(timeout, attempts), response_lambda, timeout=new_timeout, attempts=new_attempts) return response
def check_for_rate_limiting(response, response_lambda, timeout=1, attempts=0): """ Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered. If more than 3 attempts are made, a RateLimitingException is raised :param response: A response from Citrination :type response: requests.Response :param response_lambda: a callable that runs the request that returned the response :type response_lambda: function :param timeout: the time to wait before retrying :type timeout: int :param attempts: the number of the retry being executed :type attempts: int """ if attempts >= 3: raise RateLimitingException() if response.status_code == 429: sleep(timeout) new_timeout = timeout + 1 new_attempts = attempts + 1 return check_for_rate_limiting(response_lambda(timeout, attempts), response_lambda, timeout=new_timeout, attempts=new_attempts) return response
[ "Takes", "an", "initial", "response", "and", "a", "way", "to", "repeat", "the", "request", "that", "produced", "it", "and", "retries", "the", "request", "with", "an", "increasing", "sleep", "period", "between", "requests", "if", "rate", "limiting", "resposne", "codes", "are", "encountered", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/response_handling.py#L4-L27
[ "def", "check_for_rate_limiting", "(", "response", ",", "response_lambda", ",", "timeout", "=", "1", ",", "attempts", "=", "0", ")", ":", "if", "attempts", ">=", "3", ":", "raise", "RateLimitingException", "(", ")", "if", "response", ".", "status_code", "==", "429", ":", "sleep", "(", "timeout", ")", "new_timeout", "=", "timeout", "+", "1", "new_attempts", "=", "attempts", "+", "1", "return", "check_for_rate_limiting", "(", "response_lambda", "(", "timeout", ",", "attempts", ")", ",", "response_lambda", ",", "timeout", "=", "new_timeout", ",", "attempts", "=", "new_attempts", ")", "return", "response" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.create
Creates a data view from the search template and ml template given :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view :return: The data view id
citrination_client/views/client.py
def create(self, configuration, name, description): """ Creates a data view from the search template and ml template given :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view :return: The data view id """ data = { "configuration": configuration, "name": name, "description": description } failure_message = "Dataview creation failed" result = self._get_success_json(self._post_json( 'v1/data_views', data, failure_message=failure_message)) data_view_id = result['data']['id'] return data_view_id
def create(self, configuration, name, description): """ Creates a data view from the search template and ml template given :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view :return: The data view id """ data = { "configuration": configuration, "name": name, "description": description } failure_message = "Dataview creation failed" result = self._get_success_json(self._post_json( 'v1/data_views', data, failure_message=failure_message)) data_view_id = result['data']['id'] return data_view_id
[ "Creates", "a", "data", "view", "from", "the", "search", "template", "and", "ml", "template", "given" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L24-L49
[ "def", "create", "(", "self", ",", "configuration", ",", "name", ",", "description", ")", ":", "data", "=", "{", "\"configuration\"", ":", "configuration", ",", "\"name\"", ":", "name", ",", "\"description\"", ":", "description", "}", "failure_message", "=", "\"Dataview creation failed\"", "result", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/data_views'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "data_view_id", "=", "result", "[", "'data'", "]", "[", "'id'", "]", "return", "data_view_id" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.update
Updates an existing data view from the search template and ml template given :param id: Identifier for the data view. This returned from the create method. :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view
citrination_client/views/client.py
def update(self, id, configuration, name, description): """ Updates an existing data view from the search template and ml template given :param id: Identifier for the data view. This returned from the create method. :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view """ data = { "configuration": configuration, "name": name, "description": description } failure_message = "Dataview creation failed" self._patch_json( 'v1/data_views/' + id, data, failure_message=failure_message)
def update(self, id, configuration, name, description): """ Updates an existing data view from the search template and ml template given :param id: Identifier for the data view. This returned from the create method. :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view """ data = { "configuration": configuration, "name": name, "description": description } failure_message = "Dataview creation failed" self._patch_json( 'v1/data_views/' + id, data, failure_message=failure_message)
[ "Updates", "an", "existing", "data", "view", "from", "the", "search", "template", "and", "ml", "template", "given" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L51-L73
[ "def", "update", "(", "self", ",", "id", ",", "configuration", ",", "name", ",", "description", ")", ":", "data", "=", "{", "\"configuration\"", ":", "configuration", ",", "\"name\"", ":", "name", ",", "\"description\"", ":", "description", "}", "failure_message", "=", "\"Dataview creation failed\"", "self", ".", "_patch_json", "(", "'v1/data_views/'", "+", "id", ",", "data", ",", "failure_message", "=", "failure_message", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.get
Gets basic information about a view :param data_view_id: Identifier of the data view :return: Metadata about the view as JSON
citrination_client/views/client.py
def get(self, data_view_id): """ Gets basic information about a view :param data_view_id: Identifier of the data view :return: Metadata about the view as JSON """ failure_message = "Dataview get failed" return self._get_success_json(self._get( 'v1/data_views/' + data_view_id, None, failure_message=failure_message))['data']['data_view']
def get(self, data_view_id): """ Gets basic information about a view :param data_view_id: Identifier of the data view :return: Metadata about the view as JSON """ failure_message = "Dataview get failed" return self._get_success_json(self._get( 'v1/data_views/' + data_view_id, None, failure_message=failure_message))['data']['data_view']
[ "Gets", "basic", "information", "about", "a", "view" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L86-L96
[ "def", "get", "(", "self", ",", "data_view_id", ")", ":", "failure_message", "=", "\"Dataview get failed\"", "return", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "'v1/data_views/'", "+", "data_view_id", ",", "None", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "[", "'data_view'", "]" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.get_data_view_service_status
Retrieves the status for all of the services associated with a data view: - predict - experimental_design - data_reports - model_reports :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :return: A :class:`DataViewStatus` :rtype: DataViewStatus
citrination_client/views/client.py
def get_data_view_service_status(self, data_view_id): """ Retrieves the status for all of the services associated with a data view: - predict - experimental_design - data_reports - model_reports :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :return: A :class:`DataViewStatus` :rtype: DataViewStatus """ url = "data_views/{}/status".format(data_view_id) response = self._get(url).json() result = response["data"]["status"] return DataViewStatus( predict=ServiceStatus.from_response_dict(result["predict"]), experimental_design=ServiceStatus.from_response_dict(result["experimental_design"]), data_reports=ServiceStatus.from_response_dict(result["data_reports"]), model_reports=ServiceStatus.from_response_dict(result["model_reports"]) )
def get_data_view_service_status(self, data_view_id): """ Retrieves the status for all of the services associated with a data view: - predict - experimental_design - data_reports - model_reports :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :return: A :class:`DataViewStatus` :rtype: DataViewStatus """ url = "data_views/{}/status".format(data_view_id) response = self._get(url).json() result = response["data"]["status"] return DataViewStatus( predict=ServiceStatus.from_response_dict(result["predict"]), experimental_design=ServiceStatus.from_response_dict(result["experimental_design"]), data_reports=ServiceStatus.from_response_dict(result["data_reports"]), model_reports=ServiceStatus.from_response_dict(result["model_reports"]) )
[ "Retrieves", "the", "status", "for", "all", "of", "the", "services", "associated", "with", "a", "data", "view", ":", "-", "predict", "-", "experimental_design", "-", "data_reports", "-", "model_reports" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L98-L123
[ "def", "get_data_view_service_status", "(", "self", ",", "data_view_id", ")", ":", "url", "=", "\"data_views/{}/status\"", ".", "format", "(", "data_view_id", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "result", "=", "response", "[", "\"data\"", "]", "[", "\"status\"", "]", "return", "DataViewStatus", "(", "predict", "=", "ServiceStatus", ".", "from_response_dict", "(", "result", "[", "\"predict\"", "]", ")", ",", "experimental_design", "=", "ServiceStatus", ".", "from_response_dict", "(", "result", "[", "\"experimental_design\"", "]", ")", ",", "data_reports", "=", "ServiceStatus", ".", "from_response_dict", "(", "result", "[", "\"data_reports\"", "]", ")", ",", "model_reports", "=", "ServiceStatus", ".", "from_response_dict", "(", "result", "[", "\"model_reports\"", "]", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.create_ml_configuration_from_datasets
Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status)
citrination_client/views/client.py
def create_ml_configuration_from_datasets(self, dataset_ids): """ Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status) """ available_columns = self.search_template_client.get_available_columns(dataset_ids) # Create a search template from dataset ids search_template = self.search_template_client.create(dataset_ids, available_columns) return self.create_ml_configuration(search_template, available_columns, dataset_ids)
def create_ml_configuration_from_datasets(self, dataset_ids): """ Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status) """ available_columns = self.search_template_client.get_available_columns(dataset_ids) # Create a search template from dataset ids search_template = self.search_template_client.create(dataset_ids, available_columns) return self.create_ml_configuration(search_template, available_columns, dataset_ids)
[ "Creates", "an", "ml", "configuration", "from", "dataset_ids", "and", "extract_as_keys" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L125-L136
[ "def", "create_ml_configuration_from_datasets", "(", "self", ",", "dataset_ids", ")", ":", "available_columns", "=", "self", ".", "search_template_client", ".", "get_available_columns", "(", "dataset_ids", ")", "# Create a search template from dataset ids", "search_template", "=", "self", ".", "search_template_client", ".", "create", "(", "dataset_ids", ",", "available_columns", ")", "return", "self", ".", "create_ml_configuration", "(", "search_template", ",", "available_columns", ",", "dataset_ids", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.create_ml_configuration
This method will spawn a server job to create a default ML configuration based on a search template and the extract as keys. This function will submit the request to build, and wait for the configuration to finish before returning. :param search_template: A search template defining the query (properties, datasets etc) :param extract_as_keys: Array of extract-as keys defining the descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status)
citrination_client/views/client.py
def create_ml_configuration(self, search_template, extract_as_keys, dataset_ids): """ This method will spawn a server job to create a default ML configuration based on a search template and the extract as keys. This function will submit the request to build, and wait for the configuration to finish before returning. :param search_template: A search template defining the query (properties, datasets etc) :param extract_as_keys: Array of extract-as keys defining the descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status) """ data = { "search_template": search_template, "extract_as_keys": extract_as_keys } failure_message = "ML Configuration creation failed" config_job_id = self._get_success_json(self._post_json( 'v1/descriptors/builders/simple/default/trigger', data, failure_message=failure_message))['data'][ 'result']['uid'] while True: config_status = self.__get_ml_configuration_status(config_job_id) print('Configuration status: ', config_status) if config_status['status'] == 'Finished': ml_config = self.__convert_response_to_configuration(config_status['result'], dataset_ids) return ml_config time.sleep(5)
def create_ml_configuration(self, search_template, extract_as_keys, dataset_ids): """ This method will spawn a server job to create a default ML configuration based on a search template and the extract as keys. This function will submit the request to build, and wait for the configuration to finish before returning. :param search_template: A search template defining the query (properties, datasets etc) :param extract_as_keys: Array of extract-as keys defining the descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status) """ data = { "search_template": search_template, "extract_as_keys": extract_as_keys } failure_message = "ML Configuration creation failed" config_job_id = self._get_success_json(self._post_json( 'v1/descriptors/builders/simple/default/trigger', data, failure_message=failure_message))['data'][ 'result']['uid'] while True: config_status = self.__get_ml_configuration_status(config_job_id) print('Configuration status: ', config_status) if config_status['status'] == 'Finished': ml_config = self.__convert_response_to_configuration(config_status['result'], dataset_ids) return ml_config time.sleep(5)
[ "This", "method", "will", "spawn", "a", "server", "job", "to", "create", "a", "default", "ML", "configuration", "based", "on", "a", "search", "template", "and", "the", "extract", "as", "keys", ".", "This", "function", "will", "submit", "the", "request", "to", "build", "and", "wait", "for", "the", "configuration", "to", "finish", "before", "returning", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L138-L167
[ "def", "create_ml_configuration", "(", "self", ",", "search_template", ",", "extract_as_keys", ",", "dataset_ids", ")", ":", "data", "=", "{", "\"search_template\"", ":", "search_template", ",", "\"extract_as_keys\"", ":", "extract_as_keys", "}", "failure_message", "=", "\"ML Configuration creation failed\"", "config_job_id", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/descriptors/builders/simple/default/trigger'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "[", "'result'", "]", "[", "'uid'", "]", "while", "True", ":", "config_status", "=", "self", ".", "__get_ml_configuration_status", "(", "config_job_id", ")", "print", "(", "'Configuration status: '", ",", "config_status", ")", "if", "config_status", "[", "'status'", "]", "==", "'Finished'", ":", "ml_config", "=", "self", ".", "__convert_response_to_configuration", "(", "config_status", "[", "'result'", "]", ",", "dataset_ids", ")", "return", "ml_config", "time", ".", "sleep", "(", "5", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.__convert_response_to_configuration
Utility function to turn the result object from the configuration builder endpoint into something that can be used directly as a configuration. :param result_blob: Nested dicts representing the possible descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An object suitable to be used as a parameter to data view create
citrination_client/views/client.py
def __convert_response_to_configuration(self, result_blob, dataset_ids): """ Utility function to turn the result object from the configuration builder endpoint into something that can be used directly as a configuration. :param result_blob: Nested dicts representing the possible descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An object suitable to be used as a parameter to data view create """ builder = DataViewBuilder() builder.dataset_ids(dataset_ids) for i, (k, v) in enumerate(result_blob['descriptors'].items()): try: descriptor = self.__snake_case(v[0]) print(json.dumps(descriptor)) descriptor['descriptor_key'] = k builder.add_raw_descriptor(descriptor) except IndexError: pass for i, (k, v) in enumerate(result_blob['types'].items()): builder.set_role(k, v.lower()) return builder.build()
def __convert_response_to_configuration(self, result_blob, dataset_ids): """ Utility function to turn the result object from the configuration builder endpoint into something that can be used directly as a configuration. :param result_blob: Nested dicts representing the possible descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An object suitable to be used as a parameter to data view create """ builder = DataViewBuilder() builder.dataset_ids(dataset_ids) for i, (k, v) in enumerate(result_blob['descriptors'].items()): try: descriptor = self.__snake_case(v[0]) print(json.dumps(descriptor)) descriptor['descriptor_key'] = k builder.add_raw_descriptor(descriptor) except IndexError: pass for i, (k, v) in enumerate(result_blob['types'].items()): builder.set_role(k, v.lower()) return builder.build()
[ "Utility", "function", "to", "turn", "the", "result", "object", "from", "the", "configuration", "builder", "endpoint", "into", "something", "that", "can", "be", "used", "directly", "as", "a", "configuration", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L169-L193
[ "def", "__convert_response_to_configuration", "(", "self", ",", "result_blob", ",", "dataset_ids", ")", ":", "builder", "=", "DataViewBuilder", "(", ")", "builder", ".", "dataset_ids", "(", "dataset_ids", ")", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "result_blob", "[", "'descriptors'", "]", ".", "items", "(", ")", ")", ":", "try", ":", "descriptor", "=", "self", ".", "__snake_case", "(", "v", "[", "0", "]", ")", "print", "(", "json", ".", "dumps", "(", "descriptor", ")", ")", "descriptor", "[", "'descriptor_key'", "]", "=", "k", "builder", ".", "add_raw_descriptor", "(", "descriptor", ")", "except", "IndexError", ":", "pass", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "result_blob", "[", "'types'", "]", ".", "items", "(", ")", ")", ":", "builder", ".", "set_role", "(", "k", ",", "v", ".", "lower", "(", ")", ")", "return", "builder", ".", "build", "(", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.__snake_case
Utility method to convert camelcase to snake :param descriptor: The dictionary to convert
citrination_client/views/client.py
def __snake_case(self, descriptor): """ Utility method to convert camelcase to snake :param descriptor: The dictionary to convert """ newdict = {} for i, (k, v) in enumerate(descriptor.items()): newkey = "" for j, c in enumerate(k): if c.isupper(): if len(newkey) != 0: newkey += '_' newkey += c.lower() else: newkey += c newdict[newkey] = v return newdict
def __snake_case(self, descriptor): """ Utility method to convert camelcase to snake :param descriptor: The dictionary to convert """ newdict = {} for i, (k, v) in enumerate(descriptor.items()): newkey = "" for j, c in enumerate(k): if c.isupper(): if len(newkey) != 0: newkey += '_' newkey += c.lower() else: newkey += c newdict[newkey] = v return newdict
[ "Utility", "method", "to", "convert", "camelcase", "to", "snake", ":", "param", "descriptor", ":", "The", "dictionary", "to", "convert" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L195-L212
[ "def", "__snake_case", "(", "self", ",", "descriptor", ")", ":", "newdict", "=", "{", "}", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "descriptor", ".", "items", "(", ")", ")", ":", "newkey", "=", "\"\"", "for", "j", ",", "c", "in", "enumerate", "(", "k", ")", ":", "if", "c", ".", "isupper", "(", ")", ":", "if", "len", "(", "newkey", ")", "!=", "0", ":", "newkey", "+=", "'_'", "newkey", "+=", "c", ".", "lower", "(", ")", "else", ":", "newkey", "+=", "c", "newdict", "[", "newkey", "]", "=", "v", "return", "newdict" ]
409984fc65ce101a620f069263f155303492465c
valid
DataViewsClient.__get_ml_configuration_status
After invoking the create_ml_configuration async method, you can use this method to check on the status of the builder job. :param job_id: The identifier returned from create_ml_configuration :return: Job status
citrination_client/views/client.py
def __get_ml_configuration_status(self, job_id): """ After invoking the create_ml_configuration async method, you can use this method to check on the status of the builder job. :param job_id: The identifier returned from create_ml_configuration :return: Job status """ failure_message = "Get status on ml configuration failed" response = self._get_success_json(self._get( 'v1/descriptors/builders/simple/default/' + job_id + '/status', None, failure_message=failure_message))[ 'data'] return response
def __get_ml_configuration_status(self, job_id): """ After invoking the create_ml_configuration async method, you can use this method to check on the status of the builder job. :param job_id: The identifier returned from create_ml_configuration :return: Job status """ failure_message = "Get status on ml configuration failed" response = self._get_success_json(self._get( 'v1/descriptors/builders/simple/default/' + job_id + '/status', None, failure_message=failure_message))[ 'data'] return response
[ "After", "invoking", "the", "create_ml_configuration", "async", "method", "you", "can", "use", "this", "method", "to", "check", "on", "the", "status", "of", "the", "builder", "job", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L214-L227
[ "def", "__get_ml_configuration_status", "(", "self", ",", "job_id", ")", ":", "failure_message", "=", "\"Get status on ml configuration failed\"", "response", "=", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "'v1/descriptors/builders/simple/default/'", "+", "job_id", "+", "'/status'", ",", "None", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "return", "response" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.tsne
Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne`
citrination_client/models/client.py
def tsne(self, data_view_id): """ Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne` """ analysis = self._data_analysis(data_view_id) projections = analysis['projections'] tsne = Tsne() for k, v in projections.items(): projection = Projection( xs=v['x'], ys=v['y'], responses=v['label'], tags=v['inputs'], uids=v['uid'] ) tsne.add_projection(k, projection) return tsne
def tsne(self, data_view_id): """ Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne` """ analysis = self._data_analysis(data_view_id) projections = analysis['projections'] tsne = Tsne() for k, v in projections.items(): projection = Projection( xs=v['x'], ys=v['y'], responses=v['label'], tags=v['inputs'], uids=v['uid'] ) tsne.add_projection(k, projection) return tsne
[ "Get", "the", "t", "-", "SNE", "projection", "including", "responses", "and", "tags", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L28-L50
[ "def", "tsne", "(", "self", ",", "data_view_id", ")", ":", "analysis", "=", "self", ".", "_data_analysis", "(", "data_view_id", ")", "projections", "=", "analysis", "[", "'projections'", "]", "tsne", "=", "Tsne", "(", ")", "for", "k", ",", "v", "in", "projections", ".", "items", "(", ")", ":", "projection", "=", "Projection", "(", "xs", "=", "v", "[", "'x'", "]", ",", "ys", "=", "v", "[", "'y'", "]", ",", "responses", "=", "v", "[", "'label'", "]", ",", "tags", "=", "v", "[", "'inputs'", "]", ",", "uids", "=", "v", "[", "'uid'", "]", ")", "tsne", ".", "add_projection", "(", "k", ",", "projection", ")", "return", "tsne" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.predict
Predict endpoint. This simply wraps the async methods (submit and poll for status/results). :param data_view_id: The ID of the data view to use for prediction :type data_view_id: str :param candidates: A list of candidates to make predictions on :type candidates: list of dicts :param method: Method for propagating predictions through model graphs. "scalar" uses linearized uncertainty propagation, whereas "scalar_from_distribution" still returns scalar predictions but uses sampling to propagate uncertainty without a linear approximation. :type method: str ("scalar" or "scalar_from_distribution") :param use_prior: Whether to apply prior values implied by the property descriptors :type use_prior: bool :return: The results of the prediction :rtype: list of :class:`PredictionResult`
citrination_client/models/client.py
def predict(self, data_view_id, candidates, method="scalar", use_prior=True): """ Predict endpoint. This simply wraps the async methods (submit and poll for status/results). :param data_view_id: The ID of the data view to use for prediction :type data_view_id: str :param candidates: A list of candidates to make predictions on :type candidates: list of dicts :param method: Method for propagating predictions through model graphs. "scalar" uses linearized uncertainty propagation, whereas "scalar_from_distribution" still returns scalar predictions but uses sampling to propagate uncertainty without a linear approximation. :type method: str ("scalar" or "scalar_from_distribution") :param use_prior: Whether to apply prior values implied by the property descriptors :type use_prior: bool :return: The results of the prediction :rtype: list of :class:`PredictionResult` """ uid = self.submit_predict_request(data_view_id, candidates, method, use_prior) while self.check_predict_status(data_view_id, uid)['status'] not in ["Finished", "Failed", "Killed"]: time.sleep(1) result = self.check_predict_status(data_view_id, uid) if result["status"] == "Finished": paired = zip(result["results"]["candidates"], result["results"]["loss"]) prediction_result_format = [{k: (p[0][k], p[1][k]) for k in p[0].keys()} for p in paired] return list(map( lambda c: _get_prediction_result_from_candidate(c), prediction_result_format )) else: raise RuntimeError( "Prediction failed: UID={}, result={}".format(uid, result["status"]) )
def predict(self, data_view_id, candidates, method="scalar", use_prior=True): """ Predict endpoint. This simply wraps the async methods (submit and poll for status/results). :param data_view_id: The ID of the data view to use for prediction :type data_view_id: str :param candidates: A list of candidates to make predictions on :type candidates: list of dicts :param method: Method for propagating predictions through model graphs. "scalar" uses linearized uncertainty propagation, whereas "scalar_from_distribution" still returns scalar predictions but uses sampling to propagate uncertainty without a linear approximation. :type method: str ("scalar" or "scalar_from_distribution") :param use_prior: Whether to apply prior values implied by the property descriptors :type use_prior: bool :return: The results of the prediction :rtype: list of :class:`PredictionResult` """ uid = self.submit_predict_request(data_view_id, candidates, method, use_prior) while self.check_predict_status(data_view_id, uid)['status'] not in ["Finished", "Failed", "Killed"]: time.sleep(1) result = self.check_predict_status(data_view_id, uid) if result["status"] == "Finished": paired = zip(result["results"]["candidates"], result["results"]["loss"]) prediction_result_format = [{k: (p[0][k], p[1][k]) for k in p[0].keys()} for p in paired] return list(map( lambda c: _get_prediction_result_from_candidate(c), prediction_result_format )) else: raise RuntimeError( "Prediction failed: UID={}, result={}".format(uid, result["status"]) )
[ "Predict", "endpoint", ".", "This", "simply", "wraps", "the", "async", "methods", "(", "submit", "and", "poll", "for", "status", "/", "results", ")", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L52-L87
[ "def", "predict", "(", "self", ",", "data_view_id", ",", "candidates", ",", "method", "=", "\"scalar\"", ",", "use_prior", "=", "True", ")", ":", "uid", "=", "self", ".", "submit_predict_request", "(", "data_view_id", ",", "candidates", ",", "method", ",", "use_prior", ")", "while", "self", ".", "check_predict_status", "(", "data_view_id", ",", "uid", ")", "[", "'status'", "]", "not", "in", "[", "\"Finished\"", ",", "\"Failed\"", ",", "\"Killed\"", "]", ":", "time", ".", "sleep", "(", "1", ")", "result", "=", "self", ".", "check_predict_status", "(", "data_view_id", ",", "uid", ")", "if", "result", "[", "\"status\"", "]", "==", "\"Finished\"", ":", "paired", "=", "zip", "(", "result", "[", "\"results\"", "]", "[", "\"candidates\"", "]", ",", "result", "[", "\"results\"", "]", "[", "\"loss\"", "]", ")", "prediction_result_format", "=", "[", "{", "k", ":", "(", "p", "[", "0", "]", "[", "k", "]", ",", "p", "[", "1", "]", "[", "k", "]", ")", "for", "k", "in", "p", "[", "0", "]", ".", "keys", "(", ")", "}", "for", "p", "in", "paired", "]", "return", "list", "(", "map", "(", "lambda", "c", ":", "_get_prediction_result_from_candidate", "(", "c", ")", ",", "prediction_result_format", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Prediction failed: UID={}, result={}\"", ".", "format", "(", "uid", ",", "result", "[", "\"status\"", "]", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.retrain
Start a model retraining :param dataview_id: The ID of the views :return:
citrination_client/models/client.py
def retrain(self, dataview_id): """ Start a model retraining :param dataview_id: The ID of the views :return: """ url = 'data_views/{}/retrain'.format(dataview_id) response = self._post_json(url, data={}) if response.status_code != requests.codes.ok: raise RuntimeError('Retrain requested ' + str(response.status_code) + ' response: ' + str(response.message)) return True
def retrain(self, dataview_id): """ Start a model retraining :param dataview_id: The ID of the views :return: """ url = 'data_views/{}/retrain'.format(dataview_id) response = self._post_json(url, data={}) if response.status_code != requests.codes.ok: raise RuntimeError('Retrain requested ' + str(response.status_code) + ' response: ' + str(response.message)) return True
[ "Start", "a", "model", "retraining", ":", "param", "dataview_id", ":", "The", "ID", "of", "the", "views", ":", "return", ":" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L89-L99
[ "def", "retrain", "(", "self", ",", "dataview_id", ")", ":", "url", "=", "'data_views/{}/retrain'", ".", "format", "(", "dataview_id", ")", "response", "=", "self", ".", "_post_json", "(", "url", ",", "data", "=", "{", "}", ")", "if", "response", ".", "status_code", "!=", "requests", ".", "codes", ".", "ok", ":", "raise", "RuntimeError", "(", "'Retrain requested '", "+", "str", "(", "response", ".", "status_code", ")", "+", "' response: '", "+", "str", "(", "response", ".", "message", ")", ")", "return", "True" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient._data_analysis
Data analysis endpoint. :param data_view_id: The model identifier (id number for data views) :type data_view_id: str :return: dictionary containing information about the data, e.g. dCorr and tsne
citrination_client/models/client.py
def _data_analysis(self, data_view_id): """ Data analysis endpoint. :param data_view_id: The model identifier (id number for data views) :type data_view_id: str :return: dictionary containing information about the data, e.g. dCorr and tsne """ failure_message = "Error while retrieving data analysis for data view {}".format(data_view_id) return self._get_success_json(self._get(routes.data_analysis(data_view_id), failure_message=failure_message))
def _data_analysis(self, data_view_id): """ Data analysis endpoint. :param data_view_id: The model identifier (id number for data views) :type data_view_id: str :return: dictionary containing information about the data, e.g. dCorr and tsne """ failure_message = "Error while retrieving data analysis for data view {}".format(data_view_id) return self._get_success_json(self._get(routes.data_analysis(data_view_id), failure_message=failure_message))
[ "Data", "analysis", "endpoint", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L117-L126
[ "def", "_data_analysis", "(", "self", ",", "data_view_id", ")", ":", "failure_message", "=", "\"Error while retrieving data analysis for data view {}\"", ".", "format", "(", "data_view_id", ")", "return", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "routes", ".", "data_analysis", "(", "data_view_id", ")", ",", "failure_message", "=", "failure_message", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.submit_predict_request
Submits an async prediction request. :param data_view_id: The id returned from create :param candidates: Array of candidates :param prediction_source: 'scalar' or 'scalar_from_distribution' :param use_prior: True to use prior prediction, otherwise False :return: Predict request Id (used to check status)
citrination_client/models/client.py
def submit_predict_request(self, data_view_id, candidates, prediction_source='scalar', use_prior=True): """ Submits an async prediction request. :param data_view_id: The id returned from create :param candidates: Array of candidates :param prediction_source: 'scalar' or 'scalar_from_distribution' :param use_prior: True to use prior prediction, otherwise False :return: Predict request Id (used to check status) """ data = { "prediction_source": prediction_source, "use_prior": use_prior, "candidates": candidates } failure_message = "Configuration creation failed" post_url = 'v1/data_views/' + str(data_view_id) + '/predict/submit' return self._get_success_json( self._post_json(post_url, data, failure_message=failure_message) )['data']['uid']
def submit_predict_request(self, data_view_id, candidates, prediction_source='scalar', use_prior=True): """ Submits an async prediction request. :param data_view_id: The id returned from create :param candidates: Array of candidates :param prediction_source: 'scalar' or 'scalar_from_distribution' :param use_prior: True to use prior prediction, otherwise False :return: Predict request Id (used to check status) """ data = { "prediction_source": prediction_source, "use_prior": use_prior, "candidates": candidates } failure_message = "Configuration creation failed" post_url = 'v1/data_views/' + str(data_view_id) + '/predict/submit' return self._get_success_json( self._post_json(post_url, data, failure_message=failure_message) )['data']['uid']
[ "Submits", "an", "async", "prediction", "request", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L144-L168
[ "def", "submit_predict_request", "(", "self", ",", "data_view_id", ",", "candidates", ",", "prediction_source", "=", "'scalar'", ",", "use_prior", "=", "True", ")", ":", "data", "=", "{", "\"prediction_source\"", ":", "prediction_source", ",", "\"use_prior\"", ":", "use_prior", ",", "\"candidates\"", ":", "candidates", "}", "failure_message", "=", "\"Configuration creation failed\"", "post_url", "=", "'v1/data_views/'", "+", "str", "(", "data_view_id", ")", "+", "'/predict/submit'", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "post_url", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "[", "'uid'", "]" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.check_predict_status
Returns a string indicating the status of the prediction job :param view_id: The data view id returned from data view create :param predict_request_id: The id returned from predict :return: Status data, also includes results if state is finished
citrination_client/models/client.py
def check_predict_status(self, view_id, predict_request_id): """ Returns a string indicating the status of the prediction job :param view_id: The data view id returned from data view create :param predict_request_id: The id returned from predict :return: Status data, also includes results if state is finished """ failure_message = "Get status on predict failed" bare_response = self._get_success_json(self._get( 'v1/data_views/' + str(view_id) + '/predict/' + str(predict_request_id) + '/status', None, failure_message=failure_message)) result = bare_response["data"] # result.update({"message": bare_response["message"]}) return result
def check_predict_status(self, view_id, predict_request_id): """ Returns a string indicating the status of the prediction job :param view_id: The data view id returned from data view create :param predict_request_id: The id returned from predict :return: Status data, also includes results if state is finished """ failure_message = "Get status on predict failed" bare_response = self._get_success_json(self._get( 'v1/data_views/' + str(view_id) + '/predict/' + str(predict_request_id) + '/status', None, failure_message=failure_message)) result = bare_response["data"] # result.update({"message": bare_response["message"]}) return result
[ "Returns", "a", "string", "indicating", "the", "status", "of", "the", "prediction", "job" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L170-L188
[ "def", "check_predict_status", "(", "self", ",", "view_id", ",", "predict_request_id", ")", ":", "failure_message", "=", "\"Get status on predict failed\"", "bare_response", "=", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "'v1/data_views/'", "+", "str", "(", "view_id", ")", "+", "'/predict/'", "+", "str", "(", "predict_request_id", ")", "+", "'/status'", ",", "None", ",", "failure_message", "=", "failure_message", ")", ")", "result", "=", "bare_response", "[", "\"data\"", "]", "# result.update({\"message\": bare_response[\"message\"]})", "return", "result" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.submit_design_run
Submits a new experimental design run. :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param num_candidates: The number of candidates to return :type num_candidates: int :param target: An :class:``Target`` instance representing the design run optimization target :type target: :class:``Target`` :param constraints: An array of design constraints (instances of objects which extend :class:``BaseConstraint``) :type constraints: list of :class:``BaseConstraint`` :param sampler: The name of the sampler to use during the design run: either "Default" or "This view" :type sampler: str :return: A :class:`DesignRun` instance containing the UID of the new run
citrination_client/models/client.py
def submit_design_run(self, data_view_id, num_candidates, effort, target=None, constraints=[], sampler="Default"): """ Submits a new experimental design run. :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param num_candidates: The number of candidates to return :type num_candidates: int :param target: An :class:``Target`` instance representing the design run optimization target :type target: :class:``Target`` :param constraints: An array of design constraints (instances of objects which extend :class:``BaseConstraint``) :type constraints: list of :class:``BaseConstraint`` :param sampler: The name of the sampler to use during the design run: either "Default" or "This view" :type sampler: str :return: A :class:`DesignRun` instance containing the UID of the new run """ if effort > 30: raise CitrinationClientError("Parameter effort must be less than 30 to trigger a design run") if target is not None: target = target.to_dict() constraint_dicts = [c.to_dict() for c in constraints] body = { "num_candidates": num_candidates, "target": target, "effort": effort, "constraints": constraint_dicts, "sampler": sampler } url = routes.submit_data_view_design(data_view_id) response = self._post_json(url, body).json() return DesignRun(response["data"]["design_run"]["uid"])
def submit_design_run(self, data_view_id, num_candidates, effort, target=None, constraints=[], sampler="Default"): """ Submits a new experimental design run. :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param num_candidates: The number of candidates to return :type num_candidates: int :param target: An :class:``Target`` instance representing the design run optimization target :type target: :class:``Target`` :param constraints: An array of design constraints (instances of objects which extend :class:``BaseConstraint``) :type constraints: list of :class:``BaseConstraint`` :param sampler: The name of the sampler to use during the design run: either "Default" or "This view" :type sampler: str :return: A :class:`DesignRun` instance containing the UID of the new run """ if effort > 30: raise CitrinationClientError("Parameter effort must be less than 30 to trigger a design run") if target is not None: target = target.to_dict() constraint_dicts = [c.to_dict() for c in constraints] body = { "num_candidates": num_candidates, "target": target, "effort": effort, "constraints": constraint_dicts, "sampler": sampler } url = routes.submit_data_view_design(data_view_id) response = self._post_json(url, body).json() return DesignRun(response["data"]["design_run"]["uid"])
[ "Submits", "a", "new", "experimental", "design", "run", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L190-L231
[ "def", "submit_design_run", "(", "self", ",", "data_view_id", ",", "num_candidates", ",", "effort", ",", "target", "=", "None", ",", "constraints", "=", "[", "]", ",", "sampler", "=", "\"Default\"", ")", ":", "if", "effort", ">", "30", ":", "raise", "CitrinationClientError", "(", "\"Parameter effort must be less than 30 to trigger a design run\"", ")", "if", "target", "is", "not", "None", ":", "target", "=", "target", ".", "to_dict", "(", ")", "constraint_dicts", "=", "[", "c", ".", "to_dict", "(", ")", "for", "c", "in", "constraints", "]", "body", "=", "{", "\"num_candidates\"", ":", "num_candidates", ",", "\"target\"", ":", "target", ",", "\"effort\"", ":", "effort", ",", "\"constraints\"", ":", "constraint_dicts", ",", "\"sampler\"", ":", "sampler", "}", "url", "=", "routes", ".", "submit_data_view_design", "(", "data_view_id", ")", "response", "=", "self", ".", "_post_json", "(", "url", ",", "body", ")", ".", "json", "(", ")", "return", "DesignRun", "(", "response", "[", "\"data\"", "]", "[", "\"design_run\"", "]", "[", "\"uid\"", "]", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.get_design_run_status
Retrieves the status of an in progress or completed design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve status for :type run_uuid: str :return: A :class:`ProcessStatus` object
citrination_client/models/client.py
def get_design_run_status(self, data_view_id, run_uuid): """ Retrieves the status of an in progress or completed design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve status for :type run_uuid: str :return: A :class:`ProcessStatus` object """ url = routes.get_data_view_design_status(data_view_id, run_uuid) response = self._get(url).json() status = response["data"] return ProcessStatus( result=status.get("result"), progress=status.get("progress"), status=status.get("status"), messages=status.get("messages") )
def get_design_run_status(self, data_view_id, run_uuid): """ Retrieves the status of an in progress or completed design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve status for :type run_uuid: str :return: A :class:`ProcessStatus` object """ url = routes.get_data_view_design_status(data_view_id, run_uuid) response = self._get(url).json() status = response["data"] return ProcessStatus( result=status.get("result"), progress=status.get("progress"), status=status.get("status"), messages=status.get("messages") )
[ "Retrieves", "the", "status", "of", "an", "in", "progress", "or", "completed", "design", "run" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L233-L256
[ "def", "get_design_run_status", "(", "self", ",", "data_view_id", ",", "run_uuid", ")", ":", "url", "=", "routes", ".", "get_data_view_design_status", "(", "data_view_id", ",", "run_uuid", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "status", "=", "response", "[", "\"data\"", "]", "return", "ProcessStatus", "(", "result", "=", "status", ".", "get", "(", "\"result\"", ")", ",", "progress", "=", "status", ".", "get", "(", "\"progress\"", ")", ",", "status", "=", "status", ".", "get", "(", "\"status\"", ")", ",", "messages", "=", "status", ".", "get", "(", "\"messages\"", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.get_design_run_results
Retrieves the results of an existing designrun :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve results from :type run_uuid: str :return: A :class:`DesignResults` object
citrination_client/models/client.py
def get_design_run_results(self, data_view_id, run_uuid): """ Retrieves the results of an existing designrun :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve results from :type run_uuid: str :return: A :class:`DesignResults` object """ url = routes.get_data_view_design_results(data_view_id, run_uuid) response = self._get(url).json() result = response["data"] return DesignResults( best_materials=result.get("best_material_results"), next_experiments=result.get("next_experiment_results") )
def get_design_run_results(self, data_view_id, run_uuid): """ Retrieves the results of an existing designrun :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve results from :type run_uuid: str :return: A :class:`DesignResults` object """ url = routes.get_data_view_design_results(data_view_id, run_uuid) response = self._get(url).json() result = response["data"] return DesignResults( best_materials=result.get("best_material_results"), next_experiments=result.get("next_experiment_results") )
[ "Retrieves", "the", "results", "of", "an", "existing", "designrun" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L258-L279
[ "def", "get_design_run_results", "(", "self", ",", "data_view_id", ",", "run_uuid", ")", ":", "url", "=", "routes", ".", "get_data_view_design_results", "(", "data_view_id", ",", "run_uuid", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "result", "=", "response", "[", "\"data\"", "]", "return", "DesignResults", "(", "best_materials", "=", "result", ".", "get", "(", "\"best_material_results\"", ")", ",", "next_experiments", "=", "result", ".", "get", "(", "\"next_experiment_results\"", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.get_data_view
Retrieves a summary of information for a given data view - view id - name - description - columns :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str
citrination_client/models/client.py
def get_data_view(self, data_view_id): """ Retrieves a summary of information for a given data view - view id - name - description - columns :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str """ url = routes.get_data_view(data_view_id) response = self._get(url).json() result = response["data"]["data_view"] datasets_list = [] for dataset in result["datasets"]: datasets_list.append(Dataset( name=dataset["name"], id=dataset["id"], description=dataset["description"] )) columns_list = [] for column in result["columns"]: columns_list.append(ColumnFactory.from_dict(column)) return DataView( view_id=data_view_id, name=result["name"], description=result["description"], datasets=datasets_list, columns=columns_list, )
def get_data_view(self, data_view_id): """ Retrieves a summary of information for a given data view - view id - name - description - columns :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str """ url = routes.get_data_view(data_view_id) response = self._get(url).json() result = response["data"]["data_view"] datasets_list = [] for dataset in result["datasets"]: datasets_list.append(Dataset( name=dataset["name"], id=dataset["id"], description=dataset["description"] )) columns_list = [] for column in result["columns"]: columns_list.append(ColumnFactory.from_dict(column)) return DataView( view_id=data_view_id, name=result["name"], description=result["description"], datasets=datasets_list, columns=columns_list, )
[ "Retrieves", "a", "summary", "of", "information", "for", "a", "given", "data", "view", "-", "view", "id", "-", "name", "-", "description", "-", "columns" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L281-L318
[ "def", "get_data_view", "(", "self", ",", "data_view_id", ")", ":", "url", "=", "routes", ".", "get_data_view", "(", "data_view_id", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "result", "=", "response", "[", "\"data\"", "]", "[", "\"data_view\"", "]", "datasets_list", "=", "[", "]", "for", "dataset", "in", "result", "[", "\"datasets\"", "]", ":", "datasets_list", ".", "append", "(", "Dataset", "(", "name", "=", "dataset", "[", "\"name\"", "]", ",", "id", "=", "dataset", "[", "\"id\"", "]", ",", "description", "=", "dataset", "[", "\"description\"", "]", ")", ")", "columns_list", "=", "[", "]", "for", "column", "in", "result", "[", "\"columns\"", "]", ":", "columns_list", ".", "append", "(", "ColumnFactory", ".", "from_dict", "(", "column", ")", ")", "return", "DataView", "(", "view_id", "=", "data_view_id", ",", "name", "=", "result", "[", "\"name\"", "]", ",", "description", "=", "result", "[", "\"description\"", "]", ",", "datasets", "=", "datasets_list", ",", "columns", "=", "columns_list", ",", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
ModelsClient.kill_design_run
Kills an in progress experimental design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to kill :type run_uuid: str :return: The UUID of the design run
citrination_client/models/client.py
def kill_design_run(self, data_view_id, run_uuid): """ Kills an in progress experimental design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to kill :type run_uuid: str :return: The UUID of the design run """ url = routes.kill_data_view_design_run(data_view_id, run_uuid) response = self._delete(url).json() return response["data"]["uid"]
def kill_design_run(self, data_view_id, run_uuid): """ Kills an in progress experimental design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to kill :type run_uuid: str :return: The UUID of the design run """ url = routes.kill_data_view_design_run(data_view_id, run_uuid) response = self._delete(url).json() return response["data"]["uid"]
[ "Kills", "an", "in", "progress", "experimental", "design", "run" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L320-L335
[ "def", "kill_design_run", "(", "self", ",", "data_view_id", ",", "run_uuid", ")", ":", "url", "=", "routes", ".", "kill_data_view_design_run", "(", "data_view_id", ",", "run_uuid", ")", "response", "=", "self", ".", "_delete", "(", "url", ")", ".", "json", "(", ")", "return", "response", "[", "\"data\"", "]", "[", "\"uid\"", "]" ]
409984fc65ce101a620f069263f155303492465c
valid
load_file_as_yaml
Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file
citrination_client/util/credentials.py
def load_file_as_yaml(path): """ Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file """ with open(path, "r") as f: raw_yaml = f.read() parsed_dict = yaml.load(raw_yaml) return parsed_dict
def load_file_as_yaml(path): """ Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file """ with open(path, "r") as f: raw_yaml = f.read() parsed_dict = yaml.load(raw_yaml) return parsed_dict
[ "Given", "a", "filepath", "loads", "the", "file", "as", "a", "dictionary", "from", "YAML" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/util/credentials.py#L20-L29
[ "def", "load_file_as_yaml", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "f", ":", "raw_yaml", "=", "f", ".", "read", "(", ")", "parsed_dict", "=", "yaml", ".", "load", "(", "raw_yaml", ")", "return", "parsed_dict" ]
409984fc65ce101a620f069263f155303492465c
valid
get_credentials_from_file
Extracts credentials from the yaml formatted credential filepath passed in. Uses the default profile if the CITRINATION_PROFILE env var is not set, otherwise looks for a profile with that name in the credentials file. :param filepath: The path of the credentials file
citrination_client/util/credentials.py
def get_credentials_from_file(filepath): """ Extracts credentials from the yaml formatted credential filepath passed in. Uses the default profile if the CITRINATION_PROFILE env var is not set, otherwise looks for a profile with that name in the credentials file. :param filepath: The path of the credentials file """ try: creds = load_file_as_yaml(filepath) except Exception: creds = {} profile_name = os.environ.get(citr_env_vars.CITRINATION_PROFILE) if profile_name is None or len(profile_name) == 0: profile_name = DEFAULT_CITRINATION_PROFILE api_key = None site = None try: profile = creds[profile_name] api_key = profile[CREDENTIALS_API_KEY_KEY] site = profile[CREDENTIALS_SITE_KEY] except KeyError: pass return (api_key, site)
def get_credentials_from_file(filepath): """ Extracts credentials from the yaml formatted credential filepath passed in. Uses the default profile if the CITRINATION_PROFILE env var is not set, otherwise looks for a profile with that name in the credentials file. :param filepath: The path of the credentials file """ try: creds = load_file_as_yaml(filepath) except Exception: creds = {} profile_name = os.environ.get(citr_env_vars.CITRINATION_PROFILE) if profile_name is None or len(profile_name) == 0: profile_name = DEFAULT_CITRINATION_PROFILE api_key = None site = None try: profile = creds[profile_name] api_key = profile[CREDENTIALS_API_KEY_KEY] site = profile[CREDENTIALS_SITE_KEY] except KeyError: pass return (api_key, site)
[ "Extracts", "credentials", "from", "the", "yaml", "formatted", "credential", "filepath", "passed", "in", ".", "Uses", "the", "default", "profile", "if", "the", "CITRINATION_PROFILE", "env", "var", "is", "not", "set", "otherwise", "looks", "for", "a", "profile", "with", "that", "name", "in", "the", "credentials", "file", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/util/credentials.py#L31-L56
[ "def", "get_credentials_from_file", "(", "filepath", ")", ":", "try", ":", "creds", "=", "load_file_as_yaml", "(", "filepath", ")", "except", "Exception", ":", "creds", "=", "{", "}", "profile_name", "=", "os", ".", "environ", ".", "get", "(", "citr_env_vars", ".", "CITRINATION_PROFILE", ")", "if", "profile_name", "is", "None", "or", "len", "(", "profile_name", ")", "==", "0", ":", "profile_name", "=", "DEFAULT_CITRINATION_PROFILE", "api_key", "=", "None", "site", "=", "None", "try", ":", "profile", "=", "creds", "[", "profile_name", "]", "api_key", "=", "profile", "[", "CREDENTIALS_API_KEY_KEY", "]", "site", "=", "profile", "[", "CREDENTIALS_SITE_KEY", "]", "except", "KeyError", ":", "pass", "return", "(", "api_key", ",", "site", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
get_preferred_credentials
Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials. Specifically, this method ranks credential priority as follows: 1. Those passed in as the first two parameters to this method 2. Those found in the environment as variables 3. Those found in the credentials file at the profile specified by the profile environment variable 4. Those found in the default stanza in the credentials file :param api_key: A Citrination API Key or None :param site: A Citrination site URL or None :param cred_file: The path to a credentials file
citrination_client/util/credentials.py
def get_preferred_credentials(api_key, site, cred_file=DEFAULT_CITRINATION_CREDENTIALS_FILE): """ Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials. Specifically, this method ranks credential priority as follows: 1. Those passed in as the first two parameters to this method 2. Those found in the environment as variables 3. Those found in the credentials file at the profile specified by the profile environment variable 4. Those found in the default stanza in the credentials file :param api_key: A Citrination API Key or None :param site: A Citrination site URL or None :param cred_file: The path to a credentials file """ profile_api_key, profile_site = get_credentials_from_file(cred_file) if api_key is None: api_key = os.environ.get(citr_env_vars.CITRINATION_API_KEY) if api_key is None or len(api_key) == 0: api_key = profile_api_key if site is None: site = os.environ.get(citr_env_vars.CITRINATION_SITE) if site is None or len(site) == 0: site = profile_site if site is None: site = "https://citrination.com" return api_key, site
def get_preferred_credentials(api_key, site, cred_file=DEFAULT_CITRINATION_CREDENTIALS_FILE): """ Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials. Specifically, this method ranks credential priority as follows: 1. Those passed in as the first two parameters to this method 2. Those found in the environment as variables 3. Those found in the credentials file at the profile specified by the profile environment variable 4. Those found in the default stanza in the credentials file :param api_key: A Citrination API Key or None :param site: A Citrination site URL or None :param cred_file: The path to a credentials file """ profile_api_key, profile_site = get_credentials_from_file(cred_file) if api_key is None: api_key = os.environ.get(citr_env_vars.CITRINATION_API_KEY) if api_key is None or len(api_key) == 0: api_key = profile_api_key if site is None: site = os.environ.get(citr_env_vars.CITRINATION_SITE) if site is None or len(site) == 0: site = profile_site if site is None: site = "https://citrination.com" return api_key, site
[ "Given", "an", "API", "key", "a", "site", "url", "and", "a", "credentials", "file", "path", "runs", "through", "a", "prioritized", "list", "of", "credential", "sources", "to", "find", "credentials", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/util/credentials.py#L58-L86
[ "def", "get_preferred_credentials", "(", "api_key", ",", "site", ",", "cred_file", "=", "DEFAULT_CITRINATION_CREDENTIALS_FILE", ")", ":", "profile_api_key", ",", "profile_site", "=", "get_credentials_from_file", "(", "cred_file", ")", "if", "api_key", "is", "None", ":", "api_key", "=", "os", ".", "environ", ".", "get", "(", "citr_env_vars", ".", "CITRINATION_API_KEY", ")", "if", "api_key", "is", "None", "or", "len", "(", "api_key", ")", "==", "0", ":", "api_key", "=", "profile_api_key", "if", "site", "is", "None", ":", "site", "=", "os", ".", "environ", ".", "get", "(", "citr_env_vars", ".", "CITRINATION_SITE", ")", "if", "site", "is", "None", "or", "len", "(", "site", ")", "==", "0", ":", "site", "=", "profile_site", "if", "site", "is", "None", ":", "site", "=", "\"https://citrination.com\"", "return", "api_key", ",", "site" ]
409984fc65ce101a620f069263f155303492465c
valid
DataClient.upload
Upload a file, specifying source and dest paths a file (acts as the scp command).asdfasdf :param source_path: The path to the file on the source host asdf :type source_path: str :param dest_path: The path to the file where the contents of the upload will be written (on the dest host) :type dest_path: str :return: The result of the upload process :rtype: :class:`UploadResult`
citrination_client/data/client.py
def upload(self, dataset_id, source_path, dest_path=None): """ Upload a file, specifying source and dest paths a file (acts as the scp command).asdfasdf :param source_path: The path to the file on the source host asdf :type source_path: str :param dest_path: The path to the file where the contents of the upload will be written (on the dest host) :type dest_path: str :return: The result of the upload process :rtype: :class:`UploadResult` """ upload_result = UploadResult() source_path = str(source_path) if not dest_path: dest_path = source_path else: dest_path = str(dest_path) if os.path.isdir(source_path): for path, subdirs, files in os.walk(source_path): relative_path = os.path.relpath(path, source_path) current_dest_prefix = dest_path if relative_path is not ".": current_dest_prefix = os.path.join(current_dest_prefix, relative_path) for name in files: current_dest_path = os.path.join(current_dest_prefix, name) current_source_path = os.path.join(path, name) try: if self.upload(dataset_id, current_source_path, current_dest_path).successful(): upload_result.add_success(current_source_path) else: upload_result.add_failure(current_source_path,"Upload failure") except (CitrinationClientError, ValueError) as e: upload_result.add_failure(current_source_path, str(e)) return upload_result elif os.path.isfile(source_path): file_data = { "dest_path": str(dest_path), "src_path": str(source_path)} j = self._get_success_json(self._post_json(routes.upload_to_dataset(dataset_id), data=file_data)) s3url = _get_s3_presigned_url(j) with open(source_path, 'rb') as f: if os.stat(source_path).st_size == 0: # Upload a null character as a placeholder for # the empty file since Citrination does not support # truly empty files data = "\0" else: data = f r = requests.put(s3url, data=data, headers=j["required_headers"]) if r.status_code == 200: data = {'s3object': j['url']['path'], 's3bucket': j['bucket']} self._post_json(routes.update_file(j['file_id']), data=data) upload_result.add_success(source_path) return upload_result else: raise CitrinationClientError("Failure to upload {} to Citrination".format(source_path)) else: raise ValueError("No file at specified path {}".format(source_path))
def upload(self, dataset_id, source_path, dest_path=None): """ Upload a file, specifying source and dest paths a file (acts as the scp command).asdfasdf :param source_path: The path to the file on the source host asdf :type source_path: str :param dest_path: The path to the file where the contents of the upload will be written (on the dest host) :type dest_path: str :return: The result of the upload process :rtype: :class:`UploadResult` """ upload_result = UploadResult() source_path = str(source_path) if not dest_path: dest_path = source_path else: dest_path = str(dest_path) if os.path.isdir(source_path): for path, subdirs, files in os.walk(source_path): relative_path = os.path.relpath(path, source_path) current_dest_prefix = dest_path if relative_path is not ".": current_dest_prefix = os.path.join(current_dest_prefix, relative_path) for name in files: current_dest_path = os.path.join(current_dest_prefix, name) current_source_path = os.path.join(path, name) try: if self.upload(dataset_id, current_source_path, current_dest_path).successful(): upload_result.add_success(current_source_path) else: upload_result.add_failure(current_source_path,"Upload failure") except (CitrinationClientError, ValueError) as e: upload_result.add_failure(current_source_path, str(e)) return upload_result elif os.path.isfile(source_path): file_data = { "dest_path": str(dest_path), "src_path": str(source_path)} j = self._get_success_json(self._post_json(routes.upload_to_dataset(dataset_id), data=file_data)) s3url = _get_s3_presigned_url(j) with open(source_path, 'rb') as f: if os.stat(source_path).st_size == 0: # Upload a null character as a placeholder for # the empty file since Citrination does not support # truly empty files data = "\0" else: data = f r = requests.put(s3url, data=data, headers=j["required_headers"]) if r.status_code == 200: data = {'s3object': j['url']['path'], 's3bucket': j['bucket']} self._post_json(routes.update_file(j['file_id']), data=data) upload_result.add_success(source_path) return upload_result else: raise CitrinationClientError("Failure to upload {} to Citrination".format(source_path)) else: raise ValueError("No file at specified path {}".format(source_path))
[ "Upload", "a", "file", "specifying", "source", "and", "dest", "paths", "a", "file", "(", "acts", "as", "the", "scp", "command", ")", ".", "asdfasdf" ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L42-L97
[ "def", "upload", "(", "self", ",", "dataset_id", ",", "source_path", ",", "dest_path", "=", "None", ")", ":", "upload_result", "=", "UploadResult", "(", ")", "source_path", "=", "str", "(", "source_path", ")", "if", "not", "dest_path", ":", "dest_path", "=", "source_path", "else", ":", "dest_path", "=", "str", "(", "dest_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "source_path", ")", ":", "for", "path", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "source_path", ")", ":", "relative_path", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "source_path", ")", "current_dest_prefix", "=", "dest_path", "if", "relative_path", "is", "not", "\".\"", ":", "current_dest_prefix", "=", "os", ".", "path", ".", "join", "(", "current_dest_prefix", ",", "relative_path", ")", "for", "name", "in", "files", ":", "current_dest_path", "=", "os", ".", "path", ".", "join", "(", "current_dest_prefix", ",", "name", ")", "current_source_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "try", ":", "if", "self", ".", "upload", "(", "dataset_id", ",", "current_source_path", ",", "current_dest_path", ")", ".", "successful", "(", ")", ":", "upload_result", ".", "add_success", "(", "current_source_path", ")", "else", ":", "upload_result", ".", "add_failure", "(", "current_source_path", ",", "\"Upload failure\"", ")", "except", "(", "CitrinationClientError", ",", "ValueError", ")", "as", "e", ":", "upload_result", ".", "add_failure", "(", "current_source_path", ",", "str", "(", "e", ")", ")", "return", "upload_result", "elif", "os", ".", "path", ".", "isfile", "(", "source_path", ")", ":", "file_data", "=", "{", "\"dest_path\"", ":", "str", "(", "dest_path", ")", ",", "\"src_path\"", ":", "str", "(", "source_path", ")", "}", "j", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "upload_to_dataset", "(", "dataset_id", ")", ",", "data", "=", "file_data", ")", ")", "s3url", "=", "_get_s3_presigned_url", "(", "j", ")", "with", "open", "(", "source_path", ",", "'rb'", ")", "as", "f", ":", "if", "os", ".", "stat", "(", "source_path", ")", ".", "st_size", "==", "0", ":", "# Upload a null character as a placeholder for", "# the empty file since Citrination does not support", "# truly empty files", "data", "=", "\"\\0\"", "else", ":", "data", "=", "f", "r", "=", "requests", ".", "put", "(", "s3url", ",", "data", "=", "data", ",", "headers", "=", "j", "[", "\"required_headers\"", "]", ")", "if", "r", ".", "status_code", "==", "200", ":", "data", "=", "{", "'s3object'", ":", "j", "[", "'url'", "]", "[", "'path'", "]", ",", "'s3bucket'", ":", "j", "[", "'bucket'", "]", "}", "self", ".", "_post_json", "(", "routes", ".", "update_file", "(", "j", "[", "'file_id'", "]", ")", ",", "data", "=", "data", ")", "upload_result", ".", "add_success", "(", "source_path", ")", "return", "upload_result", "else", ":", "raise", "CitrinationClientError", "(", "\"Failure to upload {} to Citrination\"", ".", "format", "(", "source_path", ")", ")", "else", ":", "raise", "ValueError", "(", "\"No file at specified path {}\"", ".", "format", "(", "source_path", ")", ")" ]
409984fc65ce101a620f069263f155303492465c
valid
DataClient.list_files
List matched filenames in a dataset on Citrination. :param dataset_id: The ID of the dataset to search for files. :type dataset_id: int :param glob: A pattern which will be matched against files in the dataset. :type glob: str :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset. :type is_dir: bool :return: A list of filepaths in the dataset matching the provided glob. :rtype: list of strings
citrination_client/data/client.py
def list_files(self, dataset_id, glob=".", is_dir=False): """ List matched filenames in a dataset on Citrination. :param dataset_id: The ID of the dataset to search for files. :type dataset_id: int :param glob: A pattern which will be matched against files in the dataset. :type glob: str :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset. :type is_dir: bool :return: A list of filepaths in the dataset matching the provided glob. :rtype: list of strings """ data = { "list": { "glob": glob, "isDir": is_dir } } return self._get_success_json(self._post_json(routes.list_files(dataset_id), data, failure_message="Failed to list files for dataset {}".format(dataset_id)))['files']
def list_files(self, dataset_id, glob=".", is_dir=False): """ List matched filenames in a dataset on Citrination. :param dataset_id: The ID of the dataset to search for files. :type dataset_id: int :param glob: A pattern which will be matched against files in the dataset. :type glob: str :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset. :type is_dir: bool :return: A list of filepaths in the dataset matching the provided glob. :rtype: list of strings """ data = { "list": { "glob": glob, "isDir": is_dir } } return self._get_success_json(self._post_json(routes.list_files(dataset_id), data, failure_message="Failed to list files for dataset {}".format(dataset_id)))['files']
[ "List", "matched", "filenames", "in", "a", "dataset", "on", "Citrination", "." ]
CitrineInformatics/python-citrination-client
python
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L99-L118
[ "def", "list_files", "(", "self", ",", "dataset_id", ",", "glob", "=", "\".\"", ",", "is_dir", "=", "False", ")", ":", "data", "=", "{", "\"list\"", ":", "{", "\"glob\"", ":", "glob", ",", "\"isDir\"", ":", "is_dir", "}", "}", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "list_files", "(", "dataset_id", ")", ",", "data", ",", "failure_message", "=", "\"Failed to list files for dataset {}\"", ".", "format", "(", "dataset_id", ")", ")", ")", "[", "'files'", "]" ]
409984fc65ce101a620f069263f155303492465c