2017-08-02 38 views
0

我使用2010 VisualStdio。C++ mbstowcs_s功能retsize有時在Windows 7</p> <p>我想用函數和解密作爲<code>TCHAR*</code>的顯示結果來解密密碼返回輸入長度+ 1

實施這裏,

#include <windows.h> 
#include <stdio.h> 
#include <stdlib.h> 

char* _decrypt_password_v1(const char* strPassword); 
char Hash_v1(const char chhash, int nIndex); 

#define VIT_PASSWORD _decrypt_password_v1("OOWIEJFOISJDFNPPAJ") 

char* _decrypt_password_v1(const char* strPassword) 
{ 
    unsigned int i = 0; 
    char* strDecrypt = (char*)malloc(strlen(strPassword) + 1); 
    memset(strDecrypt, 0x00, strlen(strPassword) + 1); 
    int nLen = strlen(strPassword) -1; 
    for (int i = 0; i < nLen; i++) 
    { 
     strDecrypt[i] = Hash_v1(strPassword[nLen - i], nLen - 1); 
    } 

    strDecrypt[i] = NULL; 

    return strDecrypt; 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    TCHAR szPassword[MAX_PATH] = {0}; 
    int nLen = strlen(VIT_PASSWORD); 
    _tprintf(_T("Input Password Len : %d\n"), nLen); 

    size_t outSize; 
    mbstowcs_s(&outSize, szPassword, strlen(VIT_PASSWORD), VIT_PASSWORD, strlen(VIT_PASSWORD)); 

    _tprintf(_T("Password : %s\n"), szPassword); 

    return 0; 
} 

如果我運行這段代碼,我會得到一個錯誤

調試斷言失敗!

文件:F:\ DD \ vctools \ crt_bld \ self_x86 \ CRT \ SRC \ mbstowcs.c

線:283

表達:retsize < = sizeInWords

所以,我增加參數3的mbstowcs_sstrlen(VIT_PASSWORD) + 1

更正代碼:

mbstowcs_s(&outSize, szPassword, strlen(VIT_PASSWORD) + 1, VIT_PASSWORD, strlen(VIT_PASSWORD)); 

然後沒有死機和運行正常,但sizeInWordsstrlen(VIT_PASSWORD),不strlen(VIT_PASSWORD) + 1

如果我用mbstowcs來代替,那就沒有錯誤。像這樣mbstowcs(szPassword, VIT_PASSWORD, strlen(VIT_PASSWORD));

爲什麼會發生這種情況?如果答案不明確,我必須以這種方式修改整個代碼的這部分內容。

我需要具體的答案。

回答

1

mbtowcs_s的第三個參數應該是緩衝區的大小指向的第二個參數wchar_t S,所以你的情況應該是MAX_PATH

mbtowcs_s的目的是確保您不會向目標寫入比您有空間更多的字符。這就是第三個參數:告訴它你有多少空間。在這種情況下,如果VIT_PASSWORD中沒有非ASCII字符,則目標將需要相同數量的wchar_t s來保存轉換後的字符串。因此,如果VIT_PASSWORD的長度爲4個字符,加上nul終止符,那麼mbtowcs_s的第三個參數將需要至少爲5才能成功轉換字符串(4個字符加上nul終結符)。問題是strlen(VIT_PASSWORD)將返回4,而不是5,因爲它不計數nul終結符。

+0

謝謝。問題是非ASCII。 –