JAVA - How to store and read an RSA public key from an sqlite db
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
michele
Updated on June 05, 2022Comments
-
michele about 2 years
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