thắc mắc convert code c++ sang python

ChocoTiamo

Junior Member
mất 2 ngày em chưa xong đoạn này, mong các bác hướng dẫn em:
hiện em đang sử dụng protobuf và kafka, 1 phía bắn mess vào kafka và e nhận. dữ liệu đó là 1 proto đã
encrypt , em cần decrypt, key thì em có nhưng code giải mã là c++ mà e đang dùng python , nên hiện tại em chưa biết chuyển như nào. chatgpt cũng bó tay rồi. các bác xem hộ em rồi có thể giúp đỡ em với ạ.
Code:
std::string DecryptString(std::string cipher, std::string key){
  std::string recovered;
  SecByteBlock new_iv(AES::BLOCKSIZE);
  new_iv = SecByteBlock(reinterpret_cast<const byte*>(cipher.substr(0, AES::MIN_KEYLENGTH).data()), AES::MIN_KEYLENGTH);
  try
    {
    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV((const byte*)key.c_str(), key.size(), new_iv);
    StringSource s(cipher.substr(AES::MIN_KEYLENGTH, cipher.size()), true,
        new StreamTransformationFilter(d,
            new StringSink(recovered)
        ) // StreamTransformationFilter
    ); // StringSource

    // std::cout << "recovered text: " << recovered << std::endl;
    }
  catch(const std::exception & e)
    {
    g_print("[ERROR]: from Decrypting");
    std::cerr << e.what() << std::endl;
    recovered = "";
    }

  return recovered;
}
 
mất 2 ngày em chưa xong đoạn này, mong các bác hướng dẫn em:
hiện em đang sử dụng protobuf và kafka, 1 phía bắn mess vào kafka và e nhận. dữ liệu đó là 1 proto đã
encrypt , em cần decrypt, key thì em có nhưng code giải mã là c++ mà e đang dùng python , nên hiện tại em chưa biết chuyển như nào. chatgpt cũng bó tay rồi. các bác xem hộ em rồi có thể giúp đỡ em với ạ.
Code:
std::string DecryptString(std::string cipher, std::string key){
  std::string recovered;
  SecByteBlock new_iv(AES::BLOCKSIZE);
  new_iv = SecByteBlock(reinterpret_cast<const byte*>(cipher.substr(0, AES::MIN_KEYLENGTH).data()), AES::MIN_KEYLENGTH);
  try
    {
    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV((const byte*)key.c_str(), key.size(), new_iv);
    StringSource s(cipher.substr(AES::MIN_KEYLENGTH, cipher.size()), true,
        new StreamTransformationFilter(d,
            new StringSink(recovered)
        ) // StreamTransformationFilter
    ); // StringSource

    // std::cout << "recovered text: " << recovered << std::endl;
    }
  catch(const std::exception & e)
    {
    g_print("[ERROR]: from Decrypting");
    std::cerr << e.what() << std::endl;
    recovered = "";
    }

  return recovered;
}

ChatGPT mà còn bó tay thì ai giúp bác được nữa.
 
This C++ code snippet is a function called DecryptString that takes two input parameters: cipher (a string representing the encrypted data) and key (a string representing the encryption key). The purpose of this function is to decrypt the cipher using the key and return the decrypted string.

Here's a breakdown of what the code does:

1. It creates a SecByteBlock object called new_iv, which is initialized with the first AES::MIN_KEYLENGTH bytes (16 bytes) of the cipher string. This is used as the Initialization Vector (IV) for the decryption process.

2. It then sets up a CBC_Mode<AES>::Decryption object called d and sets the key and new_iv on it.

3. The function then uses a StringSource object to read the encrypted data (starting from the AES::MIN_KEYLENGTH byte, which is the beginning of the actual ciphertext) and passes it through a StreamTransformationFilter to decrypt it. The decrypted data is stored in the recovered string.

4. If any exceptions are thrown during the decryption process, the function catches them, prints an error message, and returns an empty string.

5. Finally, the function returns the decrypted string, recovered.

In the context of the Kafka message decryption, this function is likely used to decrypt the payload of the Kafka message, which has been encrypted using AES-CBC mode with a specific key. The first 16 bytes of the message contain the IV, and the rest of the message is the ciphertext.

To convert this C++ code to Python, your friend would need to use a similar cryptographic library, such as the pycryptodome or cryptography libraries. Here's an example of how they might implement the decryption function in Python:

Python:
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

def decrypt_string(cipher_text, key):
    iv = cipher_text[:16]
    ciphertext = cipher_text[16:]

    cipher = AES.new(key.encode(), AES.MODE_CBC, iv)
    try:
        recovered = unpad(cipher.decrypt(ciphertext), AES.block_size).decode()
    except (ValueError, UnicodeDecodeError) as e:
        print(f"[ERROR]: from Decrypting: {e}")
        return ""

    return recovered

The main differences are:

1. The Python code uses the pycryptodome library instead of the C++ Crypto++ library.
2. The IV is extracted directly from the beginning of the cipher_text string, instead of using a separate SecByteBlock.
3. The AES.new() function is used to create the decryption cipher object, and the cipher.decrypt() and unpad() functions are used to decrypt the ciphertext.
4. The function returns the decrypted string, or an empty string if an exception occurs during the decryption process.
 
mất 2 ngày em chưa xong đoạn này, mong các bác hướng dẫn em:
hiện em đang sử dụng protobuf và kafka, 1 phía bắn mess vào kafka và e nhận. dữ liệu đó là 1 proto đã
encrypt , em cần decrypt, key thì em có nhưng code giải mã là c++ mà e đang dùng python , nên hiện tại em chưa biết chuyển như nào. chatgpt cũng bó tay rồi. các bác xem hộ em rồi có thể giúp đỡ em với ạ.
Code:
std::string DecryptString(std::string cipher, std::string key){
  std::string recovered;
  SecByteBlock new_iv(AES::BLOCKSIZE);
  new_iv = SecByteBlock(reinterpret_cast<const byte*>(cipher.substr(0, AES::MIN_KEYLENGTH).data()), AES::MIN_KEYLENGTH);
  try
    {
    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV((const byte*)key.c_str(), key.size(), new_iv);
    StringSource s(cipher.substr(AES::MIN_KEYLENGTH, cipher.size()), true,
        new StreamTransformationFilter(d,
            new StringSink(recovered)
        ) // StreamTransformationFilter
    ); // StringSource

    // std::cout << "recovered text: " << recovered << std::endl;
    }
  catch(const std::exception & e)
    {
    g_print("[ERROR]: from Decrypting");
    std::cerr << e.what() << std::endl;
    recovered = "";
    }

  return recovered;
}
Nó bound với cái library kia thì chịu rồi, chịu khó tìm lib tương ứng nếu có ở python rồi đọc api mà làm theo.

Hoặc tìm mấy cái lib trong script trên, dùng boost python C++ compile nó thành dynamic lib, tự viết api rồi chạy python script tương tự đoạn trên kia.
 
Last edited:
Back
Top