php - 使用 mcrypt 在 php 和 c 中进行 AES 加密

标签 php c encryption aes mcrypt

我又遇到了 mcrypt 的问题。我想知道为什么我在使用 rinjdael-128 cfb 模式加密的 php 和 c 中得到不同的结果。这是我的 php 函数:

function mcencrypt($Clear, $Pass){
$td = mcrypt_module_open('rijndael-128', '', 'cfb', '');
$iv = 'AAAAAAAAAAAAAAAA';
mcrypt_generic_init($td, $Pass, $iv);
$encrypted = mcrypt_generic($td, $Clear);
mcrypt_generic_deinit($td);
return $encrypted;
}

和我的 c 函数:

unsigned char *Encrypt( unsigned char *key, unsigned char *message, int buff_len){

    unsigned char *Res;
    MCRYPT mfd; 
    char* IV = "AAAAAAAAAAAAAAAA";
    int i, blocks, key_size=16, block_size;

    mfd = mcrypt_module_open("rijndael-128", NULL, "cfb", NULL);
    block_size = mcrypt_enc_get_block_size(mfd);
    blocks = ceil((double)buff_len/block_size);

    mcrypt_generic_init(mfd, key, key_size, IV);
    Res = calloc(1, (blocks *block_size)+1);

    strncpy(Res, message, buff_len);
    mcrypt_generic(mfd,Res,(blocks *block_size));

    mcrypt_generic_deinit(mfd);
    mcrypt_module_close(mfd);

     return (Res);

当我在 for 循环中使用它们时,前 26 个加密是 korect,但在第 27 个中,最后一个树符号是不同的。这真的很奇怪。

在 php 中,我像这样创建 for 循环:

$seed ="m78otPfBLT48msvd";
$key = "r2oE61IQo7VwFXnF";
$start_y= mcencrypt($seed,$key);
$new =$start_y;
$enc_prob = mcencrypt($start_y,$key);
for ($j=1; $j<30;$j++){
$new.=$enc_prob;
echo "j: ".$j.'<br>';
echo "the new: ".$enc_prob."lenght: ".strlen($enc_prob).'<br>';
echo "new in hex for j=".$j.": ".strToHex($enc_prob).'<br>';
$enc_prob=mcencrypt($enc_prob,$key);
}

在 c 中是这样的:

 int j, buff_len;
char seed[] = "m78otPfBLT48msvd", key1[]="r2oE61IQo7VwFXnF";
buff_len = strlen(seed);
unsigned char *encrypted, *encrypted2;
encrypted = Encrypt(key1, seed, buff_len);
encrypted2 =  Encrypt(key1, encrypted, buff_len);
for (j=1; j<cols; j++) {
    printf("j: %d\n", j);
    printf("encrypted2 %s\n", string_to_hex(encrypted2, buff_len));

    memcpy(encrypted2, Encrypt(key1, encrypted2, buff_len),buff_len);
}
free(encrypted);
free(encrypted2);

出了什么问题。消息和 key 是相同的。我正在使用相同的库,相同的 iv。我不明白。它很奇怪。请帮我解决这个问题。非常感谢!!

最佳答案

我想出了问题所在。 c 中的字符串以 null 结尾,并且在我的加密函数中使用 strncpy 造成了问题,所以我只是在 memcpy 中更改了它,现在一切顺利。再次感谢所有试图提供帮助并花时间查看我的问题的人。

关于php - 使用 mcrypt 在 php 和 c 中进行 AES 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13443571/

相关文章:

php - 在 WAMP 服务器中安装 Magento 时出错

php - 字符串替换为 = 空字符串 PHP

c++ - 我应该对临时内联变量使用++ 运算符吗?

C - 静态分配的字符数组的 memset 段错误

python - 使用 STARTTLS 从 Python 发送电子邮件

php - 代码未在 WordPress 上显示结果

c++ - 从 node.js 调用 C 代码

java - HashMap: containsKey() 不应该是真的?

java - 使用 JVM 属性禁用特定的弱密码并强制执行完美前向保密

php - 显示 php 测验的结果而不重新加载页面