将php代码转换为C(sha1算法)


convert php code to C (sha1 algorithm)

PHP代码:

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

我的C代码使用以下位置的openSSL加密库使用SHA1:http://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代码完全相同的代码?谢谢

您需要在字符串中为连接的字符串分配足够的空间。此外,您不能修改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数组。

关于:

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中的无符号字符是很有用的,这也是SHA1_Final参数列表中的哈希类型。