GmSSL icon indicating copy to clipboard operation
GmSSL copied to clipboard

bug sm2_lib.c:499:sm2_do_encrypt(): 解密发生错误

Open tx991020 opened this issue 2 years ago • 4 comments

#include <stdio.h> #include <string.h> #include <stdlib.h> #include <gmssl/sm2.h> #include <gmssl/error.h> #include <time.h>

int main(void) { SM2_KEY sm2_key; SM2_KEY pub_key; unsigned char plaintext[SM2_MAX_PLAINTEXT_SIZE]; unsigned char ciphertext[SM2_MAX_CIPHERTEXT_SIZE]; size_t len;

// 从 hello.txt 读取文本内容
FILE *file = fopen("/Users/andy/CLionProjects/learnc/hello.txt", "r");
if (file == NULL) {
    printf("无法打开文件\n");
    return 1;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
fread(plaintext, sizeof(unsigned char), file_size, file);
fclose(file);

sm2_key_generate(&sm2_key);
memcpy(&pub_key, &sm2_key, sizeof(SM2_POINT));
//打印 file_size
printf("file_size: %ld\n", file_size);

sm2_encrypt(&pub_key, plaintext, file_size, ciphertext, &len);
format_bytes(stdout, 0, 0, "ciphertext", ciphertext, len);
//打印 len
printf("len: %ld\n", len);
if (sm2_decrypt(&sm2_key, ciphertext, len, plaintext, &len) != 1) {
    fprintf(stderr, "解密发生错误\n");
    return 1;
}
plaintext[len] = 0;

// 将解密后的文本内容写入 hello1.txt
file = fopen("/Users/andy/CLionProjects/learnc/hello1.txt", "w");
if (file == NULL) {
    printf("无法打开文件\n");
    return 1;
}
fwrite(plaintext, sizeof(unsigned char), len, file);
fclose(file);

return 0;

} /Users/andy/CLionProjects/learnc/GmSSL/src/sm2_lib.c:499:sm2_do_encrypt(): /Users/andy/CLionProjects/learnc/GmSSL/src/sm2_lib.c:802:sm2_encrypt(): /Users/andy/CLionProjects/learnc/GmSSL/src/sm2_lib.c:848:sm2_decrypt(): 解密发生错误 file_size: 19020 ciphertext: (null) len: 0

tx991020 avatar Oct 23 '23 15:10 tx991020

SM2_MAX_PLAINTEXT_SIZE 定义是255 ,你这个文件偏大了点,试试小点

/Users/andy/CLionProjects/learnc/GmSSL/src/sm2_lib.c:499:sm2_do_encrypt():

if ( !(SM2_MIN_PLAINTEXT_SIZE <= inlen && inlen <= SM2_MAX_PLAINTEXT_SIZE)) {
		error_print();
		return -1;
	}

lpilp avatar Oct 24 '23 01:10 lpilp

我有大文件要加密怎么办

tx991020 avatar Oct 24 '23 01:10 tx991020

我有大文件要加密怎么办

一般的解决方案都是sm2非对称加密一个密码,内容采用sm4 对称加密, 非得用 sm2 加密大文件就自己修改代码采用分组加密

lpilp avatar Oct 24 '23 04:10 lpilp

sm2加密可以参考rsa的加密ecb模式

deatil avatar Oct 26 '23 17:10 deatil