将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
参数列表中的哈希类型。
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 使用Qt C++计算类似Git的SHA1哈希
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- 为什么我的排序算法会更改数组值
- 求最大元素位置的分治算法
- 具有非整数边容量的最大流量的Dinic算法
- 到连接组件算法的问题(递归)
- STL算法函数在多个一维容器上的使用
- 读取最后一行代码算法 - c++ 时出现问题
- 括号更改 O(n) 算法
- std::unordered_map 搜索算法是如何实现的?
- 将php代码转换为C(sha1算法)