Search in sources :

Example 1 with DigestPasswordSpec

use of org.wildfly.security.password.spec.DigestPasswordSpec in project quarkus by quarkusio.

the class ElytronPropertiesFileRecorder method loadRealm.

/**
 * Load the embedded user and role information into the {@linkplain SecurityRealm}
 *
 * @param realm - a {@linkplain SimpleMapBackedSecurityRealm}
 * @param config - the realm config
 * @throws Exception
 */
public Runnable loadRealm(RuntimeValue<SecurityRealm> realm, MPRealmConfig config, MPRealmRuntimeConfig runtimeConfig) throws Exception {
    return new Runnable() {

        @Override
        public void run() {
            log.debugf("loadRealm, config=%s", config);
            SecurityRealm secRealm = realm.getValue();
            if (!(secRealm instanceof SimpleMapBackedSecurityRealm)) {
                return;
            }
            SimpleMapBackedSecurityRealm memRealm = (SimpleMapBackedSecurityRealm) secRealm;
            HashMap<String, SimpleRealmEntry> identityMap = new HashMap<>();
            Map<String, String> userInfo = runtimeConfig.users;
            log.debugf("UserInfoMap: %s%n", userInfo);
            Map<String, String> roleInfo = runtimeConfig.roles;
            log.debugf("RoleInfoMap: %s%n", roleInfo);
            for (Map.Entry<String, String> userPasswordEntry : userInfo.entrySet()) {
                Password password;
                String user = userPasswordEntry.getKey();
                if (runtimeConfig.plainText) {
                    password = ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, userPasswordEntry.getValue().toCharArray());
                } else {
                    try {
                        byte[] hashed = ByteIterator.ofBytes(userPasswordEntry.getValue().getBytes(StandardCharsets.UTF_8)).asUtf8String().hexDecode().drain();
                        password = PasswordFactory.getInstance(runtimeConfig.algorithm.getName(), new WildFlyElytronPasswordProvider()).generatePassword(new DigestPasswordSpec(user, config.realmName, hashed));
                    } catch (Exception e) {
                        throw new RuntimeException("Unable to register password for user:" + user + " make sure it is a valid hex encoded MD5 hash", e);
                    }
                }
                PasswordCredential passwordCred = new PasswordCredential(password);
                List<Credential> credentials = new ArrayList<>();
                credentials.add(passwordCred);
                String rawRoles = roleInfo.get(user);
                String[] roles = rawRoles != null ? rawRoles.split(",") : new String[0];
                Attributes attributes = new MapAttributes();
                for (String role : roles) {
                    attributes.addLast("groups", role);
                }
                SimpleRealmEntry entry = new SimpleRealmEntry(credentials, attributes);
                identityMap.put(user, entry);
                log.debugf("Added user(%s), roles=%s%n", user, attributes.get("groups"));
            }
            memRealm.setIdentityMap(identityMap);
        }
    };
}
Also used : SimpleMapBackedSecurityRealm(org.wildfly.security.auth.realm.SimpleMapBackedSecurityRealm) PasswordCredential(org.wildfly.security.credential.PasswordCredential) Credential(org.wildfly.security.credential.Credential) SimpleRealmEntry(org.wildfly.security.auth.realm.SimpleRealmEntry) HashMap(java.util.HashMap) SimpleMapBackedSecurityRealm(org.wildfly.security.auth.realm.SimpleMapBackedSecurityRealm) SecurityRealm(org.wildfly.security.auth.server.SecurityRealm) LegacyPropertiesSecurityRealm(org.wildfly.security.auth.realm.LegacyPropertiesSecurityRealm) PasswordCredential(org.wildfly.security.credential.PasswordCredential) ArrayList(java.util.ArrayList) MapAttributes(org.wildfly.security.authz.MapAttributes) Attributes(org.wildfly.security.authz.Attributes) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) WildFlyElytronPasswordProvider(org.wildfly.security.password.WildFlyElytronPasswordProvider) MapAttributes(org.wildfly.security.authz.MapAttributes) HashMap(java.util.HashMap) Map(java.util.Map) Password(org.wildfly.security.password.Password) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec)

Example 2 with DigestPasswordSpec

use of org.wildfly.security.password.spec.DigestPasswordSpec in project wildfly-elytron by wildfly-security.

the class PasswordFactorySpiImpl method engineGeneratePassword.

