我已經(jīng)生成了一個私鑰:openssl genrsa [-out file] –des3在此之后,我生成了一個公鑰:openssl rsa –pubout -in private.key [-out file]我想用我的私鑰簽署一些消息,并使用我的公鑰驗證其他一些消息,使用如下代碼:public String sign(String message) throws SignatureException{ try { Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(privateKey); sign.update(message.getBytes("UTF-8")); return new String(Base64.encodeBase64(sign.sign()),"UTF-8"); } catch (Exception ex) { throw new SignatureException(ex); }}public boolean verify(String message, String signature) throws SignatureException{ try { Signature sign = Signature.getInstance("SHA1withRSA"); sign.initVerify(publicKey); sign.update(message.getBytes("UTF-8")); return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8"))); } catch (Exception ex) { throw new SignatureException(ex); }}我找到了將我的私鑰轉(zhuǎn)換為PKCS8格式并加載它的解決方案。它適用于這樣的一些代碼:public PrivateKey getPrivateKey(String filename) throws Exception { File f = new File(filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec);}最后我的問題是:如何從文件加載我的RSA公鑰?我想也許我需要將我的公鑰文件轉(zhuǎn)換為x509格式,然后使用X509EncodedKeySpec。但是我怎么能這樣做呢?
添加回答
舉報
0/150
提交
取消