Search code examples
javasshsftpjschsshd

SFTP connection Failed due to java.security.InvalidAlgorithmParameterException


I am trying to connect to password less configured server using SFTP. Sftp connection is successful using terminal. But when I am connecting in JAVA (using Jsch library) through username and password, I am unable to connect. My java code:-

try {
        try {
            jsch.addIdentity(ftp_Info.getSftpCertFile());
        } catch (Exception e) {
            // TODO: Add a log message
        }
        session = jsch.getSession(ftp_Info.getUserName(), ftp_Info.getHost(), ftp_Info.getPort());
        String pswd = (password_encypted) // password encryption
        session.setPassword(pswd);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("PreferredAuthentications", "password,hostbased,publickey");
        session.connect(); // exception occurred here
        session.setTimeout(connectionTimeOut);
        Channel channel = session.openChannel(SFTP);
        channel.connect();
        sftpChannel = (ChannelSftp) channel;

    } catch (Exception e) {
        log.error(e.getMessage(), e);//error logged here
    }

I am getting following exception :-

com.jcraft.jsch.JSchException: Session.connect: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive) at com.jcraft.jsch.Session.connect(Session.java:485) at com.jcraft.jsch.Session.connect(Session.java:149)

Please help in troubleshooting or resolving it. Is there any way except any third party service provider to make my 2048 bit key pass this exception?


Solution

  • Under 1.7, I will assume you are utilizing maven for your project. I would add the bouncycastle dependency to your pom.

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk16</artifactId>
        <version>1.45</version>
    </dependency>
    

    This should work fine with jdk 7.

    Then add a line of code to add the BouncyCastle provider as the 1st provider.

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

    I would place that prior to your getSftpCertFile() call and prior to any SSL related code. If you are not using Maven or have a different infrastructure, please let me know. You could configure the security provider at the JRE level, but I would always prefer to configure at the project level if possible to not impact other projects.