簡體   English   中英

將加密消息從 php 發送到 C++ 應用程序,然后使用 CryptoPP 解密

[英]Sending encrypted message from php to a C++ App and decrypting then with CryptoPP

我正在嘗試使用需要使用 base16 十六進制編碼的AES-256-CRT發送加密消息,因為CryptoPP HexDecoder就是這樣做的,但我無法在我的 C++ 應用程序中解密加密文本我該如何解決這個問題?

PS:我正在使用 libcurl 從 c++ 發出請求。

這是代碼:

PHP 文件:

<?php

function EncryptThis($ClearTextData)
{
    $ENCRYPTION_KEY = '7D9BB722DA2DC8674E08C3D44AAE976F';
    $ENCRYPTION_IV = '37C6D22FADE22B2D924598BEE2455EFC';

    return openssl_encrypt($ClearTextData, "AES-256-CTR", $ENCRYPTION_KEY, OPENSSL_RAW_DATA, $ENCRYPTION_IV);
}

$code = 'test';
$encryptedBytes = EncryptThis($code);
echo($encryptedBytes);

PHP 回聲 Output: `]$Q

現在已經修復了,答案就是上面的代碼。 (至少對於我的問題)。 我一直在嘗試使用 CBC 模式,但它不起作用,所以我嘗試了 CRT。

我更改了文件讀取方法並添加了解密 function 只是為了檢查加密是否正常工作。

請記住,這種讀取方法不適用於大文件加密(它將整個文件讀入內存)——在這種情況下,您可能需要另一種解決方案。

這是一個非常基本的例子,不做任何虛榮檢查......

<?php
$ENCRYPTION_KEY = 'ThisIsNotMine';
$ENCRYPTION_ALGORITHM = 'AES-256-CBC';

function EncryptThis($ClearTextData)
{
    // This function encrypts the data passed into it and returns the cipher data with the IV embedded within it.
    // The initialization vector (IV) is appended to the cipher data with
    // the use of two colons serve to delimited between the two.
    global $ENCRYPTION_KEY;
    global $ENCRYPTION_ALGORITHM;
    $EncryptionKey = base64_decode($ENCRYPTION_KEY);
    $InitializationVector = openssl_random_pseudo_bytes(openssl_cipher_iv_length($ENCRYPTION_ALGORITHM));
    $EncryptedText = openssl_encrypt($ClearTextData, $ENCRYPTION_ALGORITHM, $EncryptionKey, 0, $InitializationVector);
    return base64_encode($EncryptedText . '::' . $InitializationVector);
}

function DecryptThis($CryptedTextData)
{
    // This function decrypts the data passed into it and returns the clear data
    // The initialization vector (IV) is appended to the cipher data with
    // the use of two colons serve to delimited between the two.
    global $ENCRYPTION_KEY;
    global $ENCRYPTION_ALGORITHM;
    $EncryptionKey = base64_decode($ENCRYPTION_KEY);
    list($EncryptedTextData, $InitializationVector) = explode('::', base64_decode($CryptedTextData), 2);
    $DecryptedText = openssl_decrypt($EncryptedTextData, $ENCRYPTION_ALGORITHM, $EncryptionKey, 0, $InitializationVector);
    return ($DecryptedText);
}

$path = 'file.txt';//file to send can be .exe, .dll, .txt whatever i am just trying with it.
if (file_exists($path)) {
    $code = file_get_contents($path); //Get the code to be encypted.
    $encryptedBytes = EncryptThis($code);
    echo 'encryptedBytes:' . ($encryptedBytes) . '<br>';//send the encrypted bytes to my client.
    // decryption for a simple check
    $decryptedData = DecryptThis($encryptedBytes);
    echo 'decryptedData:' . $decryptedData . '<br>';
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM