RSA加密pdf文件 RSA_public_encrypt函数return-1
文件加密到一半时,发生错误。
error:04068084:rsa routines:RSA_EAY_PUBLIC_ENCRYPT:data too large for modulus
include<stdio.h>
include<stdlib.h>
include<string.h>
include<openssl/rsa.h>
include<openssl/pem.h>
include<openssl/err.h>
include<openssl/applink.c>
define FILENAME "file.pdf"
define ENCRYPTED "encrypted.pdf"
define DECRYPTED "decrypted.pdf"
define OPENSSLKEY "key.pem"
define PUBLICKEY "pubkey.pem"
define BUFFSIZE 1024
void Encrypt(char filename, char path_key); //加密
void Decrypt(char filename, char path_key); //解密
int main(void) {
Encrypt(FILENAME, PUBLICKEY);
Decrypt(ENCRYPTED, OPENSSLKEY);
return 0;
}
void Encrypt(char filename, char path_key) {
char *w_buffer, *r_buffer, buff[240] = "";
const char *err;
unsigned long ul;
RSA *p_rsa;
FILE *f_key, *f_source, *ptr_en;
int rsa_len, flen, len;
if (NULL == (f_source = fopen(filename, "rb"))) {
puts("Failed to open the file.");
exit(-1);
}
if (NULL == (ptr_en = fopen(ENCRYPTED, "wb"))) {
puts("Failed to open the file.");
exit(-1);
}
if ((f_key = fopen(path_key, "r")) == NULL) {
perror("open key file error");
exit(-1);
}
if ((p_rsa = PEM_read_RSAPublicKey(f_key, NULL, NULL, NULL)) == NULL) {
ERR_print_errors_fp(stdout);
exit(-1);
}
rsa_len = RSA_size(p_rsa);
r_buffer = (char *)malloc(rsa_len);
w_buffer = (char *)malloc(rsa_len);
while (!feof(f_source)) {
memset(r_buffer, 0, rsa_len);
memset(w_buffer, 0, rsa_len);
fread(r_buffer, 1, rsa_len-1, f_source);
//出错
if (RSA_public_encrypt(rsa_len, (unsigned char *)r_buffer, (unsigned char*)w_buffer, p_rsa, RSA_NO_PADDING) < 0) {
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), buff);
puts(buff);
exit(-1);
}
fwrite(w_buffer, 1, rsa_len, ptr_en);
}
RSA_free(p_rsa);
fclose(f_key);
fclose(f_source);
fclose(ptr_en);
}
void Decrypt(char filename, char path_key) {
char *w_buffer, *r_buffer;
RSA *p_rsa;
FILE *f_key, *f_source, *ptr_de;
int rsa_len, flen;
if (NULL == (f_source = fopen(filename, "rb"))) {
puts("Failed to open the file.");
exit(-1);
}
if (NULL == (ptr_de = fopen(DECRYPTED, "wb"))) {
puts("Failed to open the file.");
exit(-1);
}
if ((f_key = fopen(path_key, "r")) == NULL) {
perror("open key file error");
exit(-1);
}
if ((p_rsa = PEM_read_RSAPrivateKey(f_key, NULL, NULL, NULL)) == NULL) {
ERR_print_errors_fp(stdout);
exit(-1);
}
rsa_len = RSA_size(p_rsa);
r_buffer = (char *)malloc(rsa_len);
w_buffer = (char *)malloc(rsa_len);
while (!feof(f_source)) {
memset(r_buffer, 0, rsa_len);
memset(w_buffer, 0, rsa_len);
fread(r_buffer, 1, rsa_len, f_source);
if (RSA_private_decrypt(rsa_len, (unsigned char *)r_buffer, (unsigned char*)w_buffer, p_rsa, RSA_NO_PADDING) < 0)
exit(-1);
fwrite(w_buffer, 1, rsa_len, ptr_de);
}
RSA_free(p_rsa);
fclose(f_key);
fclose(f_source);
fclose(ptr_de);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论