首页 > RSA加密pdf文件 RSA_public_encrypt函数return-1

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);

}

【热门文章】
【热门文章】