PHP
代码:
<?php
$pass = "12345678";
$salt = "1234";
echo sha1($salt.$pass.$salt);
?>
我的C
代码使用SHA1
使用openSSL加密库: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
代码完全相同的内容?
感谢。
答案 0 :(得分: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数组。
答案 1 :(得分: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中的无符号字符很有用 - 这也是SHA1_Final
参数列表中的散列类型。