1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

秘密鍵公開鍵方式RSA暗号化

Last updated at Posted at 2023-11-10

OpenSSL使って暗号化するプログラム書いた事がなかったので何と無く書いてみました。
Pythonでcryptographyを利用しています。
秘密鍵と公開鍵はコメントに書いてある感じでサクッと作ればOK

import json
from datetime import datetime

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding

# 次のコマンドで秘密鍵と公開鍵を生成
# $ openssl genrsa 2024 > private.key
# $ openssl rsa -pubout < private.key > public.key

# 秘密鍵
with open("private.key", "rb") as f:
    private_pem = f.read()
    private_key = serialization.load_pem_private_key(private_pem, password=None)

# 公開鍵
with open("public.key", "rb") as f:
    public_pem = f.read()
    public_key = serialization.load_pem_public_key(public_pem)

# 現在の時刻
dt_now = datetime.now()

# データを用意する
data_json_txt = json.dumps({
    'date': dt_now.isoformat(),
    'body': "Hello world!",
})

# 暗号化
ciphertext = public_key.encrypt(
    data_json_txt.encode(),
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# データの復号化
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

print(ciphertext)
print(plaintext.decode())

できたはず!

以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?