本文主要是介绍openssl 从pem中读取秘钥,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
openssl pem.h 中提供了关于pem格式密钥对的操作接口
通常使用.pem的格式文件来保存openssl 生成的密钥对;
在终端下 cat xxx.pem 可以看到
-----BEGIN RSA PRIVATE KEY-----
XXXX
-----END RSA PRIVATE KEY-----
密钥数据进行了BASE64编码
1. 示例:将生成的密钥对保存成pem文件
void testWriteRSA2PEM() {//生成密钥对RSA *r = RSA_new();int bits = 512;BIGNUM *e = BN_new();BN_set_word(e, 65537);RSA_generate_key_ex(r, bits, e, NULL);RSA_print_fp(stdout, r, 0);BIO *out;out = BIO_new_file("/Users/cocoajin/Desktop/opriv.pem","w");//这里生成的私钥没有加密,可选加密int ret = PEM_write_bio_RSAPrivateKey(out, r, NULL, NULL, 0, NULL, NULL);printf("writepri:%d\n",ret);BIO_flush(out);BIO_free(out);out = BIO_new_file("/Users/cocoajin/Desktop/opub.pem","w");ret = PEM_write_bio_RSAPublicKey(out, r);printf("writepub:%d\n",ret);BIO_flush(out);BIO_free(out);BN_free(e);RSA_free(r);}
在目标路径保存了生成的公钥opub.pem和私钥oprov.pem
输出日志
View Code
2. 示例:从pem文件中获取公钥私钥方式一(利用了BIO)
void testReadRSAFromPEM() {RSA *pubkey = RSA_new();RSA *prikey = RSA_new();BIO *pubio;BIO *priio;priio = BIO_new_file("/Users/cocoajin/Desktop/opriv.pem", "rb");prikey = PEM_read_bio_RSAPrivateKey(priio, &prikey, NULL, NULL);pubio = BIO_new_file("/Users/cocoajin/Desktop/opub.pem", "rb");pubkey = PEM_read_bio_RSAPublicKey(pubio, &pubkey, NULL, NULL);RSA_print_fp(stdout, pubkey, 0);RSA_print_fp(stdout, prikey, 0);RSA_free(pubkey);BIO_free(pubio);RSA_free(prikey);BIO_free(priio);}
从目标路径读取公钥opub.pem和私钥opriv.pem
输出日志
View Code
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);}
输出日志
View Code
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
参考:https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_RSAPublicKey.html
这篇关于openssl 从pem中读取秘钥的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!