上一篇提到使用openssl读取RSA的密钥文件,在此基础上,本篇介绍具体的RSA加密和解密使用方法。

/*
* rsa.cc
* - Show the usage of RSA encryption/decryption
*/

#include 
#include 
#include 
#include 
#include 

int main(int argc, char** argv) {
    RSA* rsa;
    unsigned char* input_string;
    unsigned char* encrypt_string;
    unsigned char* decrypt_string;
    int i;

    // check usage
    if (argc != 2) {
        fprintf(stderr, "%s \n", argv[0]);
        exit(-1);
    }

    // set the input string
    input_string = (unsigned char*)calloc(strlen(argv[1]) + 1,
            sizeof(unsigned char));
    if (input_string == NULL) {
        fprintf(stderr, "Unable to allocate memory for input_string\n");
        exit(-1);
    }
    strncpy((char*)input_string, argv[1], strlen(argv[1]));
    
    // Generate RSA parameters with 1024 bits (using exponent 3)
    rsa = RSA_generate_key(1024, 3, NULL, NULL);

    // set encryption RSA instance (with only n and e), to resemble
    // the key distribution process
    unsigned char* n_b = (unsigned char*)calloc(RSA_size(rsa), 
            sizeof(unsigned char));
    unsigned char* e_b = (unsigned char*)calloc(RSA_size(rsa), 
            sizeof(unsigned char));
    int n_size = BN_bn2bin(rsa->n, n_b);
    int b_size = BN_bn2bin(rsa->e, e_b);
    // assume the byte strings are sent over the network
    RSA* encrypt_rsa = RSA_new();
    encrypt_rsa->n = BN_bin2bn(n_b, n_size, NULL);
    encrypt_rsa->e = BN_bin2bn(e_b, b_size, NULL);

    // alloc encrypt_string
    encrypt_string = (unsigned char*)calloc(RSA_size(encrypt_rsa), 
            sizeof(unsigned char));    
    if (encrypt_string == NULL) {
        fprintf(stderr, "Unable to allocate memory for encrypt_string\n");
        exit(-1);
    }

    // encrypt (return the size of the encrypted data)
    // note that if RSA_PKCS1_OAEP_PADDING is used, 
    // flen must be < RSA_size - 41 
    int encrypt_size = RSA_public_encrypt(strlen((char*)input_string),
            input_string, encrypt_string, encrypt_rsa, RSA_PKCS1_OAEP_PADDING);

    // alloc decrypt_string
    decrypt_string = (unsigned char*)calloc(RSA_size(rsa), 
            sizeof(unsigned char));
    if (decrypt_string == NULL) {
        fprintf(stderr, "Unable to allocate memory for decrypt_string\n");
        exit(-1);
    }

    // decrypt
    int decrypt_size = RSA_private_decrypt(encrypt_size,
            encrypt_string, decrypt_string, rsa, RSA_PKCS1_OAEP_PADDING);

    // print
    printf("input_string = %s\n", input_string);
    printf("encrypted string = ");
    for (i=0; i> 4) & 0xf, 
                encrypt_string[i] & 0xf);    
    }
    printf("\n");
    printf("decrypted string (%d) = %s\n", decrypt_size, decrypt_string);

    return 0;
}

编译Makefile:

CC=g++
CFLAGS=-Wall -g -O2
LIBS=-lcrypto

all: rsa 

rsa: rsa.cc
    $(CC) $(CFLAGS) rsa.cc -o $@ $(LIBS)

clean:
    @rm -f rsa