PHP加密和Windows解密

时间:2012-09-28 17:09:30

标签: php c++ encryption aes

我被困住了。似乎PHP完成的AES加密无法在Windows中解密。

PHP代码:

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,"12345678", "test", MCRYPT_MODE_CBC));

Windows代码: “s”具有从base64转换回来后由上述响应创建的字符串。

bool Decrypt(char* s,char* key,char* dest)
{
// Create the crypto provider context.
HCRYPTPROV hProvider = NULL;
if (!CryptAcquireContext(&hProvider,
    NULL,  // pszContainer = no named container
    MS_ENH_RSA_AES_PROV,  // pszProvider = default provider
    PROV_RSA_AES,
    0)) 
        return false;


// Construct the blob necessary for the key generation.
aes128keyBlob aes_blob128;

aes_blob128.header.bType = PLAINTEXTKEYBLOB;
aes_blob128.header.bVersion = CUR_BLOB_VERSION;
aes_blob128.header.reserved = 0;
aes_blob128.header.aiKeyAlg = CALG_AES_128;
aes_blob128.keySize = 16;
memcpy(aes_blob128.bytes, key, 16);

HCRYPTKEY hKey = NULL;
if (!CryptImportKey(hProvider,
    (BYTE*)(&aes_blob128),
    sizeof(aes_blob128),
    NULL,  // 
    0,     // 
    &hKey)) {

        ...
    }


// Set Mode
DWORD dwMode = CRYPT_MODE_CBC;
CryptSetKeyParam( hKey, KP_MODE, (BYTE*)&dwMode, 0 );


DWORD length = 16;
BOOL X = CryptDecrypt(hKey,
    NULL,  // hHash = no hash
    TRUE,  // Final
    0,
    (BYTE*)s,
    &length);
//int le = GetLastError();
memcpy(dest,s,16);

CryptDestroyKey(hKey);
CryptReleaseContext(hProvider, 0);
}

可能出现什么问题?

3 个答案:

答案 0 :(得分:9)

您提供的信息不足以确定,但我认为您的问题是密钥长度。

在PHP代码中,您传递“12345678”作为密钥。 AES128的密钥长度为128位或16字节。 如 mcrypt_encrypt 上的文档中所述,PHP使用零字节填充剩余部分。

在C ++代码中,只将指向密钥缓冲区的指针传递给Decrypt函数。但是然后你将16个字节从它复制到密钥BLOB:

aes_blob128.keySize = 16;
memcpy(aes_blob128.bytes, key, 16);

然后,如果你将你的功能称为:

char dest[16];
bool result = Decrypt(string_from_php,"12345678",dest);

“12345678”常量复制到密钥blob并作为实际密钥传递给 CryptImportKey 后,发生驻留在内存中的8个字节。因此,C代码和PHP代码中的密钥实际上是不同的,并且由于填充错误,解密将失败。

答案 1 :(得分:1)

PHP MCRYPT函数与Windows解密函数略有不同。

因为mcrypt函数接受任意长度的密钥并通过在密钥字符串末尾添加\0将其转换为算法所需的长度。

请注意创建一个具有双方算法加密所需的指定长度的密钥。

在密钥上使用md5,然后将其转换为算法所需的长度。

答案 2 :(得分:0)

请参阅以下网址

Encrypt in PHP, Decrypt in C# (WP7 / Silverlight) using AES / Rijndael

http://pumka.net/2009/12/16/rsa-encryption-cplusplus-delphi-cryptoapi-php-openssl-2/

http://www.developer.nokia.com/Community/Wiki/Encrypt-Decrypt_contacts_database_entries_using_Symbian_C%2B%2B

阅读

我将MD5废话从PHP和C#中删除,现在它们正常工作。

万一你在这里寻找相同的答案,这里是一个示例代码。不要忘记制作自己的钥匙和iv(虽然那些波纹管可以使用,但不建议使用!)

<强> PHP:

function encrypt128($message) {

    $vector = "0000000000000000";
    $key = "00000000000000000000000000000000";

    $block = mcrypt_get_block_size('rijndael_128', 'cbc');
    $pad = $block - (strlen($message) % $block);
    $message .= str_repeat(chr($pad), $pad);

    $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
    mcrypt_generic_init($cipher, $key, $vector);
    $result = mcrypt_generic($cipher, $message);
    mcrypt_generic_deinit($cipher);

    return base64_encode($result);
}

