密碼學 - RSA 解密



在本文中,我們必須使用不同的技術來實現 RSA 密碼的解密。如您所知,解密是在非對稱金鑰密碼學中使用私鑰將加密訊息(密文)更改回其原始形式(明文)的過程。或者我們可以說解密是找到加密訊息的原始訊息的技術。

解密步驟

我們可以使用以下步驟解密使用 RSA 加密加密的訊息:

  • 接收密文 - 接收者收到一條使用其公開金鑰加密的加密訊息(密文)。
  • 使用私鑰 - 接收者使用秘密金鑰(私鑰)來解密密文。此秘密金鑰是在特殊設定期間與公鑰一起建立的。
  • 執行解密 - 為了解密訊息,接收者使用涉及秘密金鑰和大數的複雜數學運算,有效地逆轉加密過程。這將導致原始訊息的數字表示。
  • 轉換為明文 - 然後將數字表示轉換回原始訊息內容。

Python 中的解密實現

RSA 解密可以透過以下幾種方法建立:

  • 使用模算術和數論
  • 使用 RSA 模組
  • 使用 cryptography 模組

為了幫助您更好地理解 RSA 解密、Python 程式設計和函式,我們將在下面的部分中深入討論每種方法。

使用模算術和數論

在這個程式中,我們將使用模算術和數論來解密訊息。在我們的程式碼中,decrypt() 函式將私鑰和密文訊息作為輸入。解密密文涉及將密文中每個數字提高到“d”指數指定的冪。應用“mod n”計算(一種數學運算)。使用“chr”函式將結果數字轉換回字元。組合這些字元以獲得解密的訊息(明文)。

示例

以下是使用模算術和數論進行 RSA 解密的 Python 程式:

import random

def gcd(a, b):
   while b != 0:
      a, b = b, a % b
   return a

def extended_gcd(a, b):
   if a == 0:
      return (b, 0, 1)
   else:
      g, y, x = extended_gcd(b % a, a)
      return (g, x - (b // a) * y, y)

def mod_inverse(a, m):
   g, x, y = extended_gcd(a, m)
   if g != 1:
      raise Exception('Modular inverse does not exist')
   else:
      return x % m

def generate_keypair():
   p = random.randint(100, 1000)
   q = random.randint(100, 1000)
   n = p * q
   phi = (p - 1) * (q - 1)

   while True:
      e = random.randint(2, phi - 1)
      if gcd(e, phi) == 1:
         break
    
   d = mod_inverse(e, phi)
   return ((e, n), (d, n))

def encrypt(public_key, plaintext):
   e, n = public_key
   cipher = [pow(ord(char), e, n) for char in plaintext]
   return cipher

def decrypt(private_key, ciphertext):
   d, n = private_key
   plain = [chr(pow(char, d, n)) for char in ciphertext]
   return ''.join(plain)

# our keys
public_key, private_key = generate_keypair()
# plaintext
message = "Hello, world!"
encrypted_message = encrypt(public_key, message)
print("Encrypted message:", encrypted_message)
decrypted_message = decrypt(private_key, encrypted_message)
print("Decrypted message:", decrypted_message)

以下是上述示例的輸出:

輸入/輸出

Encrypted message: [5133, 206, 9012, 9012, 7041, 3509, 7193, 3479, 7041, 6939, 9012, 1255, 3267]
Decrypted message:  Hello, world!

使用 rsa 模組

可以使用 Python 的 rsa 包輕鬆高效地實現 RSA 演算法。首先,如果您尚未安裝 rsa 模組,則可以使用 pip 安裝它 - pip install rsa。因此,我們首先需要生成金鑰,然後我們將解密加密的訊息。

生成 RSA 金鑰

安裝模組後,您可以使用此 rsa 模組生成 RSA 金鑰對。方法如下:

示例
import rsa
# create a key pair with 1024 bits key length
(public_key, private_key) = rsa.newkeys(1024)

程式碼將生成一對 RSA 金鑰:一個用於加密(公鑰),另一個用於解密(私鑰)。

解密訊息

擁有金鑰對後,您可以使用它們來解密訊息。

# Encrypting a message
message = b"Hello, world!"
encrypted_message = rsa.encrypt(message, public_key)

# Decrypting the message
decrypted_message = rsa.decrypt(encrypted_message, private_key)

print("Encrypted message:", encrypted_message)
print("Decrypted message:", decrypted_message.decode()) 

完整程式碼

以下是供您參考的 Python 程式碼。因此,執行程式碼並檢視輸出:

示例
import rsa
# create a key pair with 1024 bits key length
(public_key, private_key) = rsa.newkeys(1024)

# Encrypting a message
message = b"Hello, world!"
encrypted_message = rsa.encrypt(message, public_key)

# Decrypting the message
decrypted_message = rsa.decrypt(encrypted_message, private_key)

print("Encrypted message:", encrypted_message)
print("Decrypted message:", decrypted_message.decode())  

以下是上述示例的輸出:

輸入/輸出
Encrypted message: b'+.}a\n\xda8\x83\xf7D\x0eI\xc1\xde\x9cZ\xd7\xf2\xdd}\xb0\xd4N\x9e\x1cjm\xe3\x12\xea\x95\n8\x87a\x16Y\xb6\x7f\x9ar\xf3\xd6\xe6le\xda1\xa7{\xa1\xa4\t/q\xea\x19*q\xc5[\x87\x1b\xc0\x8f%\x83\xa1KFx\xe6m\x97\x8ef\x84\xaf\xe7\xdc\xcf\xd0\xe4\x80H!\xce\xef\x13\xc5\x93\xc3a\xc0Pv\x07tQx_\xbc\xaeQ[x:\xf3\x19\xa2\xea]\xf2\x1e\x9e9\x10\xed\xf2\x83\x15W}\xbb\x89\xd7\xf6\xee'
Decrypted message: Hello, world!

使用 cryptography 模組

使用 cryptography 模組,我們可以建立 RSA 金鑰對。此程式碼建立一個私有 RSA 金鑰並提取其對應的公鑰。金鑰轉換為 PEM 格式並儲存在不同的檔案中。我們可以使用這些金鑰來加密和解密訊息。給定的程式碼顯示瞭如何使用私鑰進行解密。

示例

以下是使用 cryptography 模組進行 RSA 解密的 Python 實現:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

# Generate an RSA private key
private_key = rsa.generate_private_key(
   public_exponent=65537,
   key_size=2048,
   backend=default_backend()
)

# Get the public key from the private key
public_key = private_key.public_key()

# Serialize the keys to PEM format
private_key_pem = private_key.private_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PrivateFormat.PKCS8,
   encryption_algorithm=serialization.NoEncryption()
)
public_key_pem = public_key.public_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PublicFormat.SubjectPublicKeyInfo
)

