android使用openssl生成公私钥

需求:

android下生成PKCS#1格式的私钥,以兼容js版本客户端中使用该私钥

分析:

由于android生成的私钥格式为PKCS#8且没有找到方法可以在java中转换PKCS#8到PKCS#1

因为使用了通过JNI使用openssl来解决该问题,在C++中生成pem格式文件,在java中读取

 

int MyRSA::createPEM(const std::string &cacheDir) {
    RSA *r = RSA_new();
    int bits = 1024;
    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((cacheDir+"/pri.pem").c_str(),"w");
    int ret = PEM_write_bio_RSAPrivateKey(out, r, NULL, NULL, 0, NULL, NULL);
    BIO_flush(out);
    BIO_free(out);

    out = BIO_new_file((cacheDir+"/pub.pem").c_str(),"w");
    EVP_PKEY* pkey = EVP_PKEY_new();
    if(pkey==NULL){
        return 0;
    }
    EVP_PKEY_assign_RSA(pkey,r);
    ret = PEM_write_bio_PUBKEY(out, pkey);
    BIO_flush(out);
    BIO_free(out);

    BN_free(e);
    RSA_free(r);
    return 0;
}

 

 

 

/**
     * 获取秘钥文件内容
     * @param fileName
     * @return base64格式秘钥
     */
    public static String getPemRsaKey(String fileName){
        File f = new File(fileName);
        InputStream in = null;
        try {
            in = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "";
        }
        byte b[]=new byte[(int)f.length()];     //创建合适文件大小的数组
        try {
            in.read(b);    //读取文件中的内容到b[]数组
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

        return new String(b);
    }

 

转载于:https://www.cnblogs.com/yklszm/p/8778784.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值