我正在用 C 实现 sha256 算法。我不需要算法方面的帮助。实现该算法的任务之一是将位填充到消息中,以使消息的长度为 512 位或其长度为 512 位的倍数。
我最初认为向消息填充位只是意味着向其填充零。但由于该消息是字符消息(字符串),我认为我的逻辑不正确。
我的代码没有问题。我只是不知道如何将位填充到字符串(代码中的 msg)
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
char *msg=(char*)malloc(sizeof(char)*512);
printf("\n Enter a message");
scanf("%s",msg);
//I don't know how to pad bits to msg
return 0;
}
最佳答案
I initially thought that padding bits to a message would simply mean padding zeroes to it.
有些算法期望 block 的大小恒定,例如。 AES 或 sha256。从字面上看,它们被称为“ block 算法”,例如。 block ciphers 。当处理比 block 大小短的消息时,您必须用一些东西填充未使用的位。
通常,按照惯例,为了简单起见,它们用零填充。有一些标准规定可以用什么来填充未使用的位/字节。有时它们会填充随机字节或用单个 1
填充,然后将 0000...00
位填充为零,等等。请参见示例。 this wiki page
客户端必须知道消息的长度。对于 C 字符串,我只需用零字节填充它。无论如何,C 字符串都以零字节结尾,因此用户只需 strlen(received_message)
就可以知道字符串的长度。
在处理任意数据的情况下,您必须以某种方式传递消息的长度。例如,也许有其他方式或在消息开头。因此,例如,您可以选择前 4 个字节来表示消息长度。或者,您可以指定消息以 C 字符串开头,消息长度使用 ASCII 字符以 16 为基数表示的数字进行编码(因此您可以使用 %x
读取消息长度),并在字符串之后您的消息仍在继续。
How do I pad bits to a string in C?
只需使用 calloc
或 meset
将 msg
内存初始化为零即可:
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[]) {
char *msg = calloc(128, sizeof(*msg));
if (msg == NULL) abort();
printf("\n Enter a message");
if (scanf("%127s", msg) != 1) abort()
# bits are padded with zeros, proceed with your algorithm
return 0;
}
或者您可以仅 memset 内存中未使用的字节:
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main(int argc,char *argv[]) {
char *msg = malloc(128 * sizeof(*msg));
if (msg == NULL) abort();
printf("\n Enter a message");
if (scanf("%127s", msg) != 1) abort();
memset(&msg[strlen(msg)], 0, 128 - strlen(msg));
# bits are padded with zeros, proceed with your algorithm
return 0;
}
代码注释:
- Don't cast result of malloc
- Don't use scanf, it is unsafe 。特别是切勿将
%s
与scanf
一起使用。
关于c - 如何在 C 语言中将位填充到字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620198/