openssl pem.h 中提供了关于pem格式密钥对的操作接口
通常使用.pem的格式文件来保存openssl 生成的密钥对;
在终端下 cat xxx.pem 可以看到
-----BEGIN RSA PRIVATE KEY-----
XXXX
-----END RSA PRIVATE KEY-----
密钥数据进行了BASE64编码
1. 示例:将生成的密钥对保存成pem文件
在目标路径保存了生成的公钥opub.pem和私钥oprov.pem
输出日志
Private-Key: (512 bit) modulus: 00:e6:96:f5:6f:4d:5e:c2:ad:0d:f5:13:45:99:55: ca:6f:84:4f:3a:56:52:e2:ee:a2:cc:73:77:07:e2: 3d:0d:e3:0d:c0:6a:92:52:b6:c7:de:e2:d6:88:56: 9e:92:99:91:dd:2d:06:c5:a8:f2:c1:79:8b:20:f9: 73:0a:7a:28:93 publicExponent: 65537 (0x10001) privateExponent: 00:ca:1b:92:6f:c5:de:c2:bf:2f:b6:98:f7:ad:d8: 16:20:fc:54:fd:0a:e0:87:6b:26:62:10:ea:49:8c: b0:7a:d3:d8:28:b7:fb:15:f1:4e:95:9d:bf:31:3a: e0:f3:fa:24:d3:71:fd:b0:f5:cd:5c:25:d1:81:8c: 01:e3:fb:c7:21 prime1: 00:f6:d7:91:c4:1a:2f:eb:0b:c4:18:14:3b:fe:f6: 0d:c1:11:94:ca:6c:06:fc:de:d7:19:ac:58:9d:36: 16:fe:9b prime2: 00:ef:25:07:75:76:4d:ac:19:aa:ed:e9:a7:1d:5d: b1:7d:1c:1a:ef:95:8f:2d:bc:8a:e7:93:f5:f8:15: 69:61:69 exponent1: 00:f4:d2:c0:6f:b8:ed:77:fa:16:87:2f:62:86:31: b3:58:9f:c0:6c:b8:92:81:b1:df:b4:45:fd:2a:08: 60:ec:2b exponent2: 00:b5:88:c1:69:bc:3d:67:f8:30:15:db:f9:5c:c4: 63:d8:59:fe:64:82:7e:a6:b4:6a:29:32:db:53:d0: 45:27:89 coefficient: 0a:97:26:2f:e9:ca:b6:32:86:86:3b:5a:13:ea:5e: 8d:79:77:b9:7a:30:41:c4:31:cb:02:0e:96:6b:1b: e5:c4 writepri:1 writepub:1 Program ended with exit code: 0
2. 示例:从pem文件中获取公钥私钥方式一(利用了BIO)
从目标路径读取公钥opub.pem和私钥opriv.pem
输出日志
3. 示例:从pem文件中读取公钥私钥方式二(利用FILE)
void testPEMReadRSA() { RSA *pubkey = RSA_new(); RSA *prikey = RSA_new(); FILE *pubf = fopen("/Users/cocoajin/Desktop/opub.pem", "rb"); pubkey = PEM_read_RSAPublicKey(pubf, &pubkey, NULL, NULL); FILE *prif = fopen("/Users/cocoajin/Desktop/opriv.pem", "rb"); prikey = PEM_read_RSAPrivateKey(prif, &prikey, NULL, NULL); RSA_print_fp(stdout, pubkey, 0); RSA_print_fp(stdout, prikey, 0); fclose(pubf); fclose(prif); RSA_free(pubkey); RSA_free(prikey); }
输出日志
4. 在终端下使用openssl命令生成公钥私钥
//生成1024位的RSA私钥 openssl genrsa -out private.pem 1024 //再由私钥生成公钥 openssl rsa -in private.pem -pubout -out public.pem //私钥文件private.pem //公钥文件public.pem //上面私钥是没加密的,可选加密,指定一个加密算法生成时输入密码
以上测试使用openssl 1.1.0c
参考: