0

我一直在尝试使用 wincrypt api,但似乎无法弄清楚为什么 CryptEncrypt 的输出与 Go 等语言的输出不匹配。

密码

BYTE *inBuffer = (BYTE*)"Hello World";
HCRYPTPROV phProv = NULL;
HCRYPTKEY key = NULL;
HCRYPTHASH hHash = NULL;
DWORD len = bufLen;

BYTE password[] = "password";
DWORD passLen = strlen((char*)password);

if (!CryptAcquireContext(&phProv, NULL, NULL, PROV_RSA_FULL, 0)) {
    DWORD dwStatus = GetLastError();
    error.Fatal("CryptAcquireContext error %d", dwStatus);
}

if (!CryptCreateHash(phProv, CALG_MD5, 0, 0, &hHash)) {
    DWORD dwStatus = GetLastError();
    error.Fatal("CryptCreateHash error %d", dwStatus);
}

if (!hHash)
    error.Fatal("Hash create fail");

if (!CryptHashData(hHash, password, passLen, 0)) {
    DWORD dwStatus = GetLastError();
    error.Fatal("CryptHashData error %d", dwStatus);
}

if (!CryptDeriveKey(phProv, CALG_RC4, hHash, CRYPT_EXPORTABLE, &key)) {
    DWORD dwStatus = GetLastError();
    error.Fatal("CryptDeriveKey error %d", dwStatus);
}

if (!CryptEncrypt(key, 0, TRUE, 0, NULL, &len, 0)) {
    DWORD dwStatus = GetLastError();
    error.Fatal("CryptEncrypt error %d", dwStatus);
}

outBuffLen = len;
BYTE *cipherBlock = (BYTE*)calloc(len, sizeof(BYTE));
memcpy_s(cipherBlock, len, inBuffer, len);
if (!CryptEncrypt(key, 0, TRUE, 0, cipherBlock, &len, outBuffLen)) {
    DWORD dwStatus = GetLastError();
    error.Fatal("CryptEncrypt error %d", dwStatus);
}


CryptDestroyKey(key);
CryptReleaseContext(phProv, 0);
CryptDestroyHash(hHash);

去代码

package main

import (
    "crypto/rc4"
    "fmt"
    "log"
)

func main() {
    key := []byte("5f4dcc3b5aa765d61d8327deb882cf99")
    src := []byte("Hello World")
    c, err := rc4.NewCipher(key)
    if err != nil {
        log.Fatal(err)
    }
    dst := make([]byte, len(src))
    c.XORKeyStream(dst, src)
    for _, x := range dst {
        fmt.Printf("%02X ", x)
    }
}

如果密钥是“密码”,则输出应为:B7 90 54 62 23 1E E3 C1 13 3D CF

如果密钥是“密码”(“5f4dcc3b5aa765d61d8327deb882cf99”)的 md5 哈希,则输出应为:E4 F9 36 64 83 8A 3F 78 41 82 15

我从 wincrypt 得到的输出:a0 9d 47 51 1a 7b 32 8e 03 54 c3

我缺少一些简单的东西吗?

4

0 回答 0