実現したいこと
以下のURLを参考にPythonで暗号化をしたい。
https://ittrip.xyz/python/python-cryptography-basics
発生している問題・分からないこと
pip install cryptography
上記コマンドを実行したところ以下のようになりました。
Successfully installed cryptography-42.0.7
しかし、以下の2行でエラーが発生しています。
from cryptography.hazmat.primitives import algorithms, modes, backends
from cryptography.hazmat.primitives.ciphers import Cipher
発生しているエラーは
Import "cryptography.hazmat.primitives" could not be resolved Pylance(reportMissingImports)
該当のソースコード
Python
1from cryptography.hazmat.primitives import algorithms, modes, backends 2from cryptography.hazmat.primitives.ciphers import Cipher 3import os 4 5# キーと初期化ベクトルの生成 6key = os.urandom(32) # 256ビット 7iv = os.urandom(12) # 96ビット 8 9# AESアルゴリズムの設定 10algorithm = algorithms.AES(key) 11mode = modes.GCM(iv) 12cipher = Cipher(algorithm, mode, backend=backends.default_backend()) 13 14# 暗号化 15encryptor = cipher.encryptor() 16text = "Hello, world!" 17ciphertext = encryptor.update(text.encode()) + encryptor.finalize() 18 19# 復号 20decryptor = cipher.decryptor() 21decrypted_text = decryptor.update(ciphertext) + decryptor.finalize() 22decrypted_text = decrypted_text.decode() 23print("Decrypted text:", decrypted_text) 24
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
https://teratail.com/questions/342096
↑こちらを参考にしたところ、破線は消えましたが実行時に以下のエラーが出ます。
Exception has occurred: ImportError
cannot import name 'algorithms' from 'cryptography.hazmat.primitives' (C:\Users\xxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\cryptography\hazmat\primitives_init_.py)
File "C:\Projects\crypt\1.py", line 1, in <module>
from cryptography.hazmat.primitives import algorithms, modes, backends
ImportError: cannot import name 'algorithms' from 'cryptography.hazmat.primitives' (C:\Users\xxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\cryptography\hazmat\primitives_init_.py)
補足
意味がよくわかりません。
回答1件
あなたの回答
tips
プレビュー