2017-09-14 80 views
0

我無法從java中的xml文件轉換公鑰。經過一番研究,似乎X509編碼是最常用的格式。無法在java中創建xml中的公鑰對象

我有一個XML文件,它看起來是這樣的:

<RSAKeyValue> 
<Modulus>hkjhvgkjewrlhfelwrkjvhwerkjlrkwjvbrvkjrbvkwjlvbwekvjbekvbwkbrkvbwrwebrvvbrlkvbklvrbkvlreb</Modulus> 
<Exponent>AQAB</Exponent> 
</RSAKeyValue> 

(這不是我的實際鍵值)

這裏是什麼,我嘗試了代碼示例:

File fXmlFile = new File(".....\\...\\...\\file.xml"); //Path to xml file 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document doc = dBuilder.parse(fXmlFile); 
doc.getDocumentElement().normalize(); 

NodeList nList = doc.getElementsByTagName("Modulus"); 
Node n = nList.item(0); 

byte[] encKey = Base64.getEncoder().encode(n.getTextContent().getBytes()); 

X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey); 
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN"); 
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); 

在最後一行我收到一個異常,如下所示:

java.security.spec.InvalidKeySpecException: Inappropriate key specification: invalid key format 
at sun.security.provider.DSAKeyFactory.engineGeneratePublic(DSAKeyFactory.java:119) 
at java.security.KeyFactory.generatePublic(KeyFactory.java:328) 
at XmlReader.main(XmlReader.java:41) 

我不確定問題是關鍵格式。這可能是一個輸入被轉換成一個字符串,導致它失去了一些關鍵的重要數據的問題?

回答

1

你正在建設一個DSA KeyFactory RSA密鑰,並使用X509EncodedKeySpec,而你有模量和指數以base64

編碼試試這個:

BigInteger modulus = new BigInteger(Base64.getDecoder().decode(modulusAsString)); 
BigInteger exponent = new BigInteger(Base64.getDecoder().decode(exponentAsString)); 

RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent); 
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
PublicKey pubKey =keyFactory.generatePublic(keySpec); 

我省略了XML部分