# Save the keys to files or use them as needed
with open('private_key.pem', 'wb') as f:
   f.write(private_key_pem)

with open('public_key.pem', 'wb') as f:
   f.write(public_key_pem)

# Encrypting a message
message = b"Hello, world!"
encrypted_message = public_key.encrypt(
   message,
   padding.OAEP(
      mgf=padding.MGF1(algorithm=hashes.SHA256()),
      algorithm=hashes.SHA256(),
      label=None
   )
)

# Decrypting the message
decrypted_message = private_key.decrypt(
   encrypted_message,
   padding.OAEP(
      mgf=padding.MGF1(algorithm=hashes.SHA256()),
      algorithm=hashes.SHA256(),
      label=None
   )
)

print("Encrypted message:", encrypted_message)
print("Decrypted message:", decrypted_message.decode())

以下是上述示例的輸出:

輸入/輸出
Encrypted message: b'\xae\xdd\xaa\x16\xd5\x9e\x06N\xf7\x96\xd6\xd6\x02\x8b\xcb\xdf\x12eds\t\x1a\xa9\xb6\xe3\xc4vZ\x05\xbe\xbf$\xef\xaa\xcfqo\xc0\x8fI\x80\xb3\xea\xb6\x04\xf8\xc6\x05\xaa\x1dH\xc1J{=\x15\xe1\xef\xcbnA\xfb\x98m.\xa7\x9c\x05\x0f\x07z\x02(\x10\xae\xaf\xccv\x8a\x8f\x97\'f-\xccFU\xf8\x188\xe7\xe5I\xcc\x88\n_\xa6w\x86\x9b\x03\xc7\x96t\xca\xdb\x102O#\x94\xd0\xbe\xba\x8d\xce\x80V*l\xb5"\xdf~\x86\xe6\xf6\x08\x18\xcf\xd8\x866\x88\xe3x\x17\xebhD\xdb\xa8\x02\xa1\xd9{\xaf~\xe4\xd7[\x9c+\xcc\t\x15\x8ej\xe2\xe5b\xdf\xeb\xd0|\x82\xea\xce,p.\xf5\xd6\x0e\x01\xb9\xcb\x17\xe6\x05\xea\xe4\xb0\xa4\xc8\x9a\xc4\x822\xd1v\x8a\xa6\x85{x\xf9\x81r\xa2S\xe1\xe7l\xccwE\x16f\x1e\xfbE\x1e\xaf|\xc3\x91\x93\x99|\x99\xba\xcf\x00\xb3D\xfaq\xc3<\x8dj\x06\\L\x06{\x10\xaf7\xfa^\xa5\x87E\xbb\x8c\x9e\xd7eU\x07\xf3lk'
Decrypted message: Hello, world!

