2014-10-09 48 views
-2

PHP代碼:將PHP代碼轉換爲C(SHA1算法)

<?php 
$pass = "12345678"; 
$salt = "1234"; 
echo sha1($salt.$pass.$salt); 
?> 

C代碼使用OpenSSL的密碼庫在使用SHA1http://www.openssl.org/docs/crypto/sha.html

#include <openssl/sha.h> 

int main() 
{ 
    const char str[] = "Original String"; 
    const char salt[] = "1234"; 
    const char pass[] = "12345678"; 
    strcat(str, salt, pass); 
    unsigned char hash[SHA_DIGEST_LENGTH]; // == 20 

    SHA1(str, sizeof(str) - 1, hash); 

    // do some stuff with the hash 

    return 0; 
} 

我的問題是,我怎麼能修改C代碼的確切同樣的事情PHP代碼? 謝謝。

+0

使用'strcat()'連接鹽? – Barmar 2014-10-09 12:36:12

+0

@Barmar我不知道C如果你能告訴我該怎麼做,我會很感激。 – xwk16479 2014-10-09 12:37:14

+3

不需要。請嘗試自己弄清楚,然後我們會幫助您修復它,如果它不起作用。這就是你學習的方式。 – Barmar 2014-10-09 12:39:20

回答

1

您需要爲字符串中的連接字符串分配足夠的空間。此外,您不能修改const char,因此請不要在要連接的變量上使用該修飾符。

char str[17] = ""; // 16 characters plus null terminator 
const char salt[] = "1234"; 
const char pass[] = "12345678"; 
unsigned char hash[SHA_DIGEST_LENGTH+1]; // +1 for null terminator 

strcpy(str, salt); 
strcat(str, pass); // strcat() only takes 2 arguments, you need to call it twice 
strcat(str, salt); 

SHA1(str, strlen(str), hash); 

您還應該考慮在C++中使用std::string而不是char數組。

0

什麼:

SHA_CTX ctx; 
SHA1_Init(&ctx); 

const char salt[] = "1234"; 
const char pass[] = "12345678"; 

SHA1_Update(&ctx, salt, strlen(salt)); 
SHA1_Update(&ctx, pass, strlen(pass)); 
SHA1_Update(&ctx, salt, strlen(salt)); 
unsigned char hash[SHA_DIGEST_LENGTH]; 
SHA1_Final(hash, &ctx); 

有沒有需要中間的連接字符串。散列大小的常量已經存在。並且可以使用strlen來檢索字符串的大小。

此外,在密碼學中,將字節表示爲C中的無符號字符非常有用 - 這也是參數列表中的散列類型。