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); }
浙公网安备 33010602011771号