使用 Java 實現 RSA 解密

下面的 Java 程式碼使用 RSA 加密演算法來解密給定的訊息。該程式碼使用 Java 的不同庫來解密訊息。

示例

使用 Java 實現 RSA 解密過程如下

import java.math.BigInteger;
import java.security.SecureRandom;

public class RSA {

   private BigInteger prKey;
   private BigInteger pubKey;
   private BigInteger mod;

   // Generate public and private keys
   public RSA(int bitLength) {
      SecureRandom random = new SecureRandom();
      BigInteger p = BigInteger.probablePrime(bitLength / 2, random);
      BigInteger q = BigInteger.probablePrime(bitLength / 2, random);
      mod = p.multiply(q);
      BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
      pubKey = BigInteger.probablePrime(bitLength / 4, random);
      while (phi.gcd(pubKey).intValue() > 1) {
         pubKey = pubKey.add(BigInteger.ONE);
      }
      prKey = pubKey.modInverse(phi);
   }

   // Encrypt plaintext
   public BigInteger encrypt(String message) {
      BigInteger plaintext = new BigInteger(message.getBytes());
      return plaintext.modPow(pubKey, mod);
   }

   // Decrypt ciphertext
   public String decrypt(BigInteger encryptedMessage) {
      BigInteger decrypted = encryptedMessage.modPow(prKey, mod);
      return new String(decrypted.toByteArray());
   }

   public static void main(String[] args) {
      RSA rsa = new RSA(1024);

      // Message to encrypt
      String plaintext = "HELLO TUTORIALSPOINT";

      // Encrypt the message
      BigInteger ciphertext = rsa.encrypt(plaintext);
      System.out.println("Encrypted Message: " + ciphertext);

      // Decrypt the ciphertext
      String decryptedMessage = rsa.decrypt(ciphertext);
      System.out.println("Decrypted Message: " + decryptedMessage);
   }
}

以下是上述示例的輸出:

輸入/輸出

Encrypted Message: 81613159022598431502618861082122488243352277400520456503112436392671015741839175478780136032663342240432362810242747991048788272007296529186453061811896882040496871941396445756607265971854347817972502178724652319503362063137755270102568091525122886513678255187855721468502781772407941859987159924896465083062
Decrypted Message: HELLO TUTORIALSPOINT

使用 C++ 實現 RSA 解密

下面是 RSA 演算法的一個簡單實現,它使用 C++ 的幫助來解密訊息。給定訊息解密的程式碼如下:

示例

#include<iostream>
#include<math.h>
using namespace std;
// find gcd
int gcd(int a, int b) {
   int t;
   while(1) {
      t= a%b;
      if(t==0)
      return b;
      a = b;
      b= t;
   }
}
int main() {
   //2 random prime numbers
   double p = 13;
   double q = 11;
   double n=p*q;//calculate n
   double track;
   double phi= (p-1)*(q-1);//calculate phi
   //public key
   //e stands for encrypt
   double e=7;
   //for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
   while(e<phi) {
      track = gcd(e,phi);
      if(track==1)
         break;
      else
         e++;
   }
   //private key
   //d stands for decrypt
   //choosing d such that it satisfies d*e = 1 mod phi
   double d1=1/e;
   double d=fmod(d1,phi);
   double message = 9;
   double c = pow(message,e); //encrypt the message
   double m = pow(c,d);
   c=fmod(c,n);
   m=fmod(m,n);
   cout<<"\n"<<"Encrypted message = "<<c;
   cout<<"\n"<<"Decrypted message = "<<m;
   return 0;
}

以下是上述示例的輸出:

輸入/輸出

Encrypted message = 48
Decrypted Message = 9

總結

RSA 透過建立唯一的公鑰和私鑰對來工作,從而建立安全的通訊通道。這些金鑰用於加密和解密訊息,確保只有授權使用者才能解密資訊。

在 Python 中,RSA 解密可以透過多種方法實現。使用模算術和數論,而 RSA 模組提供了更專業的的功能。cryptography 模組還支援 RSA 加密和解密,提供了一套全面的功能。開發人員可以選擇最符合其需求的方法。

我們還開發了使用 Java 和 C++ 進行 RSA 解密的程式碼。

廣告

© . All rights reserved.