我正在尝试将crypt->public_key->data
写入二进制文件。如果我将sizeof(unsigned int)
的大小用作fwrite()
中的第二个参数,它将起作用。但是,它在头文件中声明为unsigned short *
类型。我不知道为什么会这样。另外,我在编写公共密钥并阅读它们时也会遇到问题。尽管我在fwrite()
和fread()
中使用了完全相同的类型。
编辑:看来我的crypt-> public_key->数据的大小不正确,如usr2564301所指出的。
*我不确定是否需要引用此代码的来源。但我将在此处添加URL:https://github.com/Varad0612/The-McEliece-Cryptosystem
来自矩阵的代码。h
typedef struct matrix
{
int rows; //number of rows.
int cols; //number of columns.
unsigned short *data;
}*bin_matrix;
这是mceliece.c中的代码
//Initialize the mceliece cryptosystem
mcc mceliece_init(int n0, int p, int w, int t)
{
FILE *publicKey, *privateKey;
mcc crypt;
crypt = (mcc)safe_malloc(sizeof(struct mceliece));
//crypt->code = qc_mdpc_init(n0, p, w, t);
//crypt->public_key = generator_matrix(crypt->code);
//printf("%d\n",crypt->public_key->rows);
//printf("%d\n",crypt->public_key->cols);
//Write public key into a binary file
/*publicKey = fopen("PublicKey.bin", "wb");
privateKey = fopen("PrivateKey.bin", "wb");
if(privateKey != NULL){
fwrite(crypt->code->row, n0*p*sizeof(unsigned short), n0 * p, privateKey);
fclose(privateKey);
}
else{
printf("Unable to write private key\n");
}
//Write public key into a binary file
if(publicKey != NULL){
fwrite(crypt->public_key->data, p*p*n0*sizeof(unsigned short), crypt->public_key->rows*crypt->public_key->cols, publicKey);
fclose(publicKey);
}
else{
printf("Unable to write public key\n");
}*/
//Read private key from a binary file
crypt->code = (mdpc)safe_malloc(sizeof(struct qc_mdpc));
crypt->code->n0 = n0;
crypt->code->p = p;
crypt->code->w = w;
crypt->code->t = t;
crypt->code->n = n0 * p;
crypt->code->r = p;
crypt->code->k = (n0 - 1) * p;
crypt->code->row = (unsigned short*)calloc(n0 * p, sizeof(unsigned short));
privateKey = fopen("PrivateKey.bin", "rb");
if(privateKey != NULL){
fread(crypt->code->row, p*n0*sizeof(unsigned short), p*n0, privateKey);
fclose(privateKey);
}
else
printf("Unable to read private key\n");
//Read public key from a binary file
/*crypt->public_key = (bin_matrix)safe_malloc(sizeof(struct matrix));
crypt->public_key->data = (unsigned short*)safe_malloc(p*p*n0*sizeof(unsigned short));
crypt->public_key->rows = p;
crypt->public_key->cols = n0*p;
publicKey = fopen("PublicKey.bin", "rb");
if(publicKey != NULL){
fread(crypt->public_key->data, p*p*n0*sizeof(unsigned short), crypt->public_key->rows*crypt->public_key->cols, publicKey);
fclose(publicKey);
}
else{
printf("Unable to read public key\n");
}*/
printf("Successful\n");
//printf("mceliece generated...\n");
return crypt;
}
答案 0 :(得分:1)
我们的阅读陈述有些混乱:
fread(crypt->code->row, p*n0*sizeof(unsigned short), p*n0, privateKey);
这将尝试读取p*n0
个元素,每个元素的大小为p*n0*sizeof(unsigned short)
个字节。如果文件不大于分配的大小,您会很幸运,因为fread
不会尝试在分配的块末尾进行写操作。
您应该写:
size_t nread = fread(crypt->code->row, sizeof(unsigned short), p * n0, privateKey);
if (nread == p * n0) {
/* private key was read successfully */
} else {
/* file is too short, only nread words were read */
}