RSA是基於數論中大素數的乘積難分解理論上的非對稱加密法。在此密碼術中,使用公鑰(public key)和私鑰(private key)兩個不同的密鑰:公鑰用於加密,它是向所有人公開的;私鑰用於解密,只有密文的接收者持有。

舉例:小紅希望安全地發送一條消息給小明,消息明文為m,小明的公鑰為K+,小明的私鑰為K-。通信過程為,小紅使用K+加密m,成為密文K+(m),傳送給小明,小明收到後使用K-解密這個密文得到原始消息明文,即m = K-(K+(m))。

具體的密鑰生成算法如下。隨機選擇兩個大素數p和q(比如每個都是1024 bit),計算n = pq, n’ = (p-1)(q-1). 選擇一個e (e小於n) 與n’互質。計算d使得ed = 1 mod n’.則公鑰為(n, e),私鑰為(n, d). 注意p和q都應該保密。

加密過程為c = m^e mod n
解密過程為m = c^d mod n

以上為原理簡介。下面是openssl API編程應用讀取密鑰文件的示例源代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* rsa_pem.cc
* - Show the usage of RSA that reads from key files.
*/
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
 
int main(int argc, char** argv) {
    FILE* fp;
    RSA* rsa1;
 
    // check usage
    if (argc != 2) {
        fprintf(stderr, "%s <RSA private key param file>\n", argv[0]);
        exit(-1);
    }
 
    // open the RSA private key PEM file 
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        fprintf(stderr, "Unable to open %s for RSA priv params\n", argv[1]);
        return NULL;
    }
    if ((rsa1 = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) {
        fprintf(stderr, "Unable to read private key parameters\n");
        return NULL;
    }                                                         
    fclose(fp);
 
    // print 
    printf("Content of Private key PEM file\n");
    RSA_print_fp(stdout, rsa1, 0);
    printf("\n");    
 
 
/*
    RSA* rsa2;
 
    // open the RSA public key PEM file
    fp = fopen(argv[2], "r");
    if (fp == NULL) {
        fprintf(stderr, "Unable to open %s for RSA pub params\n", argv[1]);
        return NULL;
    }
    if ((rsa2 = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
        fprintf(stderr, "Unable to read public key parameters\n");
        return NULL;
    }                                                         
    fclose(fp);
 
    printf("Content of Public key PEM file\n");
    RSA_print_fp(stdout, rsa2, 0);
    printf("\n");    
*/
    return 0;
}

編譯Makefile:

CC=g++
CFLAGS=-Wall -g -O2
LIBS=-lcrypto
 
all: rsa rsa_pem 
 
rsa: rsa.cc
    $(CC) $(CFLAGS) rsa.cc -o $@ $(LIBS)
 
rsa_pem: rsa_pem.cc
    $(CC) $(CFLAGS) rsa_pem.cc -o $@ $(LIBS)
 
clean:
    @rm -f rsa
    @rm -f rsa_pem