In my Python code, I'm using cryptography module. I have a private key on disk. So, from documentation, I used this example to load that key. Then use that key to sign a message. But running the program throws AttributeError: '_RSAPrivateKey' object has no attribute 'sign'
I looked in to source code of serialization module and check return type of load_pem_private_key(). The code requires some understanding of Abstract Base Classes.
Seeking help here to debug this issue.
Here's my code
1 from cryptography.hazmat.backends import default_backend
2 from cryptography.hazmat.primitives import hashes
3 from cryptography.hazmat.primitives import serialization
4 from cryptography.hazmat.primitives.asymmetric import padding
5 from cryptography.hazmat.primitives.asymmetric import utils
6
7 from base64 import b64encode
8
9 def test_new_crypto():
10 privkey = '/path/to/privkey'
11 with open(privkey, "rb") as kf:
12 private_key = serialization.load_pem_private_key(
13 kf.read(),
14 password=None,
15 backend=default_backend()
16 )
17
18 message = b"A message I want to sign"
19 signature = private_key.sign( #### Error is here
20 message,
21 padding.PSS(
22 mgf=padding.MGF1(hashes.SHA256()),
23 salt_length=padding.PSS.MAX_LENGTH
24 ),
25 hashes.SHA256()
26 )
27
28 return b64encode(signature)
29
30 if __name__ == "__main__":
31 print(test_new_crypto())
You mention you are running an outdated version.
Upgrading from version 1.7.1 to 2.6.1 resolves the issue.
If you are here in 2022 and you use PyJWT, in cryptography version 37 the signer methods were deprecated, so you have to downgrade to version 36.0.2 of cryptography.
Related
I am working on deep learing project so for that I wanted to import tensorflow library but when I run the code cell in the jupyter notebook it pops up the following error.
Importing tensforflow library error screenshot
Importing tensforflow library error screenshot continue
import tensorflow as tf
error
AttributeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 import tensorflow as tf
File ~\anaconda3\lib\site-packages\tensorflow\__init__.py:469
467 if hasattr(_current_module, "keras"):
468 try:
--> 469 _keras._load()
470 except ImportError:
471 pass
File ~\anaconda3\lib\site-packages\tensorflow\python\util\lazy_loader.py:41, in LazyLoader._load(self)
39 """Load the module and insert it into the parent's globals."""
40 # Import the target module and insert it into the parent's namespace
---> 41 module = importlib.import_module(self.__name__)
42 self._parent_module_globals[self._local_name] = module
44 # Emit a warning if one was specified
File ~\anaconda3\lib\importlib\__init__.py:127, in import_module(name, package)
125 break
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
File ~\anaconda3\lib\site-packages\keras\__init__.py:21
15 """Implementation of the Keras API, the high-level API of TensorFlow.
16
17 Detailed documentation and user guides are available at
18 [keras.io](https://keras.io).
19 """
20 from keras import distribute
---> 21 from keras import models
22 from keras.engine.input_layer import Input
23 from keras.engine.sequential import Sequential
File ~\anaconda3\lib\site-packages\keras\models\__init__.py:18
1 # Copyright 2022 The TensorFlow Authors. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
(...)
13 # limitations under the License.
14 # ==============================================================================
15 """Keras models API."""
---> 18 from keras.engine.functional import Functional
19 from keras.engine.sequential import Sequential
20 from keras.engine.training import Model
File ~\anaconda3\lib\site-packages\keras\engine\functional.py:34
32 from keras.engine import input_spec
33 from keras.engine import node as node_module
---> 34 from keras.engine import training as training_lib
35 from keras.engine import training_utils
36 from keras.saving.legacy import serialization
File ~\anaconda3\lib\site-packages\keras\engine\training.py:45
43 from keras.saving.experimental import saving_lib
44 from keras.saving.legacy import hdf5_format
---> 45 from keras.saving.legacy import save
46 from keras.saving.legacy import saving_utils
47 from keras.saving.legacy import serialization
File ~\anaconda3\lib\site-packages\keras\saving\legacy\save.py:24
22 from keras.saving.legacy import serialization
23 from keras.saving.legacy.saved_model import load as saved_model_load
---> 24 from keras.saving.legacy.saved_model import load_context
25 from keras.saving.legacy.saved_model import save as saved_model_save
26 from keras.utils import traceback_utils
File ~\anaconda3\lib\site-packages\keras\saving\legacy\saved_model\load_context.py:68
64 """Returns whether under a load context."""
65 return _load_context.in_load_context()
---> 68 tf.__internal__.register_load_context_function(in_load_context)
AttributeError: module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function'
I am expecting such explanation which can easily be understood and even a beginner can interpret the solution.
You have an incompatible version of keras installed.
Uninstall it with pip uninstall keras and try again.
The Keras API is available within Tensorflow itself if you need it; from tensorflow import keras.
After hours of searching and trial and error, I finally decided to ask you guys for help.
As I'm trying to call some functions from a .NET 6 open source project from python, I installed python3.8.4 on my raspberry pi and managed to install the pythonnet 3.0.0 module.
my app.runtime.json is the following:
{
"runtimeOptions": {
"tfm": "net6.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "6.0.102"
}
}
}
and when I try to load the CLR like this:
from clr_loader import get_coreclr
from pythonnet import set_runtime
rt = get_coreclr("app.runtime.json")
set_runtime(rt)
import sys
I get the following error message:
RuntimeError Traceback (most recent call
last) Input In [11], in
1 from clr_loader import get_coreclr
2 from pythonnet import set_runtime
----> 4 rt = get_coreclr("app.runtime.json")
5 set_runtime(rt)
6 import sys
File ~/.local/lib/python3.8/site-packages/clr_loader/init.py:42,
in get_coreclr(runtime_config, dotnet_root, properties)
39 from .hostfxr import DotnetCoreRuntime
41 if dotnet_root is None:
---> 42 dotnet_root = find_dotnet_root()
44 impl = DotnetCoreRuntime(runtime_config=runtime_config, dotnet_root=dotnet_root)
45 if properties:
File ~/.local/lib/python3.8/site-packages/clr_loader/util/find.py:22,
in find_dotnet_root()
20 dotnet_path = shutil.which("dotnet")
21 if not dotnet_path:
---> 22 raise RuntimeError("Can not determine dotnet root")
24 try:
25 # Pypy does not provide os.readlink right now
26 if hasattr(os, "readlink"):
RuntimeError: Can not determine dotnet root
I exported the path to my dotnet 6.0 sdk to PATH and when I use "dotnet --version" it prints out 6.0.102.
What can I possibly have done wrong?
Thanks in advance,
Epi
I am trying to do a regular import in Google Colab.
This import worked up until now.
If I try:
import plotly.express as px
or
import pingouin as pg
I get an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-86e89bd44552> in <module>()
----> 1 import plotly.express as px
9 frames
/usr/local/lib/python3.7/dist-packages/plotly/express/__init__.py in <module>()
13 )
14
---> 15 from ._imshow import imshow
16 from ._chart_types import ( # noqa: F401
17 scatter,
/usr/local/lib/python3.7/dist-packages/plotly/express/_imshow.py in <module>()
9
10 try:
---> 11 import xarray
12
13 xarray_imported = True
/usr/local/lib/python3.7/dist-packages/xarray/__init__.py in <module>()
1 import pkg_resources
2
----> 3 from . import testing, tutorial, ufuncs
4 from .backends.api import (
5 load_dataarray,
/usr/local/lib/python3.7/dist-packages/xarray/tutorial.py in <module>()
11 import numpy as np
12
---> 13 from .backends.api import open_dataset as _open_dataset
14 from .backends.rasterio_ import open_rasterio as _open_rasterio
15 from .core.dataarray import DataArray
/usr/local/lib/python3.7/dist-packages/xarray/backends/__init__.py in <module>()
4 formats. They should not be used directly, but rather through Dataset objects.
5
----> 6 from .cfgrib_ import CfGribDataStore
7 from .common import AbstractDataStore, BackendArray, BackendEntrypoint
8 from .file_manager import CachingFileManager, DummyFileManager, FileManager
/usr/local/lib/python3.7/dist-packages/xarray/backends/cfgrib_.py in <module>()
14 _normalize_path,
15 )
---> 16 from .locks import SerializableLock, ensure_lock
17 from .store import StoreBackendEntrypoint
18
/usr/local/lib/python3.7/dist-packages/xarray/backends/locks.py in <module>()
11
12 try:
---> 13 from dask.distributed import Lock as DistributedLock
14 except ImportError:
15 DistributedLock = None
/usr/local/lib/python3.7/dist-packages/dask/distributed.py in <module>()
1 # flake8: noqa
2 try:
----> 3 from distributed import *
4 except ImportError:
5 msg = (
/usr/local/lib/python3.7/dist-packages/distributed/__init__.py in <module>()
1 from __future__ import print_function, division, absolute_import
2
----> 3 from . import config
4 from dask.config import config
5 from .actor import Actor, ActorFuture
/usr/local/lib/python3.7/dist-packages/distributed/config.py in <module>()
18
19 with open(fn) as f:
---> 20 defaults = yaml.load(f)
21
22 dask.config.update_defaults(defaults)
TypeError: load() missing 1 required positional argument: 'Loader'
I think it might be a problem with Google Colab or some basic utility package that has been updated, but I can not find a way to solve it.
Now, the load() function requires parameter loader=Loader.
If your YAML file contains just simple YAML (str, int, lists), try to use yaml.safe_load() instead of yaml.load().
And If you need FullLoader, you can use yaml.full_load().
Starting from pyyaml>=5.4, it doesn't have any discovered critical vulnerabilities, pyyaml status.
source: https://stackoverflow.com/a/1774043/13755823
yaml.safe_load() should always be preferred unless you explicitly need
the arbitrary object serialization/deserialization provided in order
to avoid introducing the possibility for arbitrary code execution.
More about yaml.load(input) here.
Found the problem.
I was installing pandas_profiling, and this package updated pyyaml to version 6.0 which is not compatible with the current way Google Colab imports packages.
So just reverting back to pyyaml version 5.4.1 solved the problem.
For more information check versions of pyyaml here.
See this issue and formal answers in GitHub
##################################################################
For reverting back to pyyaml version 5.4.1 in your code, add the next line at the end of your packages installations:
!pip install pyyaml==5.4.1
It is important to put it at the end of the installation, some of the installations will change the pyyaml version.
this worked for me
config = yaml.load(ymlfile, Loader=yaml.Loader)
The Python "TypeError: load() missing 1 required positional argument: 'Loader'" occurs when we use the yaml.load() method without specifying the Loader keyword argument.
To solve the error, use the yaml.full_load() method instead or explicitly set the Loader keyword arg.
config = yaml.full_load(ymlfile)
or
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
my version of python is 3.6.9
and I tried install many versions of google-cloud-pubsub
2.1.0
1.5.0
1.3.0 .....
but I still have problem import
" "
the error message is
""" from google.cloud import pubsub_v1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-5ae969a9c485> in <module>
----> 1 from google.cloud import pubsub_v1
~\AppData\Local\Continuum\anaconda3\envs\jb\lib\site-packages\google\cloud\pubsub_v1\__init__.py in <module>
15 from __future__ import absolute_import
16
---> 17 from google.cloud.pubsub_v1 import types
18 from google.cloud.pubsub_v1 import publisher
19 from google.cloud.pubsub_v1 import subscriber
~\AppData\Local\Continuum\anaconda3\envs\jb\lib\site-packages\google\cloud\pubsub_v1\types.py in <module>
17 import sys
18
---> 19 from google.api import http_pb2
20 from google.iam.v1 import iam_policy_pb2
21 from google.iam.v1 import policy_pb2
~\AppData\Local\Continuum\anaconda3\envs\jb\lib\site-packages\google\api\http_pb2.py in <module>
33 syntax="proto3",
34 serialized_options=b"\n\016com.google.apiB\tHttpProtoP\001ZAgoogle.golang.org/genproto/googleapis/api/annotations;annotations\370\001\001\242\002\004GAPI",
---> 35 serialized_pb=b'\n\x15google/api/http.proto\x12\ngoogle.api"T\n\x04Http\x12#\n\x05rules\x18\x01 \x03(\x0b\x32\x14.google.api.HttpRule\x12\'\n\x1f\x66ully_decode_reserved_expansion\x18\x02 \x01(\x08"\x81\x02\n\x08HttpRule\x12\x10\n\x08selector\x18\x01 \x01(\t\x12\r\n\x03get\x18\x02 \x01(\tH\x00\x12\r\n\x03put\x18\x03 \x01(\tH\x00\x12\x0e\n\x04post\x18\x04 \x01(\tH\x00\x12\x10\n\x06\x64\x65lete\x18\x05 \x01(\tH\x00\x12\x0f\n\x05patch\x18\x06 \x01(\tH\x00\x12/\n\x06\x63ustom\x18\x08 \x01(\x0b\x32\x1d.google.api.CustomHttpPatternH\x00\x12\x0c\n\x04\x62ody\x18\x07 \x01(\t\x12\x15\n\rresponse_body\x18\x0c \x01(\t\x12\x31\n\x13\x61\x64\x64itional_bindings\x18\x0b \x03(\x0b\x32\x14.google.api.HttpRuleB\t\n\x07pattern"/\n\x11\x43ustomHttpPattern\x12\x0c\n\x04kind\x18\x01 \x01(\t\x12\x0c\n\x04path\x18\x02 \x01(\tBj\n\x0e\x63om.google.apiB\tHttpProtoP\x01ZAgoogle.golang.org/genproto/googleapis/api/annotations;annotations\xf8\x01\x01\xa2\x02\x04GAPIb\x06proto3',
36 )
37
TypeError: __init__() got an unexpected keyword argument 'serialized_options'
"""
I tried change version of protobuf, but i could not solve this problem...
how to fix this issue???
Please help me...
...for current user? for all users?
I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more portable approaches?
OUR_STARTMENU = os.environ['ALLUSERSPROFILE'] + '\Start Menu\Programs\Our Stuff'
thank you
I've heard of 2 ways of doing this. First:
from win32com.shell import shell
shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_COMMON_STARTMENU)
Second, using the WScript.Shell object (source : http://www.mail-archive.com/python-win32#python.org/msg00992.html):
import win32com.client
objShell = win32com.client.Dispatch("WScript.Shell")
allUserProgramsMenu = objShell.SpecialFolders("AllUsersPrograms")
userMenu = objShell.SpecialFolders("StartMenu")
Another source: http://blogs.msdn.com/saveenr/archive/2005/12/28/creating-a-start-menu-shortcut-with-powershell-and-python.aspx
Also, CSIDL_COMMON_STARTMENU is for all user startup and CSIDL_STARTMENU for current user startup.
A friend, Luke Pinner of Environment.gov.au, gave a solution by email which uses a core module (python 2.5+). Believed to be multi-lingual as the return from the API call is unicode. Tested on Win7 with Japanese locale, and on another us-english machine by manually changing Start Menu to point to %USERPROFILE%\Startmenü
''' Get windows special folders without pythonwin
Example:
import specialfolders
start_programs = specialfolders.get(specialfolders.PROGRAMS)
Code is public domain, do with it what you will.
Luke Pinner - Environment.gov.au, 2010 February 10
'''
#Imports use _syntax to mask them from autocomplete IDE's
import ctypes as _ctypes
from ctypes.wintypes import HWND as _HWND, HANDLE as _HANDLE,DWORD as _DWORD,LPCWSTR as _LPCWSTR,MAX_PATH as _MAX_PATH, create_unicode_buffer as _cub
_SHGetFolderPath = _ctypes.windll.shell32.SHGetFolderPathW
#public special folder constants
DESKTOP= 0
PROGRAMS= 2
MYDOCUMENTS= 5
FAVORITES= 6
STARTUP= 7
RECENT= 8
SENDTO= 9
STARTMENU= 11
MYMUSIC= 13
MYVIDEOS= 14
NETHOOD= 19
FONTS= 20
TEMPLATES= 21
ALLUSERSSTARTMENU= 22
ALLUSERSPROGRAMS= 23
ALLUSERSSTARTUP= 24
ALLUSERSDESKTOP= 25
APPLICATIONDATA= 26
PRINTHOOD= 27
LOCALSETTINGSAPPLICATIONDATA= 28
ALLUSERSFAVORITES= 31
LOCALSETTINGSTEMPORARYINTERNETFILES=32
COOKIES= 33
LOCALSETTINGSHISTORY= 34
ALLUSERSAPPLICATIONDATA= 35
def get(intFolder):
_SHGetFolderPath.argtypes = [_HWND, _ctypes.c_int, _HANDLE, _DWORD, _LPCWSTR]
auPathBuffer = _cub(_MAX_PATH)
exit_code=_SHGetFolderPath(0, intFolder, 0, 0, auPathBuffer)
return auPathBuffer.value