使用 Java 读取存储在 WildFly 的 Elytron 凭据存储中的密码?

Reading passwords stored in WildFly's Elytron credential store using Java?

我在 Wildfly 17.x 凭据存储中存储了几个应用程序密码。如何以编程方式访问凭据存储中存储的密码?

这就是凭据库的创建方式和密码存储方式。

/subsystem=elytron/credential-store=test:add(relative-to=jboss.server.data.dir, location=test.jceks, create=true,credential-reference={clear-text=storepass})

/subsystem=elytron/credential-store=test:add-alias(alias=keystorepw,secret-value=secret)

我用不同的扩展而不是 jceks 创建了商店。一旦修复,我就可以从商店读取密码。花了一些时间才弄清楚,因为 WildFly 在创建商店时没有抱怨,并且除了以编程方式读取它之外,一切正常。

首先原谅我的英文写作。我现在最好的方法是使用此代码,以及库 Maven 版本 1.12.1.Final。其他库,如最近的 Alpha,此代码有错误。

<dependency>
        <groupId>org.wildfly.security</groupId>
        <artifactId>wildfly-elytron</artifactId>
        <version>1.12.1.Final</version>
</dependency>
  

方法

public Password giveMeAPass(String alias) throws NoSuchAlgorithmException, CredentialStoreException, InvalidKeySpecException {
    /*
     * Create a ProtectionParameter for access to the store.
     */
    Password storePassword = ClearPassword.createRaw(
            ClearPassword.ALGORITHM_CLEAR,
            "storepass".toCharArray());

    ProtectionParameter protectionParameter = new CredentialSourceProtectionParameter(
            IdentityCredentials.NONE.withCredential(
                    new PasswordCredential(storePassword)));

    Security.addProvider(elytronProvider);

    CredentialStore credentialStore = CredentialStore.getInstance(
            "KeyStoreCredentialStore", csProvider);
    // Configure and Initialise the CredentialStore
    String configPath = System.getProperty("jboss.server.data.dir");
    Map<String, String> configuration = new HashMap<>();
    
    String path = configPath + File.separator + "test.jceks";
    configuration.put("keyStoreType", "JCEKS");
    configuration.put("location", path);
    configuration.put("modifiable", "false");
    
    //Inicialize credentialStore
    credentialStore.initialize(configuration, protectionParameter);

    return credentialStore.retrieve(alias, PasswordCredential.class).getPassword();
}

此方法基于您的凭据存储。

如果您正在寻找完整的示例,请查看 https://github.com/wildfly-security-incubator/elytron-examples/blob/master/credential-store/src/main/java/org/wildfly/security/examples/CredentialStoreExample.java 您可以在那里看到,cs(那里名为 CREDENTIAL_STORE_PROVIDER)和 elytronProvider(那里名为 PASSWORD_PROVIDER)是通过调用适当的构造函数创建的: private static final Provider CREDENTIAL_STORE_PROVIDER = new WildFlyElytronCredentialStoreProvider(); private static final Provider PASSWORD_PROVIDER = new WildFlyElytronPasswordProvider();