@Override
protected Password engineGeneratePassword(final String algorithm, final KeySpec keySpec) throws InvalidKeySpecException {
    switch(algorithm) {
        case ALGORITHM_CLEAR:
            {
                if (keySpec instanceof ClearPasswordSpec) {
                    return new ClearPasswordImpl(((ClearPasswordSpec) keySpec).getEncodedPassword().clone());
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    return new ClearPasswordImpl(((EncryptablePasswordSpec) keySpec).getPassword().clone());
                } else {
                    break;
                }
            }
        case ALGORITHM_BCRYPT:
            {
                if (keySpec instanceof IteratedSaltedHashPasswordSpec) {
                    try {
                        return new BCryptPasswordImpl((IteratedSaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new BCryptPasswordImpl((SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new BCryptPasswordImpl((ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new BCryptPasswordImpl(encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new BCryptPasswordImpl(encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedSaltedPasswordAlgorithmSpec) {
                            return new BCryptPasswordImpl(encryptableSpec.getPassword(), (IteratedSaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedPasswordAlgorithmSpec) {
                            return new BCryptPasswordImpl(encryptableSpec.getPassword(), (IteratedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_CRYPT_MD5:
            {
                if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new UnixMD5CryptPasswordImpl((SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new UnixMD5CryptPasswordImpl((ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new UnixMD5CryptPasswordImpl(encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new UnixMD5CryptPasswordImpl(encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_SUN_CRYPT_MD5:
        case ALGORITHM_SUN_CRYPT_MD5_BARE_SALT:
            {
                if (keySpec instanceof IteratedSaltedHashPasswordSpec) {
                    try {
                        return new SunUnixMD5CryptPasswordImpl(algorithm, (IteratedSaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new SunUnixMD5CryptPasswordImpl(algorithm, (SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new SunUnixMD5CryptPasswordImpl((ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new SunUnixMD5CryptPasswordImpl(algorithm, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new SunUnixMD5CryptPasswordImpl(algorithm, encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedSaltedPasswordAlgorithmSpec) {
                            return new SunUnixMD5CryptPasswordImpl(algorithm, encryptableSpec.getPassword(), (IteratedSaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedPasswordAlgorithmSpec) {
                            return new SunUnixMD5CryptPasswordImpl(algorithm, encryptableSpec.getPassword(), (IteratedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | NullPointerException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_CRYPT_SHA_256:
        case ALGORITHM_CRYPT_SHA_512:
            {
                if (keySpec instanceof IteratedSaltedHashPasswordSpec) {
                    try {
                        return new UnixSHACryptPasswordImpl(algorithm, (IteratedSaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new UnixSHACryptPasswordImpl(algorithm, (SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new UnixSHACryptPasswordImpl(algorithm, (ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new UnixSHACryptPasswordImpl(algorithm, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedPasswordAlgorithmSpec) {
                            return new UnixSHACryptPasswordImpl(algorithm, (IteratedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedSaltedPasswordAlgorithmSpec) {
                            return new UnixSHACryptPasswordImpl(algorithm, (IteratedSaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new UnixSHACryptPasswordImpl(algorithm, (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | NullPointerException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_DIGEST_MD5:
        case ALGORITHM_DIGEST_SHA:
        case ALGORITHM_DIGEST_SHA_256:
        case ALGORITHM_DIGEST_SHA_384:
        case ALGORITHM_DIGEST_SHA_512:
        case ALGORITHM_DIGEST_SHA_512_256:
            if (keySpec instanceof DigestPasswordSpec) {
                return new DigestPasswordImpl(algorithm, (DigestPasswordSpec) keySpec);
            } else if (keySpec instanceof EncryptablePasswordSpec) {
                return new DigestPasswordImpl(algorithm, (EncryptablePasswordSpec) keySpec);
            }
            break;
        case ALGORITHM_SIMPLE_DIGEST_MD2:
        case ALGORITHM_SIMPLE_DIGEST_MD5:
        case ALGORITHM_SIMPLE_DIGEST_SHA_1:
        case ALGORITHM_SIMPLE_DIGEST_SHA_256:
        case ALGORITHM_SIMPLE_DIGEST_SHA_384:
        case ALGORITHM_SIMPLE_DIGEST_SHA_512:
            {
                if (keySpec instanceof HashPasswordSpec) {
                    try {
                        return new SimpleDigestPasswordImpl(algorithm, (HashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new SimpleDigestPasswordImpl(algorithm, (ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new SimpleDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_PASSWORD_SALT_DIGEST_MD5:
        case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_1:
        case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_256:
        case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_384:
        case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_512:
        case ALGORITHM_SALT_PASSWORD_DIGEST_MD5:
        case ALGORITHM_SALT_PASSWORD_DIGEST_SHA_1:
        case ALGORITHM_SALT_PASSWORD_DIGEST_SHA_256:
        case ALGORITHM_SALT_PASSWORD_DIGEST_SHA_384:
        case ALGORITHM_SALT_PASSWORD_DIGEST_SHA_512:
            if (keySpec instanceof SaltedHashPasswordSpec) {
                try {
                    return new SaltedSimpleDigestPasswordImpl(algorithm, (SaltedHashPasswordSpec) keySpec);
                } catch (IllegalArgumentException | NullPointerException e) {
                    throw new InvalidKeySpecException(e);
                }
            } else if (keySpec instanceof ClearPasswordSpec) {
                try {
                    return new SaltedSimpleDigestPasswordImpl(algorithm, (ClearPasswordSpec) keySpec);
                } catch (IllegalArgumentException | NullPointerException e) {
                    throw new InvalidKeySpecException(e);
                }
            } else if (keySpec instanceof EncryptablePasswordSpec) {
                try {
                    final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                    final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                    if (parameterSpec == null) {
                        return new SaltedSimpleDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                    } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                        return new SaltedSimpleDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                    } else {
                        break;
                    }
                } catch (IllegalArgumentException | NullPointerException e) {
                    throw new InvalidKeySpecException(e);
                }
            }
            break;
        case ALGORITHM_CRYPT_DES:
            {
                if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new UnixDESCryptPasswordImpl((SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | InvalidParameterSpecException | InvalidKeyException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new UnixDESCryptPasswordImpl((ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | InvalidKeyException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new UnixDESCryptPasswordImpl(encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new UnixDESCryptPasswordImpl(encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | InvalidParameterSpecException | InvalidKeyException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_BSD_CRYPT_DES:
            {
                if (keySpec instanceof IteratedSaltedHashPasswordSpec) {
                    try {
                        return new BSDUnixDESCryptPasswordImpl((IteratedSaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | InvalidParameterSpecException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new BSDUnixDESCryptPasswordImpl((SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | InvalidParameterSpecException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new BSDUnixDESCryptPasswordImpl((ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new BSDUnixDESCryptPasswordImpl(encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new BSDUnixDESCryptPasswordImpl(encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedSaltedPasswordAlgorithmSpec) {
                            return new BSDUnixDESCryptPasswordImpl(encryptableSpec.getPassword(), (IteratedSaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedPasswordAlgorithmSpec) {
                            return new BSDUnixDESCryptPasswordImpl(encryptableSpec.getPassword(), (IteratedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (InvalidParameterSpecException | IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_SCRAM_SHA_1:
        case ALGORITHM_SCRAM_SHA_256:
        case ALGORITHM_SCRAM_SHA_384:
        case ALGORITHM_SCRAM_SHA_512:
            {
                if (keySpec instanceof IteratedSaltedHashPasswordSpec) {
                    try {
                        return new ScramDigestPasswordImpl(algorithm, (IteratedSaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof SaltedHashPasswordSpec) {
                    try {
                        return new ScramDigestPasswordImpl(algorithm, (SaltedHashPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof ClearPasswordSpec) {
                    try {
                        return new ScramDigestPasswordImpl(algorithm, (ClearPasswordSpec) keySpec);
                    } catch (IllegalArgumentException | NullPointerException | InvalidKeyException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    try {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new ScramDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new ScramDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedSaltedPasswordAlgorithmSpec) {
                            return new ScramDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), (IteratedSaltedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else if (parameterSpec instanceof IteratedPasswordAlgorithmSpec) {
                            return new ScramDigestPasswordImpl(algorithm, encryptableSpec.getPassword(), (IteratedPasswordAlgorithmSpec) parameterSpec, encryptableSpec.getHashCharset());
                        } else {
                            break;
                        }
                    } catch (IllegalArgumentException | NullPointerException | InvalidKeyException | NoSuchAlgorithmException e) {
                        throw new InvalidKeySpecException(e);
                    }
                } else {
                    break;
                }
            }
        case ALGORITHM_OTP_MD5:
        case ALGORITHM_OTP_SHA1:
        case ALGORITHM_OTP_SHA_256:
        case ALGORITHM_OTP_SHA_384:
        case ALGORITHM_OTP_SHA_512:
            {
                if (keySpec instanceof OneTimePasswordSpec) {
                    return new OneTimePasswordImpl(algorithm, (OneTimePasswordSpec) keySpec);
                } else if (keySpec instanceof EncryptablePasswordSpec) {
                    final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                    final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                    try {
                        if (parameterSpec instanceof OneTimePasswordAlgorithmSpec) {
                            return new OneTimePasswordImpl(algorithm, encryptableSpec.getPassword(), (OneTimePasswordAlgorithmSpec) parameterSpec);
                        } else {
                            break;
                        }
                    } catch (SaslException e) {
                        throw new InvalidKeySpecException(e);
                    }
                }
                break;
            }
        default:
            {
                if (MaskedPassword.isMaskedAlgorithm(algorithm)) {
                    if (keySpec instanceof MaskedPasswordSpec) {
                        return new MaskedPasswordImpl(algorithm, (MaskedPasswordSpec) keySpec);
                    } else if (keySpec instanceof EncryptablePasswordSpec) {
                        final EncryptablePasswordSpec encryptableSpec = (EncryptablePasswordSpec) keySpec;
                        final AlgorithmParameterSpec parameterSpec = encryptableSpec.getAlgorithmParameterSpec();
                        if (parameterSpec == null) {
                            return new MaskedPasswordImpl(algorithm, encryptableSpec.getPassword());
                        } else if (parameterSpec instanceof MaskedPasswordAlgorithmSpec) {
                            return new MaskedPasswordImpl(algorithm, encryptableSpec.getPassword(), (MaskedPasswordAlgorithmSpec) parameterSpec);
                        } else if (parameterSpec instanceof IteratedSaltedPasswordAlgorithmSpec) {
                            return new MaskedPasswordImpl(algorithm, encryptableSpec.getPassword(), (IteratedSaltedPasswordAlgorithmSpec) parameterSpec);
                        } else if (parameterSpec instanceof SaltedPasswordAlgorithmSpec) {
                            return new MaskedPasswordImpl(algorithm, encryptableSpec.getPassword(), (SaltedPasswordAlgorithmSpec) parameterSpec);
                        } else if (parameterSpec instanceof IteratedPasswordAlgorithmSpec) {
                            return new MaskedPasswordImpl(algorithm, encryptableSpec.getPassword(), (IteratedPasswordAlgorithmSpec) parameterSpec);
                        }
                    } else if (keySpec instanceof ClearPasswordSpec) {
                        return new MaskedPasswordImpl(algorithm, (ClearPasswordSpec) keySpec);
                    }
                    break;
                }
                break;
            }
    }
    throw log.invalidKeySpecUnknownAlgorithmOrIncompatiblePasswordSpec(algorithm, keySpec == null ? null : keySpec.getClass().getSimpleName());
}
Also used : MaskedPasswordSpec(org.wildfly.security.password.spec.MaskedPasswordSpec) IteratedSaltedPasswordAlgorithmSpec(org.wildfly.security.password.spec.IteratedSaltedPasswordAlgorithmSpec) SaltedPasswordAlgorithmSpec(org.wildfly.security.password.spec.SaltedPasswordAlgorithmSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) EncryptablePasswordSpec(org.wildfly.security.password.spec.EncryptablePasswordSpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SaslException(javax.security.sasl.SaslException) OneTimePasswordSpec(org.wildfly.security.password.spec.OneTimePasswordSpec) IteratedSaltedPasswordAlgorithmSpec(org.wildfly.security.password.spec.IteratedSaltedPasswordAlgorithmSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) HashPasswordSpec(org.wildfly.security.password.spec.HashPasswordSpec) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) InvalidKeyException(java.security.InvalidKeyException) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) IteratedPasswordAlgorithmSpec(org.wildfly.security.password.spec.IteratedPasswordAlgorithmSpec) OneTimePasswordAlgorithmSpec(org.wildfly.security.password.spec.OneTimePasswordAlgorithmSpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) MaskedPasswordAlgorithmSpec(org.wildfly.security.password.spec.MaskedPasswordAlgorithmSpec) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec)

Example 3 with DigestPasswordSpec

use of org.wildfly.security.password.spec.DigestPasswordSpec in project wildfly-elytron by wildfly-security.

the class DigestPasswordTest method performTest.

private void performTest(final String algorithm, final String expectedHexDigest) throws Exception {
    byte[] preDigested = CodePointIterator.ofString(expectedHexDigest).hexDecode().drain();
    PasswordFactory factory = PasswordFactory.getInstance(algorithm);
    DigestPasswordAlgorithmSpec dpas = new DigestPasswordAlgorithmSpec(USERNAME, REALM);
    EncryptablePasswordSpec encryptableSpec = new EncryptablePasswordSpec(PASSWORD.toCharArray(), dpas);
    DigestPassword digestPassword = (DigestPassword) factory.generatePassword(encryptableSpec);
    validatePassword(digestPassword, PASSWORD, preDigested, factory);
    assertTrue("Convertable to key spec", factory.convertibleToKeySpec(digestPassword, DigestPasswordSpec.class));
    DigestPasswordSpec digestSpec = factory.getKeySpec(digestPassword, DigestPasswordSpec.class);
    assertTrue("Digest Correctly Generated", Arrays.equals(preDigested, digestSpec.getDigest()));
    digestSpec = new DigestPasswordSpec(USERNAME, REALM, preDigested);
    digestPassword = (DigestPassword) factory.generatePassword(digestSpec);
    validatePassword(digestPassword, PASSWORD, preDigested, factory);
}
Also used : DigestPassword(org.wildfly.security.password.interfaces.DigestPassword) PasswordFactory(org.wildfly.security.password.PasswordFactory) DigestPasswordAlgorithmSpec(org.wildfly.security.password.spec.DigestPasswordAlgorithmSpec) EncryptablePasswordSpec(org.wildfly.security.password.spec.EncryptablePasswordSpec) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec)

Example 4 with DigestPasswordSpec

use of org.wildfly.security.password.spec.DigestPasswordSpec in project wildfly-elytron by wildfly-security.

the class LegacyPropertiesSecurityRealm method getRealmIdentity.

@Override
public RealmIdentity getRealmIdentity(final Principal principal) throws RealmUnavailableException {
    if (!(principal instanceof NamePrincipal)) {
        log.tracef("PropertiesRealm: unsupported principal type: [%s]", principal);
        return RealmIdentity.NON_EXISTENT;
    }
    final LoadedState loadedState = this.loadedState.get();
    final AccountEntry accountEntry = loadedState.getAccounts().get(principal.getName());
    if (accountEntry == null) {
        log.tracef("PropertiesRealm: identity [%s] does not exist", principal);
        return RealmIdentity.NON_EXISTENT;
    }
    return new RealmIdentity() {

        public Principal getRealmIdentityPrincipal() {
            return principal;
        }

        @Override
        public SupportLevel getCredentialAcquireSupport(final Class<? extends Credential> credentialType, final String algorithmName, final AlgorithmParameterSpec parameterSpec) throws RealmUnavailableException {
            return LegacyPropertiesSecurityRealm.this.getCredentialAcquireSupport(credentialType, algorithmName, parameterSpec);
        }

        @Override
        public SupportLevel getEvidenceVerifySupport(final Class<? extends Evidence> evidenceType, final String algorithmName) throws RealmUnavailableException {
            return LegacyPropertiesSecurityRealm.this.getEvidenceVerifySupport(evidenceType, algorithmName);
        }

        @Override
        public <C extends Credential> C getCredential(final Class<C> credentialType) throws RealmUnavailableException {
            return getCredential(credentialType, null, null);
        }

        @Override
        public <C extends Credential> C getCredential(final Class<C> credentialType, final String algorithmName) throws RealmUnavailableException {
            return getCredential(credentialType, algorithmName, null);
        }

        @Override
        public <C extends Credential> C getCredential(final Class<C> credentialType, final String algorithmName, final AlgorithmParameterSpec parameterSpec) throws RealmUnavailableException {
            if (accountEntry.getPasswordRepresentation() == null || LegacyPropertiesSecurityRealm.this.getCredentialAcquireSupport(credentialType, algorithmName, parameterSpec) == SupportLevel.UNSUPPORTED) {
                log.tracef("PropertiesRealm: Unable to obtain credential for identity [%s]", principal);
                return null;
            }
            // whether should be clear or digested credential returned
            boolean clear;
            if (algorithmName == null) {
                clear = plainText;
            } else if (ALGORITHM_CLEAR.equals(algorithmName)) {
                clear = true;
            } else if (ALGORITHM_DIGEST_MD5.equals(algorithmName)) {
                clear = false;
            } else {
                log.tracef("PropertiesRealm: Unable to obtain credential for identity [%s]: unsupported algorithm [%s]", principal, algorithmName);
                return null;
            }
            final PasswordFactory passwordFactory;
            final PasswordSpec passwordSpec;
            if (clear) {
                passwordFactory = getPasswordFactory(ALGORITHM_CLEAR);
                passwordSpec = new ClearPasswordSpec(accountEntry.getPasswordRepresentation().toCharArray());
            } else {
                passwordFactory = getPasswordFactory(ALGORITHM_DIGEST_MD5);
                if (plainText) {
                    // file contains clear passwords - needs to be digested
                    AlgorithmParameterSpec spec = parameterSpec != null ? parameterSpec : new DigestPasswordAlgorithmSpec(accountEntry.getName(), loadedState.getRealmName());
                    passwordSpec = new EncryptablePasswordSpec(accountEntry.getPasswordRepresentation().toCharArray(), spec);
                } else {
                    // already digested file - need to check realm name
                    if (parameterSpec != null) {
                        // when not null, type already checked in acquire support check
                        DigestPasswordAlgorithmSpec spec = (DigestPasswordAlgorithmSpec) parameterSpec;
                        if (!loadedState.getRealmName().equals(spec.getRealm()) || !accountEntry.getName().equals(spec.getUsername())) {
                            if (log.isTraceEnabled()) {
                                log.tracef("PropertiesRealm: Unable to obtain credential for username [%s] (available [%s]) and realm [%s] (available [%s])", spec.getUsername(), accountEntry.getName(), spec.getRealm(), loadedState.getRealmName());
                            }
                            // no digest for given username+realm
                            return null;
                        }
                    }
                    byte[] hashed;
                    if (hashEncoding.equals(Encoding.BASE64)) {
                        hashed = ByteIterator.ofBytes(accountEntry.getPasswordRepresentation().getBytes(hashCharset)).asUtf8String().base64Decode().drain();
                    } else {
                        // use hex by default otherwise
                        hashed = ByteIterator.ofBytes(accountEntry.getPasswordRepresentation().getBytes(hashCharset)).asUtf8String().hexDecode().drain();
                    }
                    passwordSpec = new DigestPasswordSpec(accountEntry.getName(), loadedState.getRealmName(), hashed);
                }
            }
            try {
                return credentialType.cast(new PasswordCredential(passwordFactory.generatePassword(passwordSpec)));
            } catch (InvalidKeySpecException e) {
                throw new IllegalStateException(e);
            }
        }

        @Override
        public boolean verifyEvidence(final Evidence evidence) throws RealmUnavailableException {
            if (accountEntry.getPasswordRepresentation() == null || !(evidence instanceof PasswordGuessEvidence)) {
                log.tracef("Unable to verify evidence for identity [%s]", principal);
                return false;
            }
            final char[] guess = ((PasswordGuessEvidence) evidence).getGuess();
            final PasswordFactory passwordFactory;
            final PasswordSpec passwordSpec;
            final Password actualPassword;
            if (plainText) {
                passwordFactory = getPasswordFactory(ALGORITHM_CLEAR);
                passwordSpec = new ClearPasswordSpec(accountEntry.getPasswordRepresentation().toCharArray());
            } else {
                passwordFactory = getPasswordFactory(ALGORITHM_DIGEST_MD5);
                try {
                    byte[] hashed;
                    if (hashEncoding.equals(Encoding.BASE64)) {
                        hashed = ByteIterator.ofBytes(accountEntry.getPasswordRepresentation().getBytes(hashCharset)).asUtf8String().base64Decode().drain();
                    } else {
                        // use hex by default otherwise
                        hashed = ByteIterator.ofBytes(accountEntry.getPasswordRepresentation().getBytes(hashCharset)).asUtf8String().hexDecode().drain();
                    }
                    passwordSpec = new DigestPasswordSpec(accountEntry.getName(), loadedState.getRealmName(), hashed);
                } catch (DecodeException e) {
                    throw log.decodingHashedPasswordFromPropertiesRealmFailed(e);
                }
            }
            try {
                log.tracef("Attempting to authenticate account %s using LegacyPropertiesSecurityRealm.", accountEntry.getName());
                actualPassword = passwordFactory.generatePassword(passwordSpec);
                return passwordFactory.verify(actualPassword, guess, hashCharset);
            } catch (InvalidKeySpecException | InvalidKeyException | IllegalStateException e) {
                throw new IllegalStateException(e);
            }
        }

        public boolean exists() throws RealmUnavailableException {
            return true;
        }

        @Override
        public AuthorizationIdentity getAuthorizationIdentity() throws RealmUnavailableException {
            return AuthorizationIdentity.basicIdentity(new MapAttributes(Collections.singletonMap(groupsAttribute, accountEntry.getGroups())));
        }
    };
}
Also used : ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) PasswordSpec(org.wildfly.security.password.spec.PasswordSpec) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec) EncryptablePasswordSpec(org.wildfly.security.password.spec.EncryptablePasswordSpec) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(org.wildfly.security.credential.PasswordCredential) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) EncryptablePasswordSpec(org.wildfly.security.password.spec.EncryptablePasswordSpec) Evidence(org.wildfly.security.evidence.Evidence) PasswordGuessEvidence(org.wildfly.security.evidence.PasswordGuessEvidence) RealmIdentity(org.wildfly.security.auth.server.RealmIdentity) DigestPasswordAlgorithmSpec(org.wildfly.security.password.spec.DigestPasswordAlgorithmSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Password(org.wildfly.security.password.Password) PasswordCredential(org.wildfly.security.credential.PasswordCredential) Credential(org.wildfly.security.credential.Credential) InvalidKeyException(java.security.InvalidKeyException) DecodeException(org.wildfly.common.codec.DecodeException) PasswordFactory(org.wildfly.security.password.PasswordFactory) MapAttributes(org.wildfly.security.authz.MapAttributes) PasswordGuessEvidence(org.wildfly.security.evidence.PasswordGuessEvidence) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec)

Example 5 with DigestPasswordSpec

use of org.wildfly.security.password.spec.DigestPasswordSpec in project wildfly-elytron by wildfly-security.

the class KeyStoreCredentialStore method store.

public void store(final String credentialAlias, final Credential credential, final CredentialStore.ProtectionParameter protectionParameter) throws CredentialStoreException {
    try {
        // first, attempt to encode the credential into a keystore entry
        final Class<? extends Credential> credentialClass = credential.getClass();
        final String algorithmName = credential instanceof AlgorithmCredential ? ((AlgorithmCredential) credential).getAlgorithm() : null;
        final AlgorithmParameterSpec parameterSpec = credential.castAndApply(AlgorithmCredential.class, AlgorithmCredential::getParameters);
        final KeyStore.Entry entry;
        if (credentialClass == SecretKeyCredential.class) {
            entry = new KeyStore.SecretKeyEntry(credential.castAndApply(SecretKeyCredential.class, SecretKeyCredential::getSecretKey));
        } else if (credentialClass == PublicKeyCredential.class) {
            final PublicKey publicKey = credential.castAndApply(PublicKeyCredential.class, PublicKeyCredential::getPublicKey);
            final KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm());
            final X509EncodedKeySpec keySpec = keyFactory.getKeySpec(keyFactory.translateKey(publicKey), X509EncodedKeySpec.class);
            final byte[] encoded = keySpec.getEncoded();
            entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(encoded, DATA_OID));
        } else if (credentialClass == KeyPairCredential.class) {
            final KeyPair keyPair = credential.castAndApply(KeyPairCredential.class, KeyPairCredential::getKeyPair);
            final PublicKey publicKey = keyPair.getPublic();
            final PrivateKey privateKey = keyPair.getPrivate();
            final KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm());
            // ensured by KeyPairCredential
            assert privateKey.getAlgorithm().equals(publicKey.getAlgorithm());
            final X509EncodedKeySpec publicSpec = keyFactory.getKeySpec(keyFactory.translateKey(publicKey), X509EncodedKeySpec.class);
            final PKCS8EncodedKeySpec privateSpec = keyFactory.getKeySpec(keyFactory.translateKey(privateKey), PKCS8EncodedKeySpec.class);
            final DEREncoder encoder = new DEREncoder();
            encoder.startSequence();
            encoder.writeEncoded(publicSpec.getEncoded());
            encoder.writeEncoded(privateSpec.getEncoded());
            encoder.endSequence();
            entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(encoder.getEncoded(), DATA_OID));
        } else if (credentialClass == X509CertificateChainPublicCredential.class) {
            final X509Certificate[] x509Certificates = credential.castAndApply(X509CertificateChainPublicCredential.class, X509CertificateChainPublicCredential::getCertificateChain);
            final DEREncoder encoder = new DEREncoder();
            encoder.encodeInteger(x509Certificates.length);
            encoder.startSequence();
            for (X509Certificate x509Certificate : x509Certificates) {
                encoder.writeEncoded(x509Certificate.getEncoded());
            }
            encoder.endSequence();
            entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(encoder.getEncoded(), DATA_OID));
        } else if (credentialClass == X509CertificateChainPrivateCredential.class) {
            @SuppressWarnings("ConstantConditions") X509CertificateChainPrivateCredential cred = (X509CertificateChainPrivateCredential) credential;
            entry = new KeyStore.PrivateKeyEntry(cred.getPrivateKey(), cred.getCertificateChain());
        } else if (credentialClass == BearerTokenCredential.class) {
            entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(credential.castAndApply(BearerTokenCredential.class, c -> c.getToken().getBytes(StandardCharsets.UTF_8)), DATA_OID));
        } else if (credentialClass == PasswordCredential.class) {
            final Password password = credential.castAndApply(PasswordCredential.class, PasswordCredential::getPassword);
            final String algorithm = password.getAlgorithm();
            final DEREncoder encoder = new DEREncoder();
            final PasswordFactory passwordFactory = providers != null ? PasswordFactory.getInstance(algorithm, () -> providers) : PasswordFactory.getInstance(algorithm);
            switch(algorithm) {
                case BCryptPassword.ALGORITHM_BCRYPT:
                case BSDUnixDESCryptPassword.ALGORITHM_BSD_CRYPT_DES:
                case ScramDigestPassword.ALGORITHM_SCRAM_SHA_1:
                case ScramDigestPassword.ALGORITHM_SCRAM_SHA_256:
                case ScramDigestPassword.ALGORITHM_SCRAM_SHA_384:
                case ScramDigestPassword.ALGORITHM_SCRAM_SHA_512:
                case SunUnixMD5CryptPassword.ALGORITHM_SUN_CRYPT_MD5:
                case SunUnixMD5CryptPassword.ALGORITHM_SUN_CRYPT_MD5_BARE_SALT:
                case UnixSHACryptPassword.ALGORITHM_CRYPT_SHA_256:
                case UnixSHACryptPassword.ALGORITHM_CRYPT_SHA_512:
                    {
                        IteratedSaltedHashPasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), IteratedSaltedHashPasswordSpec.class);
                        encoder.startSequence();
                        encoder.encodeOctetString(passwordSpec.getHash());
                        encoder.encodeOctetString(passwordSpec.getSalt());
                        encoder.encodeInteger(passwordSpec.getIterationCount());
                        encoder.endSequence();
                        break;
                    }
                case ClearPassword.ALGORITHM_CLEAR:
                    {
                        final ClearPasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), ClearPasswordSpec.class);
                        encoder.encodeOctetString(new String(passwordSpec.getEncodedPassword()));
                        break;
                    }
                case DigestPassword.ALGORITHM_DIGEST_MD5:
                case DigestPassword.ALGORITHM_DIGEST_SHA:
                case DigestPassword.ALGORITHM_DIGEST_SHA_256:
                case DigestPassword.ALGORITHM_DIGEST_SHA_384:
                case DigestPassword.ALGORITHM_DIGEST_SHA_512:
                case DigestPassword.ALGORITHM_DIGEST_SHA_512_256:
                    {
                        final DigestPasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), DigestPasswordSpec.class);
                        encoder.startSequence();
                        encoder.encodeOctetString(passwordSpec.getUsername());
                        encoder.encodeOctetString(passwordSpec.getRealm());
                        encoder.encodeOctetString(passwordSpec.getDigest());
                        encoder.endSequence();
                        break;
                    }
                case OneTimePassword.ALGORITHM_OTP_MD5:
                case OneTimePassword.ALGORITHM_OTP_SHA1:
                case OneTimePassword.ALGORITHM_OTP_SHA_256:
                case OneTimePassword.ALGORITHM_OTP_SHA_384:
                case OneTimePassword.ALGORITHM_OTP_SHA_512:
                    {
                        final OneTimePasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), OneTimePasswordSpec.class);
                        encoder.startSequence();
                        encoder.encodeOctetString(passwordSpec.getHash());
                        encoder.encodeIA5String(passwordSpec.getSeed());
                        encoder.encodeInteger(passwordSpec.getSequenceNumber());
                        encoder.endSequence();
                        break;
                    }
                case SaltedSimpleDigestPassword.ALGORITHM_PASSWORD_SALT_DIGEST_MD5:
                case SaltedSimpleDigestPassword.ALGORITHM_PASSWORD_SALT_DIGEST_SHA_1:
                case SaltedSimpleDigestPassword.ALGORITHM_PASSWORD_SALT_DIGEST_SHA_256:
                case SaltedSimpleDigestPassword.ALGORITHM_PASSWORD_SALT_DIGEST_SHA_384:
                case SaltedSimpleDigestPassword.ALGORITHM_PASSWORD_SALT_DIGEST_SHA_512:
                case SaltedSimpleDigestPassword.ALGORITHM_SALT_PASSWORD_DIGEST_MD5:
                case SaltedSimpleDigestPassword.ALGORITHM_SALT_PASSWORD_DIGEST_SHA_1:
                case SaltedSimpleDigestPassword.ALGORITHM_SALT_PASSWORD_DIGEST_SHA_256:
                case SaltedSimpleDigestPassword.ALGORITHM_SALT_PASSWORD_DIGEST_SHA_384:
                case SaltedSimpleDigestPassword.ALGORITHM_SALT_PASSWORD_DIGEST_SHA_512:
                case UnixDESCryptPassword.ALGORITHM_CRYPT_DES:
                case UnixMD5CryptPassword.ALGORITHM_CRYPT_MD5:
                    {
                        final SaltedHashPasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), SaltedHashPasswordSpec.class);
                        encoder.startSequence();
                        encoder.encodeOctetString(passwordSpec.getHash());
                        encoder.encodeOctetString(passwordSpec.getSalt());
                        encoder.endSequence();
                        break;
                    }
                case SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_MD2:
                case SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_MD5:
                case SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_SHA_1:
                case SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_SHA_256:
                case SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_SHA_384:
                case SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_SHA_512:
                    {
                        final HashPasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), HashPasswordSpec.class);
                        encoder.startSequence();
                        encoder.encodeOctetString(passwordSpec.getDigest());
                        encoder.endSequence();
                        break;
                    }
                default:
                    {
                        if (MaskedPassword.isMaskedAlgorithm(algorithmName)) {
                            final MaskedPasswordSpec passwordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), MaskedPasswordSpec.class);
                            encoder.startSequence();
                            encoder.encodeOctetString(new String(passwordSpec.getInitialKeyMaterial()));
                            encoder.encodeInteger(passwordSpec.getIterationCount());
                            encoder.encodeOctetString(passwordSpec.getSalt());
                            encoder.encodeOctetString(passwordSpec.getMaskedPasswordBytes());
                            encoder.endSequence();
                            break;
                        } else {
                            throw log.unsupportedCredentialType(credentialClass);
                        }
                    }
            }
            entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(encoder.getEncoded(), DATA_OID));
        } else {
            throw log.unsupportedCredentialType(credentialClass);
        }
        // now, store it under a unique alias
        final String ksAlias = calculateNewAlias(credentialAlias, credentialClass, algorithmName, parameterSpec);
        try (Hold hold = lockForWrite()) {
            keyStore.setEntry(ksAlias, entry, convertParameter(protectionParameter));
            final TopEntry topEntry = cache.computeIfAbsent(toLowercase(credentialAlias), TopEntry::new);
            final MidEntry midEntry = topEntry.getMap().computeIfAbsent(credentialClass, c -> new MidEntry(topEntry, c));
            final BottomEntry bottomEntry;
            if (algorithmName != null) {
                bottomEntry = midEntry.getMap().computeIfAbsent(algorithmName, n -> new BottomEntry(midEntry, n));
            } else {
                bottomEntry = midEntry.getOrCreateNoAlgorithm();
            }
            final String oldAlias;
            if (parameterSpec != null) {
                oldAlias = bottomEntry.getMap().put(new ParamKey(parameterSpec), ksAlias);
            } else {
                oldAlias = bottomEntry.setNoParams(ksAlias);
            }
            if (oldAlias != null && !oldAlias.equals(ksAlias)) {
                // unlikely but possible
                keyStore.deleteEntry(oldAlias);
            }
        }
    } catch (KeyStoreException | NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | CertificateException e) {
        throw log.cannotWriteCredentialToStore(e);
    }
}
Also used : MaskedPasswordSpec(org.wildfly.security.password.spec.MaskedPasswordSpec) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) Enumeration(java.util.Enumeration) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeyStoreException(java.security.KeyStoreException) CodePointIterator(org.wildfly.common.iteration.CodePointIterator) KeyUtil(org.wildfly.security.key.KeyUtil) UnixSHACryptPassword(org.wildfly.security.password.interfaces.UnixSHACryptPassword) GeneralSecurityException(java.security.GeneralSecurityException) Matcher(java.util.regex.Matcher) Map(java.util.Map) MaskedPasswordSpec(org.wildfly.security.password.spec.MaskedPasswordSpec) PasswordSpec(org.wildfly.security.password.spec.PasswordSpec) Path(java.nio.file.Path) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) EmptyProvider(org.wildfly.security.EmptyProvider) Assert(org.wildfly.common.Assert) Set(java.util.Set) DEREncoder(org.wildfly.security.asn1.DEREncoder) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) StandardCharsets(java.nio.charset.StandardCharsets) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) BearerTokenCredential(org.wildfly.security.credential.BearerTokenCredential) SecretKey(javax.crypto.SecretKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DERDecoder(org.wildfly.security.asn1.DERDecoder) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) PasswordFactory(org.wildfly.security.password.PasswordFactory) AlgorithmCredential(org.wildfly.security.credential.AlgorithmCredential) OneTimePassword(org.wildfly.security.password.interfaces.OneTimePassword) IvParameterSpec(javax.crypto.spec.IvParameterSpec) PasswordCredential(org.wildfly.security.credential.PasswordCredential) ObjectOutputStream(java.io.ObjectOutputStream) SecretKeyCredential(org.wildfly.security.credential.SecretKeyCredential) HashPasswordSpec(org.wildfly.security.password.spec.HashPasswordSpec) Files(java.nio.file.Files) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec) DigestPassword(org.wildfly.security.password.interfaces.DigestPassword) BCryptPassword(org.wildfly.security.password.interfaces.BCryptPassword) IOException(java.io.IOException) MaskedPassword(org.wildfly.security.password.interfaces.MaskedPassword) Paths(java.nio.file.Paths) CredentialStoreSpi(org.wildfly.security.credential.store.CredentialStoreSpi) AtomicFileOutputStream(org.wildfly.security.util.AtomicFileOutputStream) ScramDigestPassword(org.wildfly.security.password.interfaces.ScramDigestPassword) X509Certificate(java.security.cert.X509Certificate) ByteIterator(org.wildfly.common.iteration.ByteIterator) CertificateFactory(java.security.cert.CertificateFactory) X509CertificateChainPublicCredential(org.wildfly.security.credential.X509CertificateChainPublicCredential) ObjectInputStream(java.io.ObjectInputStream) Security(java.security.Security) OneTimePasswordSpec(org.wildfly.security.password.spec.OneTimePasswordSpec) SunUnixMD5CryptPassword(org.wildfly.security.password.interfaces.SunUnixMD5CryptPassword) CredentialSource(org.wildfly.security.credential.source.CredentialSource) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) UnrecoverableEntryException(java.security.UnrecoverableEntryException) UnixMD5CryptPassword(org.wildfly.security.password.interfaces.UnixMD5CryptPassword) CredentialStore(org.wildfly.security.credential.store.CredentialStore) PublicKeyCredential(org.wildfly.security.credential.PublicKeyCredential) KeyStore(java.security.KeyStore) KeyPairCredential(org.wildfly.security.credential.KeyPairCredential) KeyFactory(java.security.KeyFactory) Provider(java.security.Provider) List(java.util.List) Certificate(java.security.cert.Certificate) Pattern(java.util.regex.Pattern) SimpleDigestPassword(org.wildfly.security.password.interfaces.SimpleDigestPassword) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) X500(org.wildfly.security.x500.X500) HashMap(java.util.HashMap) Cipher(javax.crypto.Cipher) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) HashSet(java.util.HashSet) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) ElytronMessages.log(org.wildfly.security.credential.store._private.ElytronMessages.log) UnixDESCryptPassword(org.wildfly.security.password.interfaces.UnixDESCryptPassword) OutputStream(java.io.OutputStream) X509CertificateChainPrivateCredential(org.wildfly.security.credential.X509CertificateChainPrivateCredential) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) Iterator(java.util.Iterator) ASN1Exception(org.wildfly.security.asn1.ASN1Exception) PublicKey(java.security.PublicKey) CertificateException(java.security.cert.CertificateException) Base32Alphabet(org.wildfly.common.codec.Base32Alphabet) AlgorithmParameters(java.security.AlgorithmParameters) BadPaddingException(javax.crypto.BadPaddingException) SaltedSimpleDigestPassword(org.wildfly.security.password.interfaces.SaltedSimpleDigestPassword) BSDUnixDESCryptPassword(org.wildfly.security.password.interfaces.BSDUnixDESCryptPassword) Password(org.wildfly.security.password.Password) CredentialStoreException(org.wildfly.security.credential.store.CredentialStoreException) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) Credential(org.wildfly.security.credential.Credential) Collections(java.util.Collections) InputStream(java.io.InputStream) PrivateKey(java.security.PrivateKey) PasswordCredential(org.wildfly.security.credential.PasswordCredential) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) BearerTokenCredential(org.wildfly.security.credential.BearerTokenCredential) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeyCredential(org.wildfly.security.credential.SecretKeyCredential) OneTimePasswordSpec(org.wildfly.security.password.spec.OneTimePasswordSpec) AlgorithmCredential(org.wildfly.security.credential.AlgorithmCredential) DEREncoder(org.wildfly.security.asn1.DEREncoder) SecretKeySpec(javax.crypto.spec.SecretKeySpec) HashPasswordSpec(org.wildfly.security.password.spec.HashPasswordSpec) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) X509CertificateChainPublicCredential(org.wildfly.security.credential.X509CertificateChainPublicCredential) KeyFactory(java.security.KeyFactory) UnixSHACryptPassword(org.wildfly.security.password.interfaces.UnixSHACryptPassword) OneTimePassword(org.wildfly.security.password.interfaces.OneTimePassword) DigestPassword(org.wildfly.security.password.interfaces.DigestPassword) BCryptPassword(org.wildfly.security.password.interfaces.BCryptPassword) MaskedPassword(org.wildfly.security.password.interfaces.MaskedPassword) ScramDigestPassword(org.wildfly.security.password.interfaces.ScramDigestPassword) SunUnixMD5CryptPassword(org.wildfly.security.password.interfaces.SunUnixMD5CryptPassword) UnixMD5CryptPassword(org.wildfly.security.password.interfaces.UnixMD5CryptPassword) SimpleDigestPassword(org.wildfly.security.password.interfaces.SimpleDigestPassword) UnixDESCryptPassword(org.wildfly.security.password.interfaces.UnixDESCryptPassword) SaltedSimpleDigestPassword(org.wildfly.security.password.interfaces.SaltedSimpleDigestPassword) BSDUnixDESCryptPassword(org.wildfly.security.password.interfaces.BSDUnixDESCryptPassword) Password(org.wildfly.security.password.Password) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) KeyPair(java.security.KeyPair) X509CertificateChainPrivateCredential(org.wildfly.security.credential.X509CertificateChainPrivateCredential) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) PublicKeyCredential(org.wildfly.security.credential.PublicKeyCredential) KeyStoreException(java.security.KeyStoreException) InvalidKeyException(java.security.InvalidKeyException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) PasswordFactory(org.wildfly.security.password.PasswordFactory) KeyPairCredential(org.wildfly.security.credential.KeyPairCredential) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec)

Aggregations

DigestPasswordSpec (org.wildfly.security.password.spec.DigestPasswordSpec)7 PasswordCredential (org.wildfly.security.credential.PasswordCredential)5 PasswordFactory (org.wildfly.security.password.PasswordFactory)5 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 Password (org.wildfly.security.password.Password)4 DigestPassword (org.wildfly.security.password.interfaces.DigestPassword)4 ClearPasswordSpec (org.wildfly.security.password.spec.ClearPasswordSpec)4 PasswordSpec (org.wildfly.security.password.spec.PasswordSpec)4 IOException (java.io.IOException)3 InvalidKeyException (java.security.InvalidKeyException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)3 HashMap (java.util.HashMap)3 Credential (org.wildfly.security.credential.Credential)3 ClearPassword (org.wildfly.security.password.interfaces.ClearPassword)3 EncryptablePasswordSpec (org.wildfly.security.password.spec.EncryptablePasswordSpec)3 HashPasswordSpec (org.wildfly.security.password.spec.HashPasswordSpec)3 IteratedSaltedHashPasswordSpec (org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec)3 MaskedPasswordSpec (org.wildfly.security.password.spec.MaskedPasswordSpec)3 OneTimePasswordSpec (org.wildfly.security.password.spec.OneTimePasswordSpec)3