How to store public and private key generated by RSA in java to Postgres sql

Viewed 138
public static void keyPairProducing() throws NoSuchAlgorithmException, FileNotFoundException, IOException, SQLException {
        File pFile = new File("public.key");
        File prFile = new File("private.key");
        //ResultSet rs = statement.executeQuery("SELECT * FROM KEYS WHERE SNO=1;");
        //rs.next();
        //if(rs.getBytes("PUBLICKEY")==null || rs.getBytes("PRIVATEKEY")==null){
        if(!pFile.exists() || !prFile.exists()){
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keypair = keyGen.genKeyPair();
        PrivateKey privateKey = keypair.getPrivate();
        PublicKey publicKey = keypair.getPublic();
        try (FileOutputStream fos = new FileOutputStream("public.key")) {
            fos.write(publicKey.getEncoded());
        }
        try (FileOutputStream fos = new FileOutputStream("private.key")) {
            fos.write(privateKey.getEncoded());
        }
        //PreparedStatement preparedStatement = c.prepareStatement("INSERT INTO KEYS(PUBLICKEY, PRIVATKEY) VALUES(?, ?) WHERE SNO=1;");
        //byte[] publicKeyBytes = publicKey.getEncoded();
        //preparedStatement.setBytes(1, publicKey.getEncoded());
        //preparedStatement.setBytes(2, publicKey.getEncoded());
        System.out.println("public.key created");
        System.out.println("private.key created");
    }
    }
    public static PrivateKey getPrivateKey() throws IOException, GeneralSecurityException {
        File privateKeyFile = new File("private.key");
        byte[] privateKeyBytes = Files.readAllBytes(privateKeyFile.toPath());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey prikey = keyFactory.generatePrivate(privateKeySpec);
        return prikey;
    }
    public static PublicKey getPublicKey() throws IOException, GeneralSecurityException, InvalidKeySpecException {
        File publicKeyFile = new File("public.key");
        byte[] publicKeyBytes = Files.readAllBytes(publicKeyFile.toPath());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey pubkey = keyFactory.generatePublic(publicKeySpec);
        return pubkey;
    }

'can someone please explain instead of into public.key or private.key file how can i store it to postgres database and retrive the key back for encryption and decryption Thanks in advance'

0 Answers
Related