JAVA - How to store and read an RSA public key from an sqlite db
i have to store a public key and a private one into a sqlite database. Actually i write the pubKey.getEncoded() into the database, and to recreate the pubkey i use the following code:
ResultSet result = stat.executeQuery("select publickey from cert where id='1'"); KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(result.getBytes(1)); RSAPublicKey pubKey; pubKey = (RSAPublicKey) rsaKeyFac.generatePublic(keySpec);
but it gives me the following error
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.开发者_高级运维InvalidKeyException: IOException: Detect premature EOF
at this point :
pubKey = (RSAPublicKey) rsaKeyFac.generatePublic(keySpec);
Anyone can help me?
Thank you in advance
If you look here: http://java.sun.com/docs/books/tutorial/jdbc/basics/retrieving.html you will see how to properly retrieve from a DB. That is assuming you have a type of char(n) for your DB column.
ResultSet result = stat.executeQuery("select publickey from cert where id='1'");
while(result.next())
{
KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(result.getString(1));
RSAPublicKey pubKey;
pubKey = (RSAPublicKey) rsaKeyFac.generatePublic(keySpec);
}
If the type is a BLOB or CLOB then you need to use a different mechanism. http://java.sun.com/j2se/1.5.0/docs/guide/jdbc/blob.html
When you first get a ResultSet, the cursor points to the space before the first row of results. So you need to call next() on it before trying to retrieve the data.
You should make sure that the query actually succeeded.
精彩评论