在文件中读取私钥和公钥

在做项目中,碰到是给到定的私钥和公钥,我们得把公钥和私钥读出来才可以使用,私钥一般还会有密码!

/** * 获取公钥 */ public PublicKey readPublicKey(String cerFileName) { CertificateFactory cf; FileInputStream in; Certificate c; PublicKey pk = null; try { cf = CertificateFactory.getInstance("X.509"); in = new FileInputStream(cerFileName); c = cf.generateCertificate(in); pk = c.getPublicKey(); } catch (CertificateException e) { log.error("获取公钥错误!!!"); log.error(e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { log.error("获取公钥错误!!!"); log.error(e.getMessage()); e.printStackTrace(); } return pk; } /** * 获取私钥 * * @return */ public PrivateKey readPrivateKey(String privateKeyFileName, String privatepass) { KeyStore ks; PrivateKey prk = null; try { ks = KeyStore.getInstance("pkcs12"); FileInputStream fis = new FileInputStream(privateKeyFileName); ks.load(fis, null); String pwd = privatepass; String alias = ks.aliases().nextElement().toString(); prk = (PrivateKey) ks.getKey(alias, pwd.toCharArray()); } catch (Exception e) { log.error("获取私钥错误!!!"); log.error(e.getMessage()); e.printStackTrace(); } return prk; }

  

posted @ 2016-03-31 13:26  ~铁臂阿童木~  阅读(2297)  评论(0编辑  收藏  举报