简体   繁体   English

将Windows RC4 CryptDeriveKey转换为openssl的PHP

[英]Translate Windows RC4 CryptDeriveKey to PHP for openssl

This is the second component of the legacy system translation we've been trying to do. 这是我们一直在尝试的遗留系统转换的第二部分。 We have managed to match exactly the initial binary password/key that Windows ::CryptHashData generates. 我们已经设法完全匹配Windows :: CryptHashData生成的初始二进制密码/密钥。

That password/key is passed to ::CryptDeriveKey where it performs a number of steps to create the final key to be used by ::CryptEncrypt. 该密码/密钥将传递给:: CryptDeriveKey,在此执行许多步骤来创建最终的密钥,以供:: CryptEncrypt使用。 My research has led me to the CryptDeriveKey documentation where it clearly describes the steps required to derive the key for ::CryptEncrypt but so far I haven't been able to get it to decrypt the file on the PHP side. 我的研究使我进入了CryptDeriveKey文档,该文档清楚地描述了为:: CryptEncrypt导出密钥所需的步骤,但到目前为止,我还无法在PHP方面获得它来解密文件。 https://docs.microsoft.com/en-us/windows/desktop/api/wincrypt/nf-wincrypt-cryptderivekey https://docs.microsoft.com/en-us/windows/desktop/api/wincrypt/nf-wincrypt-cryptderivekey

Based on the ::CryptDeriveKey documentation there may be some additional undocumented steps for our specific legacy key size that may not be well understood. 根据:: CryptDeriveKey文档,对于我们特定的传统密钥大小,可能还有一些其他未记录的步骤,可能无法很好地理解。 The current Windows ::CryptDeriveKey is set for ZERO SALT by default which is apparently different from NO_SALT somehow. 默认情况下,当前Windows :: CryptDeriveKey设置为ZERO SALT,这显然与NO_SALT有所不同。 See salt value functionality here: https://docs.microsoft.com/en-us/windows/desktop/SecCrypto/salt-value-functionality 在此处查看盐值功能: https : //docs.microsoft.com/zh-cn/windows/desktop/SecCrypto/salt-value-functionality

The parameters on the CryptAPI for our legacy system are as follows: 我们的旧系统的CryptAPI上的参数如下:

Provider type: PROV_RSA_FULL 提供程序类型:PROV_RSA_FULL

Provider name: MS_DEF_PROV 提供程序名称:MS_DEF_PROV

Algo ID CALG_RC4 算法ID CALG_RC4

Description RC4 stream encryption algorithm 说明RC4流加密算法

Key length: 40 bits. 密钥长度:40位。

Salt length: 88 bits. 盐长:88位。 ZERO_SALT ZERO_SALT

Special Note: A 40-bit symmetric key with zero-value salt, however, is not equivalent to a 40-bit symmetric key without salt. 特别说明:然而,带有零值盐的40位对称密钥并不等同于没有盐的40位对称密钥。 For interoperability, keys must be created without salt. 为了实现互操作性,必须在不添加盐的情况下创建密钥。 This problem results from a default condition that occurs only with keys of exactly 40 bits. 此问题是由仅使用正好40位的密钥的默认情况导致的。

I'm not looking to export the key, but reproduce the process that creates the final encryption key that is passed to ::CryptEncrypt for the RC4 encryption algorithm and have it work with openssl_decrypt. 我不希望导出密钥,而是重现创建最终加密密钥的过程,该过程将最终的加密密钥传递给:: CryptEncrypt以用于RC4加密算法,并使其与openssl_decrypt一起使用。

Here is the current windows code that's working fine for encrypt. 这是当前适用于加密的Windows代码。

