def generate_token(key, user_id, action_id='', when=None): """Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token. """ digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8')) digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8')) digester.update(DELIMITER) digester.update(_helpers._to_bytes(action_id, encoding='utf-8')) digester.update(DELIMITER) when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8') digester.update(when) digest = digester.digest() token = base64.urlsafe_b64encode(digest + DELIMITER + when) return token
def clean_headers(headers): """Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary of headers. Returns: The same dictionary but with all the keys converted to strings. """ clean = {} try: for k, v in six.iteritems(headers): if not isinstance(k, six.binary_type): k = str(k) if not isinstance(v, six.binary_type): v = str(v) clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v) except UnicodeEncodeError: from my_oauth2client.client import NonAsciiHeaderError raise NonAsciiHeaderError(k, ': ', v) return clean
def from_string(cls, key_pem, is_x509_cert): """Construct an RsaVerifier instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: RsaVerifier instance. Raises: ValueError: if the key_pem can't be parsed. In either case, error will begin with 'No PEM start marker'. If ``is_x509_cert`` is True, will fail to find the "-----BEGIN CERTIFICATE-----" error, otherwise fails to find "-----BEGIN RSA PUBLIC KEY-----". """ key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: der = rsa.pem.load_pem(key_pem, 'CERTIFICATE') asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) if remaining != b'': raise ValueError('Unused bytes', remaining) cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo'] key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey']) pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER') else: pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM') return cls(pubkey)
def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return rsa.pkcs1.sign(message, self._key, 'SHA-256')
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._pubkey).verify(SHA256.new(message), signature)
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') try: return rsa.pkcs1.verify(message, signature, self._pubkey) except (ValueError, rsa.pkcs1.VerificationError): return False
def verify_signed_jwt_with_certs(jwt, certs, audience=None): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError: if any checks are failed. """ jwt = _helpers._to_bytes(jwt) if jwt.count(b'.') != 2: raise AppIdentityError( 'Wrong number of segments in token: {0}'.format(jwt)) header, payload, signature = jwt.split(b'.') message_to_sign = header + b'.' + payload signature = _helpers._urlsafe_b64decode(signature) # Parse token. payload_bytes = _helpers._urlsafe_b64decode(payload) try: payload_dict = json.loads(_helpers._from_bytes(payload_bytes)) except: raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes)) # Verify that the signature matches the message. _verify_signature(message_to_sign, signature, certs.values()) # Verify the issued at and created times in the payload. _verify_time_range(payload_dict) # Check audience. _check_audience(payload_dict, audience) return payload_dict
def _write_credentials_file(credentials_file, credentials): """Writes credentials to a file. Refer to :func:`_load_credentials_file` for the format. Args: credentials_file: An open file handle, must be read/write. credentials: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`. """ data = {'file_version': 2, 'credentials': {}} for key, credential in iteritems(credentials): credential_json = credential.to_json() encoded_credential = _helpers._from_bytes(base64.b64encode( _helpers._to_bytes(credential_json))) data['credentials'][key] = encoded_credential credentials_file.seek(0) json.dump(data, credentials_file) credentials_file.truncate()
def from_string(key, password='******'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if the key isn't in PEM format. """ parsed_pem_key = _helpers._parse_pem_key(_helpers._to_bytes(key)) if parsed_pem_key: pkey = RSA.importKey(parsed_pem_key) else: raise NotImplementedError( 'No key in PEM format was detected. This implementation ' 'can only use the PyCrypto library for keys in PEM ' 'format.') return PyCryptoSigner(pkey)
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. """ if is_x509_cert: key_pem = _helpers._to_bytes(key_pem) pemLines = key_pem.replace(b' ', b'').split() certDer = _helpers._urlsafe_b64decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
def _SendRecv(): """Communicate with the Developer Shell server socket.""" port = int(os.getenv(DEVSHELL_ENV, 0)) if port == 0: raise NoDevshellServer() sock = socket.socket() sock.connect(('localhost', port)) data = CREDENTIAL_INFO_REQUEST_JSON msg = '{0}\n{1}'.format(len(data), data) sock.sendall(_helpers._to_bytes(msg, encoding='utf-8')) header = sock.recv(6).decode() if '\n' not in header: raise CommunicationError('saw no newline in the first 6 bytes') len_str, json_str = header.split('\n', 1) to_read = int(len_str) - len(json_str) if to_read > 0: json_str += sock.recv(to_read, socket.MSG_WAITALL).decode() return CredentialInfoResponse(json_str)