Come risolvere l'errore java.lang.RuntimeException: Could not generate DH keypair

Mattepuffo's logo
Come risolvere l'errore java.lang.RuntimeException: Could not generate DH keypair

Come risolvere l'errore java.lang.RuntimeException: Could not generate DH keypair

L'altro giorno stavo cercando di eseguire il download da un mio programma in Java da un sito con HTTPS.

Cosa già fatta varie altre volte; solo che questa volta, su questo sito, riscontravo questo errore (vi posto una parte del trace):

javax.net.ssl.SSLException: java.lang.RuntimeException: 
Could not generate DH keypair
......
Caused by: java.lang.RuntimeException: Could not generate DH keypair
......
Caused by: java.security.InvalidAlgorithmParameterException: 
DH key size must be multiple of 64, and can only range 
from 512 to 2048 (inclusive). 
The specific key size 4096 is not supported
......

Questo il codice che usavo:

public class InstallYDL {

    private String os = System.getProperty("os.name");
    private String remoteFile = null;
    private String fileYdl;
    private File ydlEnd;

    public InstallYDL() {
        if (os.contains("Windows")) {
            remoteFile = "...";
            fileYdl = "ydl.exe";
        } else {
            remoteFile = "...";
            fileYdl = "ydl";
        }
        ydlEnd = new File(System.getProperty("user.home") + "/" + fileYdl);
    }

    public boolean checkLibrary() {
        return ydlEnd.exists();
    }

    public void install() throws IOException {
        FileUtils.copyURLToFile(new URL(remoteFile), ydlEnd, 20000, 20000);
        ydlEnd.setExecutable(true);
    }
}

Nulla di eclatante...

Cercando in giro ho trovato la soluzione usando la libreria Bouncy Castle, installabile così usando Maven:

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.58</version>
        </dependency>

A questo punto ci basta modificare il codice così:

public class InstallYDL {

    private String os = System.getProperty("os.name");
    private String remoteFile = null;
    private String fileYdl;
    private File ydlEnd;

    public InstallYDL() {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
        if (os.contains("Windows")) {
            remoteFile = "...";
            fileYdl = "ydl.exe";
        } else {
            remoteFile = "...";
            fileYdl = "ydl";
        }
        ydlEnd = new File(System.getProperty("user.home") + "/" + fileYdl);
    }

    public boolean checkLibrary() {
        return ydlEnd.exists();
    }

    public void install() throws IOException {
        FileUtils.copyURLToFile(new URL(remoteFile), ydlEnd, 20000, 20000);
        ydlEnd.setExecutable(true);
    }
}

Quindi aggiungendo questa riga prima di qualsiasi connessione:

Security.insertProviderAt(new BouncyCastleProvider(), 1);

Enjoy!


Condividi

Commentami!