Вызов CryptProtectData в Python, а затем вызов CryptUnprotectData в C++ возвращает ошибку 87 (и наоборот)

Использование Python 3.11.0 и C++ в Unreal Engine 5.1

Я шифрую пользовательский ввод с помощью DPAPI в Python (3.11.0) и расшифровываю его с помощью C++ (UE 5.1), но получаю ошибку 87 (которая, как мне кажется, является недопустимым параметром?) при запуске CryptUnprotectData в C++. То же самое я получаю, если запускаю Protect from C++ и Unprotect from Python, НО все работает, если я выполняю обе операции из одного и того же места, т.е. оба из C++ или оба из Python.

Код Python:

      # DPAPI access library
# This file uses code originally created by Crusher Joe:
# http://article.gmane.org/gmane.comp.python.ctypes/420
# And modified by Wayne Koorts:
# http://stackoverflow.com/questions/463832/using-dpapi-with-python

from ctypes import *
from ctypes.wintypes import DWORD
from getpass import getpass
import os

##

LocalFree = windll.kernel32.LocalFree
memcpy = cdll.msvcrt.memcpy
CryptProtectData = windll.crypt32.CryptProtectData
CryptUnprotectData = windll.crypt32.CryptUnprotectData


my_dir = 'C:\\Users\\User\\Desktop\\PythonCrypt'
file_name = 'EncryptedToken.txt'
encrypted_file_path = os.path.join(my_dir, file_name)


class DATA_BLOB(Structure):
    _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))]


def getData(blobOut):
    cbData = int(blobOut.cbData)
    pbData = blobOut.pbData
    buffer = c_buffer(cbData)
    memcpy(buffer, pbData, cbData)
    LocalFree(pbData)
    return buffer.raw


def Win32CryptProtectData(plainText):
    bufferIn = c_buffer(plainText, len(plainText))
    blobIn = DATA_BLOB(len(plainText), bufferIn)
    blobOut = DATA_BLOB()

    if CryptProtectData(byref(blobIn), None, None, None, None, 0, byref(blobOut)):
        return getData(blobOut)
    else:
        print("CryptProtectData failed, Error:  " + str(GetLastError()))
        print("Returning an empty string")
        return ""


def Win32CryptUnprotectData(cipherText):
    bufferIn = c_buffer(cipherText, len(cipherText))
    blobIn = DATA_BLOB(len(cipherText), bufferIn)
    blobOut = DATA_BLOB()

    if CryptUnprotectData(byref(blobIn), None, None, None, None, 0, byref(blobOut)):
        print("CryptUnprotectData successful")
        return getData(blobOut)
    else:
        print("CryptUnprotectData failed, Error:  " + str(GetLastError()))
        print("Returning an empty string")
        return ""


# Encrypts bytes and saves to file
def cryptData(file_path, text_bytes):
    WriteBytesToFile(file_path, Win32CryptProtectData(text_bytes))


# Reads byte file and returns decrypted bytes
def decryptData(file_path):
    readFile = ReadBytesFromFile(file_path)
    return Win32CryptUnprotectData(readFile)


def WriteBytesToFile(file_path, bytes_to_write):
    with open(file_path, "wb") as wf:
        wf.write(bytes_to_write)


def ReadBytesFromFile(file_path):
    with open(file_path, "rb") as rf:
        return rf.read()


if __name__ == '__main__':
    # Prompt user for string password
    Password = getpass("Enter your password: ")

    # Convert string to bytes, and encrypt
    cryptData(encrypted_file_path, bytes(Password, 'utf-8'))

Код Unreal C++:

  • XLOG — это макрос, используемый для ведения журнала вместо UE_LOG.
  • Я включил Encrypt только для полноты картины, но шифрование не будет выполняться на C++. Будет запущена только Decrypt().
      #define ENCRYPTED_TOKEN_FILE_NAME TEXT("EncryptedToken.txt")