try {
    BOOL bSuccess;
    bSuccess = ::CryptAcquireContextA(&hCryptProv, 
                                      CE_CRYPTCONTEXT, 
                                      MS_DEF_PROV_A, 
                                      PROV_RSA_FULL, 
                                      CRYPT_MACHINE_KEYSET);

    ::CryptCreateHash(hCryptProv, 
                      CALG_MD5, 
                      0, 
                      0, 
                      &hSaveHash);

    ::CryptHashData(hSaveHash, 
                    baKeyRandom, 
                    (DWORD)sizeof(baKeyRandom), 
                    0);

    ::CryptHashData(hSaveHash, 
                    (LPBYTE)T2CW(pszSecret), 
                    (DWORD)_tcslen(pszSecret) * sizeof(WCHAR), 
                     0);

    ::CryptDeriveKey(hCryptProv, 
                     CALG_RC4, 
                     hSaveHash, 
                     0, 
                     &hCryptKey);

    // Now Encrypt the value
    BYTE * pData = NULL;
    DWORD dwSize = (DWORD)_tcslen(pszToEncrypt) * sizeof(WCHAR); 
    // will be a wide str
    DWORD dwReqdSize = dwSize;

    ::CryptEncrypt(hCryptKey, 
                   NULL, 
                   TRUE, 
                   0, 
                   (LPBYTE)NULL, 
                   &dwReqdSize, 0);

    dwReqdSize = max(dwReqdSize, dwSize);

    pData = new BYTE[dwReqdSize];

    memcpy(pData, T2CW(pszToEncrypt), dwSize);

    if (!::CryptEncrypt(hCryptKey, 
                        NULL, 
                        TRUE, 
                        0, 
                        pData, 
                        &dwSize, 
                        dwReqdSize)) {

            printf("%l\n", hCryptKey);
            printf("error during CryptEncrypt\n");
            }

    if (*pbstrEncrypted)
    ::SysFreeString(*pbstrEncrypted);
    *pbstrEncrypted = ::SysAllocStringByteLen((LPCSTR)pData, dwSize);
    delete[] pData;
    hr = S_OK;
}

Here is the PHP code that tries to replicate the ::CryptDeriveKey function as described in the documentation. 这是PHP文档,试图按照文档中的描述复制:: CryptDeriveKey函数。

Let n be the required derived key length, in bytes. 令n为所需的派生密钥长度(以字节为单位)。 The derived key is the first n bytes of the hash value after the hash computation has been completed by CryptDeriveKey. 派生密钥是CryptDeriveKey完成哈希计算之后的哈希值的前n个字节。 If the hash is not a member of the SHA-2 family and the required key is for either 3DES or AES, the key is derived as follows: 如果哈希不是SHA-2家族的成员,并且所需的密钥是3DES或AES,则密钥的导出如下:

  1. Form a 64-byte buffer by repeating the constant 0x36 64 times. 通过重复常数0x36 64次来形成64字节的缓冲区。 Let k be the length of the hash value that is represented by the input parameter hBaseData. 令k为由输入参数hBaseData表示的哈希值的长度。 Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData. 将缓冲区的前k个字节设置为使用输入参数hBaseData表示的哈希值对缓冲区的前k个字节进行XOR操作的结果。

  2. Form a 64-byte buffer by repeating the constant 0x5C 64 times. 通过重复常数0x5C 64次形成一个64字节的缓冲区。 Set the first k bytes of the buffer to the result of an XORoperation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData. 将缓冲区的前k个字节设置为缓冲区的前k个字节与由输入参数hBaseData表示的哈希值进行XOR运算的结果。

  3. Hash the result of step 1 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter. 通过使用与用于计算由hBaseData参数表示的哈希值的哈希算法相同的哈希算法来哈希步骤1的结果。

  4. Hash the result of step 2 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter. 通过使用与用于计算由hBaseData参数表示的哈希值的哈希算法相同的哈希算法来哈希步骤2的结果。

  5. Concatenate the result of step 3 with the result of step 4. 将步骤3的结果与步骤4的结果连接起来。

  6. Use the first n bytes of the result of step 5 as the derived key. 使用步骤5的结果的前n个字节作为派生密钥。

PHP Version of ::CryptDeriveKey. :: CryptDeriveKey的PHP版本。

