RSAは公開鍵暗号の一つ
暗号文 = 平文^E mod N {E, N}が公開鍵
平文 = 暗号文^D mod N {D, N}が秘密鍵
E, D, Nを求めるには素数を使う
N = p * q
L = lmc(p – 1, q – 1) # lmcとは最小公倍数(Least Common Multiple)
1 < E < L
gcd(E,L) = 1 # gcdとは最大公約数、 E, Lは互いに素な整数
1 < D < L
(E・D) mod L = 1 # DはEとの積の余剰が1となる任意の整数
from math import gcd def lcm(p, q): return (p * q) // gcd(p, q) def generate_keys(p, q): N = p * q L = lcm(p – 1, q – 1) for i in range(2, L): if gcd(i, L) == 1: E = i break for i in range(2, L): if(E * i) % L == 1: D = i break return (E, N), (D, N) def encrypt(plain_text, public_key): E, N = public_key plain_integers = [ord(char) for char in plain_text] encrypted_integers = [pow(i, E, N) for i in plain_integers] encrypted_text = ”.join(chr(i) for i in encrypted_integers) return encrypted_text def decrypt(encrypted_text, private_key): D, N = private_key encrypted_integers = [ord(char) for char in encrypted_text] decrypted_integers = [pow(i, D, N) for i in encrypted_integers] decrypted_text = ”.join(chr(i) for i in decrypted_integers) return decrypted_text def sanitize(encrypted_text): return encrypted_text.encode(‘utf-8’, ‘replace’).decode(‘utf-8’) if __name__ == ‘__main__’: public_key, private_key = generate_keys(101, 3259) plain_text = ‘おはようございます’ encrypted_text = encrypt(plain_text, public_key) decrypted_text = decrypt(encrypted_text, private_key) print(f”’ 秘密鍵: {public_key} 公開鍵: {private_key} 平文: 「{plain_text}」 暗号文: 「{sanitize(encrypted_text)}」 平文(複合後): 「{decrypted_text}」 ”'[1:-1])
なるほど、crypto currencyは暗号通貨ってことね