bool CryptUtil::Encrypt(FString InString)
{
    // Encrypt data from DATA_BLOB DataIn to DATA_BLOB DataOut
    DATA_BLOB DataIn, DataOut;
    TArray<uint8> Data;
    const int32 Size = InString.Len();
    Data.AddUninitialized(Size);

    // Create entropy data blob
    DATA_BLOB entropyBlob;

    // Convert FString to BYTE
    StringToBytes(*InString, Data.GetData(), Size);

    // Declare and initialize the DataIn structure
    BYTE* PbDataInput = Data.GetData();
    const DWORD CBDataInput = Size;
    DataIn.pbData = PbDataInput;
    DataIn.cbData = CBDataInput;

    // Begin protect phase
    if (CryptProtectData(
        &DataIn,        // Unencrypted data in
        nullptr,        // Optional description string
        nullptr,        // Optional entropy
        nullptr,        // Reserved
        nullptr,        // Optional prompt struct
        0,                  // Flags
        &DataOut))      // Encrypted data out
    {
        // If we're saving a new token, delete any existing encrypted files
        const FString TokenFile = GetEncryptedTokenFile();
        if (!TokenFile.IsEmpty())
        {
            if (FPaths::ValidatePath(TokenFile) && FPaths::FileExists(TokenFile))
            {
                IFileManager& FileManager = IFileManager::Get();
                FileManager.Delete(*TokenFile);
            }
        }

        // Convert from FString
        const char* EncryptedTokenFile = StringCast<ANSICHAR>(*TokenFile).Get();

        // Write encrypted data out to file
        std::ofstream EncryptedFile(EncryptedTokenFile, std::ios::out | std::ios::binary);
        EncryptedFile.write(reinterpret_cast<char*>(&DataOut.cbData), sizeof(DataOut.cbData));
        EncryptedFile.write(reinterpret_cast<char*>(DataOut.pbData), DataOut.cbData);
        EncryptedFile.close();

        // Release memory
        SecureZeroMemory(DataOut.pbData, DataOut.cbData);
        LocalFree(DataOut.pbData);
    }
    else
    {
        XLOG(LogConsoleResponse, Error, TEXT("Encryption error using CryptProtectData."));
        return false;
    }

    return true;
}

bool CryptUtil::Decrypt(FString& OutString)
{
    // Decrypt data from DATA_BLOB DataIn to DATA_BLOB DataOut
    DATA_BLOB DataIn, DataOut;

    // Create entropy data blob
    DATA_BLOB entropyBlob;

    // Convert from FString
    const char* EncryptedTokenFile = StringCast<ANSICHAR>(*GetEncryptedTokenFile()).Get();

    std::ifstream ReadEncryptedFile(EncryptedTokenFile, std::ios::in | std::ios::binary);
    if (!ReadEncryptedFile.is_open())
    {
        XLOG(LogConsoleResponse, Error, TEXT("Cannot open {%s}."), *GetEncryptedTokenFile());
        return false;
    }

    // Read encrypted data from file
    ReadEncryptedFile.read(reinterpret_cast<char*>(&DataIn.cbData), sizeof(DataIn.cbData));
    DataIn.pbData = new BYTE[DataIn.cbData];
    ReadEncryptedFile.read(reinterpret_cast<char*>(DataIn.pbData), DataIn.cbData);

    // Begin unprotect phase.
    if (CryptUnprotectData(
        &DataIn,        // Encrypted data in
        nullptr,        // Optional description string
        nullptr,        // Optional entropy
        nullptr,        // Reserved
        nullptr,        // Optional prompt struct
        0,              // Flags
        &DataOut))      // Unncrypted data out
    {

        // Convert BYTE to FString
        OutString = BytesToString(DataOut.pbData, DataOut.cbData);
        XLOG(LogConsoleResponse, Verbose, TEXT("CryptUnprotectData was successful!"));

        // Release memory
        SecureZeroMemory(DataOut.pbData, DataOut.cbData);
        LocalFree(DataOut.pbData);
    }
    else
    {
        XLOG(LogConsoleResponse, Error, TEXT("CryptUnprotectData failed, Error: %s"), *GetLastError());
        return false;
    }

    return true;
}

FString CryptUtil::GetEncryptedTokenFile()
{
    const FString tokenFile = FPaths::Combine("C:\\Users\\User\\Desktop\\PythonCrypt", ENCRYPTED_TOKEN_FILE_NAME);
    return tokenFile;
}

Пробовал сохранить файл как строковый, а не как двоичный файл, не помогло. Пробовал шифровать и расшифровывать как на Python, так и на C++, и в каждом случае это работало. Только когда я пытаюсь выполнить первую часть из одного, а вторую часть из другого, я получаю ошибку 87.

1 ответ

Я нашел решение. Оба метода Unreal BytesToString и StringToBytes удаляют нулевые терминаторы. Я создал свои собственные функции для преобразования между FString и байтами, которые это позволяют. Это решило мою проблему.

В StringToBytes удалите + 1 изOutBytes[NumBytes] = (int8)(*CharPos + 1);и в BytesToString удалитеValue += 1;

Также используйте FileHelper для чтения зашифрованного файла вместо std::ifstream.

      TArray<uint8> EncryptedData;
const FString TokenFile = GetEncryptedTokenFile();
FFileHelper::LoadFileToArray(EncryptedData, *TokenFileFString);
Другие вопросы по тегам