function cryptoDeriveKey($key){

    //Put the hash key into an array
    $hashKey1 = str_split($key,2);
    $count = count($hashKey1);
    $hashKeyInt = array();

    for ($i=0; $i<$count; $i++){
        $hashKeyInt[$i] = hexdec($hashKey1[$i]);
    }
    $hashKey = $hashKeyInt;

    //Let n be the required derived key length, in bytes.  CALG_RC4 = 40 bits key or 88 salt bytes
    $n = 40/8;

    //Let k be the length of the hash value that is represented by the input parameter hBaseData
    $k = 16;

    //Step 1 Form a 64-byte buffer by repeating the constant 0x36 64 times   
    $arraya = array_fill(0, 64, 0x36);

    //Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value 
    for ($i=0; $i<$k; $i++){
        $arraya[$i] = $arraya[$i] ^ $hashKey[$i];
    }

    //Hash the result of step 1 by using the same hash algorithm as hBaseData
    $arrayPacka = pack('c*', ...$arraya);
    $hashArraya = md5($arrayPacka);

    //Put the hash string back into the array
    $hashKeyArraya = str_split($hashArraya,2);
    $count = count($hashKeyArraya);
    $hashKeyInta = array();
    for ($i=0; $i<$count; $i++){
        $hashKeyInta[$i] = hexdec($hashKeyArraya[$i]);
    }

    //Step 2 Form a 64-byte buffer by repeating the constant 0x5C 64 times. 
    $arrayb = array_fill(0, 64, 0x5C);

    //Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value
    for ($i=0; $i<$k; $i++){
        $arrayb[$i] =  $arrayb[$i] ^ $hashKey[$i];
    }

    //Hash the result of step 2 by using the same hash algorithm as hBaseData    
    $arrayPackb = pack('c*', ...$arrayb);
    $hashArrayb = md5($arrayPackb);

    //Put the hash string back into the array
    $hashKeyArrayb = str_split($hashArrayb,2);
    $count = count($hashKeyArrayb);
    $hashKeyIntb = array();
    for ($i=0; $i<$count; $i++){
        $hashKeyIntb[$i] = hexdec($hashKeyArrayb[$i]);
    }

    //Concatenate the result of step 3 with the result of step 4.
    $combined = array_merge($hashKeyInta, $hashKeyIntb);

    //Use the first n bytes of the result of step 5 as the derived key.
    $finalKey = array();
    for ($i=0; $i <$n; $i++){
        $finalKey[$i] =  $combined[$i];
    }
    $key = $finalKey;

    return $key;
}

PHP Decrypt Function PHP解密功能

function decryptRC4($encrypted, $key){
    $opts = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
    $cypher = ‘rc4-40’;
    $decrypted = openssl_decrypt($encrypted, $cypher, $key, $opts);
    return $decrypted; 
}

So here are the big questions: 因此,这里有个大问题:

Has anyone been able to successfully replicate ::CryptDeriveKey with RC4 on another system? 有没有人能够在另一个系统上使用RC4成功复制:: CryptDeriveKey?

Does anyone know what is missing from the PHP script we created that prevents it from creating the same key and decrypt the Windows CryptoAPI encrypted file with openssl_decrypt? 有谁知道我们创建的PHP脚本中缺少哪些内容,从而阻止该脚本创建相同的密钥并使用openssl_decrypt解密Windows CryptoAPI加密文件?

Where and how do we create the 88 bit zero-salt that is required for the 40bit key? 我们在哪里以及如何创建40位密钥所需的88位零盐?

What are the correct openssl_decrypt parameters that would accept this key and decrypt what was generated by ::CryptDeriveKey? 可以接受此密钥并解密:: CryptDeriveKey生成的内容的正确的openssl_decrypt参数是什么?

Yes, we know this isn't secure and its not being used for passwords or PII. 是的,我们知道这是不安全的,并且不用于密码或PII。 We would like to move away from this old and insecure method, but we need take this interim step of translating the original encryption to PHP first for interoperability with the existing deployed systems. 我们希望摆脱这种古老而又不安全的方法,但是我们需要采取此过渡步骤,首先将原始加密转换为PHP,以实现与现有已部署系统的互操作性。 Any help or guidance would be appreciated. 任何帮助或指导,将不胜感激。

