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

PHP code:

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

My C code to use SHA1 using the openSSL crypto library at: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;
}

My question is, how can i modify the C code to the exact same thing as the PHP code? Thanks.

You need to allocate enough space in the string for the concatenated string. Also, you can't modify a const char, so don't use that modifier on the variable that you're concatenating into.

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);

You should also consider using std::string instead of char arrays in C++.

What about:

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);

There is no need for an intermediate concatenated string. The constant for the hash size is already there. And the size of the strings can just be retrieved using strlen.

Furthermore, in cryptography it is useful to represent bytes as unsigned chars in C - and this is also the type of the hash in SHA1_Final argument list.