簡體   English   中英

使用C ++和PHP的openssl加密

[英]openssl encryption in c++ and php

我需要在c ++中編碼一些數據並在php中對其進行解碼,但是php無法正確解碼。 我檢查了使用相同的鍵和iv對相同的消息進行編碼,結果之間存在差異。 這是我的代碼:

struct ctr_state
{
    unsigned char ivec[AES_BLOCK_SIZE];
    unsigned int num;
    unsigned char ecount[AES_BLOCK_SIZE];
};
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE];

struct ctr_state state;

int init_ctr(struct ctr_state *state, const byte iv[16])
{
    /* aes_ctr128_encrypt requires 'num' and 'ecount' set to zero on the
     * first call. */
    state->num = 0;
    memset(state->ecount, 0, AES_BLOCK_SIZE);

    /* Initialise counter in 'ivec' to 0 */
    memset(state->ivec + 8, 0, 8);

    /* Copy IV into 'ivec' */
    memcpy(state->ivec, iv, 8);
}

void aes_encoder(byte *read, byte *write, int size, byte *enc_key, byte *iv)
{
    AES_KEY key;
    if (AES_set_encrypt_key(enc_key, 128, &key) < 0)
    {
       Logger::getInstance()->Error("problem with setting encrypt key");
    }
    init_ctr(&state, iv);

    AES_ctr128_encrypt(read, write, size, &key, state.ivec, state.ecount, &state.num);
}

byte *key = (byte*)"2123456789012345";
byte *iv = (byte*)"2asdasdasdasdasd";

QByteArray message = "this is message";
byte *data = reinterpret_cast<byte *>(message.data());

aes_encoder(data, data,  message.size(), key, iv);
qDebug() << message.toBase64();

結果是:“ hF / nlW4e + FmuF8Bfny9M”

和php代碼:

<?php
$message = "this is message";
$key = "2123456789012345";
$iv = "2asdasdasdasdasd";

$encrypted = openssl_encrypt($message, 'aes-128-ctr', $key, true, $iv);

echo base64_encode($encrypted);

結果:“ RLLUkP54El9FCeWpO / bI”

為什么結果不一樣?

您的問題是您沒有以標准方式使用點擊率模式。 init_ctr您僅復制了提供的IV的8個字節,並將其余字節設置為零。 相反,如果您使用整個IV,則會得到與PHP代碼相同的結果:

//don't do this:
//memset(state->ivec + 8, 0, 8);
//memcpy(state->ivec, iv, 8);  

//do this:
memcpy(state->ivec, iv, AES_BLOCK_SIZE);  

這個教訓是,僅僅因為您在某個地方找到了一些代碼,並不意味着您可以在不了解其功能的情況下進行復制-n-粘貼。 對於加密代碼尤其如此。 如果您甚至知道分組密碼是什么以及密碼在CTR模式下如何工作的基礎知識,您都將直接意識到代碼的問題。

哦,重要的安全提示:使用CTR模式時,切勿使用相同的IV加密多個消息。 否則你會死。

暫無
暫無

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

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