Just in case anyone else wanders down this path here are the answers to all the questions above. 以防万一其他人走这条路,这里是上述所有问题的答案。

You can replicate ::CryptDeriveKey on PHP using openssl but there are some prerequisites that have to be met on the windows side first. 您可以使用openssl在PHP上复制:: CryptDeriveKey,但必须首先在Windows端满足一些先决条件。

CryptDeriveKey MUST be set to CRYPT_NO_SALT as follows: 必须将CryptDeriveKey设置为CRYPT_NO_SALT,如下所示:

::CrypeDeriveKey(hCryptProv, CALG_RC4, hSaveHash, CRYPT_NO_SALT, &hCryptKey)

This will allow you to create a key from your hash and generate a matching key in PHP that will work on openssl. 这将允许您从哈希中创建密钥,并在PHP中生成匹配密钥,该密钥可在openssl上使用。 If you don't set any salt parameters you will get a key that is created with an unknown proprietary salt algorithm that cant be matched on another system. 如果您未设置任何盐参数,则将获得由未知专有盐算法创建的密钥,该算法无法在另一个系统上匹配。

The reason that you have to set CRYPT_NO_SALT is because both the CryptAPI and openssl have proprietary salt algorithms and there is no way to get them to match. 您必须设置CRYPT_NO_SALT的原因是因为CryptAPI和openssl都拥有专有的salt算法,并且无法使它们匹配。 So you should do your salting separately. 因此,您应该分开腌制。 There are more details about this salt value functionality here: https://docs.microsoft.com/en-us/windows/desktop/SecCrypto/salt-value-functionality 这里有关于此盐值功能的更多详细信息: https : //docs.microsoft.com/zh-cn/windows/desktop/SecCrypto/salt-value-functionality

Here is what the PHP script needs to look like to create an equivalent passkey for for openssl to use. 这是PHP脚本需要创建一个等效密码以供openssl使用的样子。

<?php
$random = pack('c*', 87,194,...........);
$origSecret = 'ASCII STRING OF CHARACTERS AS PASSWORD'; 

//Need conversion to match format of Windows CString or wchar_t*
//Windows will probably be UTF-16LE and LAMP will be UTF-8
$secret = iconv('UTF-8','UTF-16LE', $origSecret);

//Create hash key from Random and Secret
//This is basically a hash and salt process.
$hash = hash_init("md5");
hash_update($hash, $random);
hash_update($hash, $secret);
$key = hash_final($hash);

$key = cryptoDeriveKey($key);
//Convert the key hex array to a hex string for openssl_decrypt
$count = count($key);
$maxchars = 2;
for ($i=0; $i<$count; $i++){
    $key .= str_pad(dechex($key[$i]), $maxchars, "0", STR_PAD_LEFT);
}

IMPORTANT: OpenSSL expects the key to be the raw hex values that are derived from the hash, unfortunately openssl_decrypt() wants the same value as a string or password. 重要说明:OpenSSL期望密钥是从哈希派生的原始十六进制值,不幸的是,openssl_decrypt()希望与字符串或密码具有相同的值。 Therefor you have to do a hex to string conversion at this point. 因此,此时您必须进行十六进制到字符串的转换。 There is a great write up here on why you have to do this. 这里有很多关于为什么必须这样做的文章。 http://php.net/manual/en/function.openssl-encrypt.php http://php.net/manual/en/function.openssl-encrypt.php

$opts = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
//Convert key hex string to a string for openssl_decrypt
//Leave it as it is for openssl command line.
$key = hexToStr($key);
$cipher = 'rc4-40';
$encrypted = “the data you want to encrypt or decrypt”;
$decrypted = openssl_decrypt($encrypted, $cipher, $key, $opts);  

echo $decrypted;  //This is the final information you’re looking for