<强> C ++

使用Symbian C ++加密 - 解密联系数据库条目

http://www.developer.nokia.com/Community/Wiki/Encrypt-Decrypt_contacts_database_entries_using_Symbian_C%2B%2B

标题必填:

#include <cntdb.h> // CContactDatabse, 
#include <cntitem.h> //CContactItem,CContactItemFieldSet

http://www.developer.nokia.com/Community/Wiki/Encrypt-Decrypt_contacts_database_entries_using_Symbian_C%2B%2B

加密联系人字段

void CEncryptContactContainer::EncryptAll()
{
    CContactDatabase *contactDB = CContactDatabase::OpenL();
    CleanupStack::PushL(contactDB);

    TContactIter iter(*contactDB);
    TContactItemId aContactId;

//Developer can take Heap based descriptor for large/unknown size of contact items.
    TBuf16<70> aValue; 

    const CContactIdArray* contactArray = contactDB->SortedItemsL();

    TInt cnt=contactArray->Count();

    for(TInt i=0;i<cnt;i++)
    {
        CContactItem* contactItem=NULL;

        contactItem= contactDB->OpenContactL((*contactArray)[i]);
        CleanupStack::PushL(contactItem);

        CContactItemFieldSet& fieldSet= contactItem->CardFields();
        TInt fieldCount=fieldSet.Count(); // This will give number of contact fields.

        for(TInt index=0; index < fieldCount; index++)
        {
            CContactItemField& field = fieldSet[index];
            const CContentType& type = field.ContentType();
            if(!(type.ContainsFieldType(KUidContactFieldBirthday)))
            {
                TPtrC name = contactItem->CardFields()[index].TextStorage()->Text();
                aValue.Copy(name);
                Encrypt(aValue); // Call real encyption here
                contactItem->CardFields()[index].TextStorage()->SetTextL(aValue);
            }
        } //Inner for loop ends here
        contactDB->CommitContactL(*contactItem);
        CleanupStack::PopAndDestroy(contactItem);
    } //Outer for loop ends here
    CleanupStack::PopAndDestroy(contactDB);
}

void CEncryptContactContainer:: Encrypt (TDes& aValue)
{
    for(TInt iCount=0; iCount< aValue.Length();iCount++)
    {
        aValue[iCount]+=3;
    }
}

解密联系人字段

void CEncryptContactContainer::DecryptAll()
{
    CContactDatabase *contactDB = CContactDatabase::OpenL();
    CleanupStack::PushL(contactDB);

    TContactIter iter(*contactDB);
    TContactItemId aContactId;
    TBuf16<70> aValue;

    const CContactIdArray* contactArray = contactDB->SortedItemsL();

    TInt cnt=contactArray->Count();

    for(TInt i=0;i<cnt;i++)
    {
        CContactItem* contactItem=NULL;

        contactItem= contactDB->OpenContactL((*contactArray)[i]);
        CleanupStack::PushL(contactItem);

        CContactItemFieldSet& fieldSet= contactItem->CardFields();
        TInt fieldCount=fieldSet.Count(); // This will give number of contact fields.

        for(TInt index=0; index < fieldCount; index++)
        {
            CContactItemField& field = fieldSet[index];
            const CContentType& type = field.ContentType();
            if(!(type.ContainsFieldType(KUidContactFieldBirthday)))
            {
                TPtrC name = contactItem->CardFields()[index].TextStorage()->Text();
                aValue.Copy(name);
                Decrypt(aValue);
                contactItem->CardFields()[index].TextStorage()->SetTextL(aValue);
            }
        } //Inner for loop ends here
        contactDB->CommitContactL(*contactItem);
        CleanupStack::PopAndDestroy(contactItem);
    } //Outer for loop ends here
    CleanupStack::PopAndDestroy(contactDB);
}

void CEncryptContactContainer:: Decrypt (TDes& aValue)
{
    for(TInt iCount=0; iCount< aValue.Length();iCount++)
    {
        aValue[iCount]-=3;
    }
}

<强> C#:

byte[] cripted = EncryptStringToBytes("Test", System.Text.Encoding.UTF8.GetBytes("00000000000000000000000000000000"), System.Text.Encoding.UTF8.GetBytes("0000000000000000"));