2014-10-09 110 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中的无符号字符非常有用 - 这也是参数列表中的散列类型。