function cryptoDeriveKey($key){
//convert the key into hex byte array as int
    $hashKey1 = str_split($key,2);
    $count = count($hashKey1);
    $hashKeyInt = array();
    for ($i=0; $i<$count; $i++){
        $hashKeyInt[$i] = hexdec($hashKey1[$i]);
    }
    $hashKey = $hashKeyInt;
    //Let n be the required derived key length, in bytes.  CALG_RC4 = 40 bits key with 88 salt bits
    $n = 40/8;
    //Chop the key down to the first 40 bits or 5 bytes.
    $finalKey = array();
    for ($i=0; $i <$n; $i++){
        $finalKey[$i] =  $hashKey[$i];
    }
    return $finalKey;
}


function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
return $string;
}
?>

If you're having trouble getting the correct values after using the code above you can try exporting your key value from CryptoAPI and testing it with openssl command line. 如果在使用上述代码后无法正确获取值,可以尝试从CryptoAPI导出密钥值并使用openssl命令行对其进行测试。

First you have to set CryptDeriveKey to allow the key to be exported with CRYPT_EXPORTABLE and CRYPT_NO_SALT 首先,您必须设置CryptDeriveKey以允许使用CRYPT_EXPORTABLE和CRYPT_NO_SALT导出密钥

::CrypeDeriveKey(hCryptProv, CALG_RC4, hSaveHash, CRYPT_EXPORTABLE | CRYPT_NO_SALT, &hCryptKey)

If you want to know how to display a PLAINTEXTKEYBLOB from the exported key follow this link. 如果您想知道如何从导出的键中显示PLAINTEXTKEYBLOB,请单击此链接。 https://docs.microsoft.com/en-us/windows/desktop/seccrypto/example-c-program--importing-a-plaintext-key https://docs.microsoft.com/en-us/windows/desktop/seccrypto/example-c-program--importing-a-plaintext-key

Here is an example exported key blob 0x08 0x02 0x00 0x00 0x01 0x68 0x00 0x00 0x05 0x00 0x00 0x00 0xAA 0xBB 0xCC 0xDD 0xEE 这是导出密钥Blob的示例0x08 0x02 0x00 0x00 0x01 0x68 0x00 0x00 0x05 0x00 0x00 0x00 0xAA 0xBB 0xCC 0xDD 0xEE

0x08 0x02 0x00 0x00 0x01 0x68 0x00 0x00 //BLOB header matches almost exactly 0x05 0x00 0x00 0x00 //Key length in bytes is correct 5 bytes 0xAA 0xBB 0xCC 0xDD 0xEE //First 5 bytes of our created hash key!! 0x08 0x02 0x00 0x00 0x01 0x68 0x00 0x00 // BLOB标头几乎完全匹配0x05 0x00 0x00 0x00 //以字节为单位的密钥长度正确5字节0xAA 0xBB 0xCC 0xDD 0xEE //我们创建的哈希密钥的前5个字节!

Use your exported key value from the BLOB as the Hex Key Value in the openssl enc command below. 在下面的openssl enc命令中,使用从BLOB导出的键值作为十六进制键值。

openssl enc -d -rc4-40 -in testFile-NO_SALT-enc.txt -out testFile-NO_SALT-dec.txt -K "Hex Key Value" -nosalt -nopad

This will decrypt the file that was encrypted on the Windows machine using CryptEncrypt. 这将解密使用CryptEncrypt在Windows计算机上加密的文件。

As you can see, when you set the CryptDeriveKey to CRYPT_NO_SALT all you need for the openssl password or key is the first “keylength” bits of your CryptHashData password. 如您所见,将CryptDeriveKey设置为CRYPT_NO_SALT时,所需的openssl密码或密钥是CryptHashData密码的第一个“密钥长度”位。 Simple enough to say but a real pain to get to. 说的很简单,但是很难理解。 Good luck and hope this helps someone else with legacy Windows translation issues. 祝您好运,并希望这对旧版Windows翻译问题有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM