wincrypt输出与其他语言不匹配

时间:2017-11-12 09:07:11

标签: c++ c winapi go wincrypt

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

wincrypt代码

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

有什么简单的我不见了吗?

0 个答案:

没有答案