SSL and TLS with EMySQL API
Using the EMySQL API – Part 13
Foreword: In this part of the series, you learn how to use TLS for the EMySQL API client.
By: Date Published: 24 Oct 2017
Introduction
The web scheme for SSL operation is HTTPS and not HTTP, as in https://www.site.com .
To use TLS with EMySQL API client, you need two files which are called, the client key (client-key.pem) file and the client certificate (client-cert.pem) file. You may also need the server certificate (server-cert.pem) file; server certificate can be considered as certificate authoriry (ca). Search this site (or the web) for the meaning and how to obtain these three files.
You should use TLS with MySQL when the API client and the MySQL server are in different computers (in a network).
Syntax
The EMySQL API client indicates to the MySQL server that it wants TLS communication, when it connects to the MySQL server. The syntax is:
con = new mysql.Connection("root", "secret", "server.com", 3306, callbackFn(){}, undefined, 'tls', 'path/to/client-key.pem', 'path/to/client-cert.pem', [, 'path/to/server-cert.pem'] );
The last file in the argument list is optional, depending on the network system. The sixth argument is undefined instead of 'compress'. TLS also does compression, so if the sixth argument is 'compress', there will be an unnecessary second compression of data.
The following code should read rows from a table in a MySQL database, or inform you that the MySQL server does not support TLS:
const mysql = require('./server/Mysql.js');
con = new mysql.Connection("root", "secret", "localhost", 3306, function(err)
{
if (err)
console.log(err);
}, undefined, 'tls', 'client-key.pem', 'client-cert.pem');
var db = `PetStore`;
con.selectDB(db, function(err)
{
if (err)
console.log(err);
else
console.log('database selected');
});
var selStr = `SELECT * FROM pet`;
con.query(selStr, function(err, result)
{
if (err)
console.log(err);
else
{
for (i=0; i<result.length; ++i)
{
tempStr = `${result[i].get('name')}, ${result[i].get('owner')}, ${result[i].get('species')}, ${result[i].get('sex')}, ${result[i].get('birth')}, ${result[i].get('death')}`
console.log(tempStr);
}
}
});
con.close();
That is it for this part of the series. We stop here and continue in the next part.
Chrys