简体   繁体   English

Spring Integration SFTP:使用 PrivateKey 凭证

[英]Spring Integration SFTP: Using PrivateKey Credentials

I had a few hickups setting up private keys for Spring Integration SFTP.我为 Spring Integration SFTP 设置了一些私钥。

Thought I may share my findings here.想我可以在这里分享我的发现。

I read elsewhere that I should parameterize the JSch object with the private key.我在别处读到我应该用私钥参数化 JSch 对象。 This, however, is not working :但是,这不起作用

 private SessionFactory<ChannelSftp.LsEntry> createSftpSessionFactoryForPrivateKeyCredentials(
      SftpProperties sftpProperties, String sftpUser, String privateKey) throws JSchException {

    byte[] privateKeyBytes = privateKey.getBytes(StandardCharsets.UTF_8);
    JSch javaSecureChannel = javaSecureChannelForPrivateKey(privateKeyBytes);
    DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(javaSecureChannel, true);
    return setCommonConfigProperties(factory, sftpProperties, sftpUser);
  }

  private JSch javaSecureChannelForPrivateKey(byte[] privateKey) throws JSchException {
    JSch javSecureChannel = new JSch();
    javSecureChannel.addIdentity("key", privateKey, /* public key */
        null, /* private key password */ null);
    return javSecureChannel;
  }

Resulting Exception:结果异常:

Caused by: java.lang.IllegalStateException: failed to create SFTP Session
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:404)
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:61)
    at org.springframework.integration.file.remote.session.CachingSessionFactory$1.createForPool(CachingSessionFactory.java:85)
    at org.springframework.integration.file.remote.session.CachingSessionFactory$1.createForPool(CachingSessionFactory.java:82)
    at org.springframework.integration.util.SimplePool.doGetItem(SimplePool.java:200)
    at org.springframework.integration.util.SimplePool.getItem(SimplePool.java:181)
    ... 32 more
Caused by: java.lang.IllegalArgumentException: either a password or a private key is required
    at org.springframework.util.Assert.isTrue(Assert.java:121)
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.initJschSession(DefaultSftpSessionFactory.java:418)
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:393)
    ... 37 more

The solution is to instead set the private key for the session factory:解决方案是改为设置会话工厂的私钥:

DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(new JSch(), true);
byte[] privateKeyBytes = privateKey.getBytes(StandardCharsets.UTF_8);
factory.setPrivateKey(new ByteArrayResource(privateKeyBytes));
return setCommonConfigProperties(factory, sftpProperties, sftpUser);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM