Home  >  Article  >  Database  >  Why am I getting the \"Public Key Retrieval is not allowed\" error when connecting to MySQL with Java?

Why am I getting the \"Public Key Retrieval is not allowed\" error when connecting to MySQL with Java?

DDD
DDDOriginal
2024-11-01 17:20:02610browse

Why am I getting the

MySQL Connection Error: "Public Key Retrieval is not allowed"

When attempting to connect to a MySQL database using Java's MySQL Connector 8.0.11, you may encounter the following exception:

java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

This error indicates that the client is attempting to retrieve the public key from the server, but the connection has not been configured to allow it.

Resolution

To resolve the issue, you need to add the allowPublicKeyRetrieval=true client option to your connection string. This will allow the client to automatically request the public key from the server. However, it's important to note that setting this option to true could allow a malicious proxy to perform a MITM attack to obtain the plaintext password.

Example Connection Manager with AllowPublicKeyRetrieval

The following code snippet updates the getConnection method in your ConnectionManager class to include the allowPublicKeyRetrieval option:

<code class="java">public static Connection getConnection() throws SQLException {

    MysqlDataSource dataSource = new MysqlDataSource();

    dataSource.setUseSSL(false);
    dataSource.setServerTimezone(serverTimeZone);
    dataSource.setServerName(serverName);
    dataSource.setDatabaseName(databaseName);
    dataSource.setPortNumber(portNumber);
    dataSource.setUser(user);
    dataSource.setPassword(password);

    dataSource.setAllowPublicKeyRetrieval(true); // Allow public key retrieval

    return dataSource.getConnection();
}</code>

Additional Note

For testing or development purposes, you may also consider disabling SSL by setting useSSL=false, as suggested in the provided solution:

<code class="java">jdbc:mysql://localhost:3306/db?allowPublicKeyRetrieval=true&useSSL=false</code>

The above is the detailed content of Why am I getting the \"Public Key Retrieval is not allowed\" error when connecting to MySQL with Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn