use of org.wildfly.security.password.spec.PasswordSpec in project wildfly-core by wildfly.
the class CustomCredentialSecurityFactoryImpl method create.
@Override
public Credential create() throws GeneralSecurityException {
if (throwException) {
throw new RuntimeException("This exception is expected");
}
final PasswordFactory passwordFactory;
final PasswordSpec passwordSpec;
passwordFactory = getPasswordFactory(ALGORITHM_CLEAR);
passwordSpec = new ClearPasswordSpec("password".toCharArray());
try {
return new PasswordCredential(passwordFactory.generatePassword(passwordSpec));
} catch (InvalidKeySpecException e) {
throw new IllegalStateException(e);
}
}
use of org.wildfly.security.password.spec.PasswordSpec in project wildfly-elytron by wildfly-security.
the class PasswordKeyMapper method map.
@Override
public Credential map(ResultSet resultSet, Supplier<Provider[]> providers) throws SQLException {
byte[] hash = null;
char[] clear = null;
byte[] salt = null;
int iterationCount;
String algorithmName = getDefaultAlgorithm();
final ResultSetMetaData metaData = resultSet.getMetaData();
if (algorithmColumn > 0) {
algorithmName = resultSet.getString(algorithmColumn);
if (algorithmName == null) {
algorithmName = getDefaultAlgorithm();
}
}
if (ClearPassword.ALGORITHM_CLEAR.equals(algorithmName)) {
final String s = getStringColumn(metaData, resultSet, hashColumn);
if (s != null) {
clear = s.toCharArray();
} else {
hash = getBinaryColumn(metaData, resultSet, hashColumn, hashEncoding);
}
} else {
if (saltColumn == -1 && iterationCountColumn == -1) {
// try modular crypt
final String s = getStringColumn(metaData, resultSet, hashColumn);
if (s != null) {
final char[] chars = s.toCharArray();
final String identified = ModularCrypt.identifyAlgorithm(chars);
if (identified != null) {
try {
Password modularCryptPassword = ModularCrypt.decode(chars);
if (log.isTraceEnabled()) {
log.tracef("Key Mapper: Password credential created using Modular Crypt algorithm [%s]", identified);
}
return new PasswordCredential(modularCryptPassword);
} catch (InvalidKeySpecException e) {
log.tracef(e, "Key Mapper: Unable to identify Modular Crypt algorithm [%s]", identified);
}
}
}
}
hash = getBinaryColumn(metaData, resultSet, hashColumn, hashEncoding);
}
if (saltColumn > 0) {
salt = getBinaryColumn(metaData, resultSet, saltColumn, saltEncoding);
}
if (iterationCountColumn > 0) {
iterationCount = resultSet.getInt(iterationCountColumn);
} else {
iterationCount = defaultIterationCount;
}
final PasswordFactory passwordFactory;
try {
passwordFactory = PasswordFactory.getInstance(algorithmName, providers);
} catch (NoSuchAlgorithmException e) {
throw log.couldNotObtainPasswordFactoryForAlgorithm(algorithmName, e);
}
PasswordSpec passwordSpec;
if (hash != null) {
if (salt != null) {
if (iterationCount > 0) {
passwordSpec = new IteratedSaltedHashPasswordSpec(hash, salt, iterationCount);
} else {
passwordSpec = new SaltedHashPasswordSpec(hash, salt);
}
} else {
if (iterationCount > 0) {
passwordSpec = new IteratedHashPasswordSpec(hash, iterationCount);
} else {
passwordSpec = new HashPasswordSpec(hash);
}
}
} else if (clear != null) {
passwordSpec = new ClearPasswordSpec(clear);
} else {
return null;
}
try {
Password password = passwordFactory.generatePassword(passwordSpec);
if (log.isTraceEnabled()) {
log.tracef("Key Mapper: Password credential created using algorithm column value [%s]", algorithmName);
}
return new PasswordCredential(password);
} catch (InvalidKeySpecException e) {
throw log.invalidPasswordKeySpecificationForAlgorithm(algorithmName, e);
}
}
use of org.wildfly.security.password.spec.PasswordSpec 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())));
}
};
}
use of org.wildfly.security.password.spec.PasswordSpec 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);
}
}
use of org.wildfly.security.password.spec.PasswordSpec in project wildfly-elytron by wildfly-security.
the class KeyStoreCredentialStore method retrieve.
public <C extends Credential> C retrieve(final String credentialAlias, final Class<C> credentialType, final String credentialAlgorithm, final AlgorithmParameterSpec parameterSpec, final CredentialStore.ProtectionParameter protectionParameter) throws CredentialStoreException {
final KeyStore.Entry entry;
final MidEntry midEntry;
final BottomEntry bottomEntry;
final String ksAlias;
try (Hold hold = lockForRead()) {
final TopEntry topEntry = cache.get(toLowercase(credentialAlias));
if (topEntry == null) {
log.trace("KeyStoreCredentialStore: alias not found in cache");
return null;
}
if (topEntry.getMap().containsKey(credentialType)) {
log.trace("KeyStoreCredentialStore: contains exact type");
midEntry = topEntry.getMap().get(credentialType);
} else {
// loose (slow) match
final Iterator<MidEntry> iterator = topEntry.getMap().values().iterator();
for (; ; ) {
if (!iterator.hasNext()) {
log.trace("KeyStoreCredentialStore: no assignable found");
return null;
}
MidEntry item = iterator.next();
if (credentialType.isAssignableFrom(item.getCredentialType())) {
log.trace("KeyStoreCredentialStore: assignable found");
midEntry = item;
break;
}
}
}
if (credentialAlgorithm != null) {
bottomEntry = midEntry.getMap().get(credentialAlgorithm);
} else {
// match any
final Iterator<BottomEntry> iterator = midEntry.getMap().values().iterator();
if (iterator.hasNext()) {
bottomEntry = iterator.next();
} else {
bottomEntry = midEntry.getNoAlgorithm();
}
}
if (bottomEntry == null) {
log.tracef("KeyStoreCredentialStore: no entry for algorithm %s", credentialAlgorithm);
return null;
}
if (parameterSpec != null) {
ksAlias = bottomEntry.getMap().get(new ParamKey(parameterSpec));
} else {
// match any
final Iterator<String> iterator = bottomEntry.getMap().values().iterator();
if (iterator.hasNext()) {
ksAlias = iterator.next();
} else {
ksAlias = bottomEntry.getNoParams();
}
}
if (ksAlias == null) {
log.tracef("KeyStoreCredentialStore: no entry for parameterSpec %s", parameterSpec);
return null;
}
entry = keyStore.getEntry(ksAlias, convertParameter(protectionParameter));
} catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
throw log.cannotAcquireCredentialFromStore(e);
}
if (entry == null) {
// odd, but we can handle it
log.trace("KeyStoreCredentialStore: null entry");
return null;
}
final Class<? extends Credential> matchedCredentialType = midEntry.getCredentialType();
if (matchedCredentialType == SecretKeyCredential.class) {
if (entry instanceof KeyStore.SecretKeyEntry) {
// simple
final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
return credentialType.cast(new SecretKeyCredential(secretKey));
} else {
throw log.invalidCredentialStoreEntryType(KeyStore.SecretKeyEntry.class, entry.getClass());
}
} else if (matchedCredentialType == PublicKeyCredential.class) {
if (entry instanceof KeyStore.SecretKeyEntry)
try {
// we store as a secret key because we can't store the public key properly...
final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
final byte[] encoded = secretKey.getEncoded();
final String matchedAlgorithm = bottomEntry.getAlgorithm();
// because PublicKeyCredential is an AlgorithmCredential
assert matchedAlgorithm != null;
final KeyFactory keyFactory = KeyFactory.getInstance(matchedAlgorithm);
final PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(encoded));
return credentialType.cast(new PublicKeyCredential(publicKey));
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw log.cannotAcquireCredentialFromStore(e);
}
else {
throw log.invalidCredentialStoreEntryType(KeyStore.SecretKeyEntry.class, entry.getClass());
}
} else if (matchedCredentialType == KeyPairCredential.class) {
if (entry instanceof KeyStore.SecretKeyEntry)
try {
final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
final byte[] encoded = secretKey.getEncoded();
final String matchedAlgorithm = bottomEntry.getAlgorithm();
// because KeyPairCredential is an AlgorithmCredential
assert matchedAlgorithm != null;
// extract public and private segments
final DERDecoder decoder = new DERDecoder(encoded);
decoder.startSequence();
final byte[] publicBytes = decoder.drainElement();
final byte[] privateBytes = decoder.drainElement();
decoder.endSequence();
final KeyFactory keyFactory = KeyFactory.getInstance(matchedAlgorithm);
final PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicBytes));
final PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateBytes));
final KeyPair keyPair = new KeyPair(publicKey, privateKey);
return credentialType.cast(new KeyPairCredential(keyPair));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | ASN1Exception e) {
throw log.cannotAcquireCredentialFromStore(e);
}
else {
throw log.invalidCredentialStoreEntryType(KeyStore.SecretKeyEntry.class, entry.getClass());
}
} else if (matchedCredentialType == X509CertificateChainPublicCredential.class) {
if (entry instanceof KeyStore.SecretKeyEntry)
try {
// OK so this is pretty ugly, but the TrustedCertificateEntry type only holds a single cert so it's no good
final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
final byte[] encoded = secretKey.getEncoded();
final String matchedAlgorithm = bottomEntry.getAlgorithm();
// because it is an AlgorithmCredential
assert matchedAlgorithm != null;
final DERDecoder decoder = new DERDecoder(encoded);
final CertificateFactory certificateFactory = CertificateFactory.getInstance(X_509);
final int count = decoder.decodeInteger().intValueExact();
final X509Certificate[] array = new X509Certificate[count];
decoder.startSequence();
int i = 0;
while (decoder.hasNextElement()) {
final byte[] certBytes = decoder.drainElement();
array[i++] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
}
decoder.endSequence();
return credentialType.cast(new X509CertificateChainPublicCredential(array));
} catch (ASN1Exception | CertificateException | ArrayIndexOutOfBoundsException e) {
throw log.cannotAcquireCredentialFromStore(e);
}
else {
throw log.invalidCredentialStoreEntryType(KeyStore.SecretKeyEntry.class, entry.getClass());
}
} else if (matchedCredentialType == X509CertificateChainPrivateCredential.class) {
if (entry instanceof KeyStore.PrivateKeyEntry) {
// an entry type that matches our credential type!
final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;
final PrivateKey privateKey = privateKeyEntry.getPrivateKey();
final Certificate[] certificateChain = privateKeyEntry.getCertificateChain();
final X509Certificate[] x509Certificates = X500.asX509CertificateArray(certificateChain);
return credentialType.cast(new X509CertificateChainPrivateCredential(privateKey, x509Certificates));
} else {
throw log.invalidCredentialStoreEntryType(KeyStore.PrivateKeyEntry.class, entry.getClass());
}
} else if (matchedCredentialType == BearerTokenCredential.class) {
if (entry instanceof KeyStore.SecretKeyEntry) {
final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
final byte[] encoded = secretKey.getEncoded();
return credentialType.cast(new BearerTokenCredential(new String(encoded, StandardCharsets.UTF_8)));
} else {
throw log.invalidCredentialStoreEntryType(KeyStore.SecretKeyEntry.class, entry.getClass());
}
} else if (matchedCredentialType == PasswordCredential.class) {
if (entry instanceof KeyStore.SecretKeyEntry)
try {
final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
final byte[] encoded = secretKey.getEncoded();
final String matchedAlgorithm = bottomEntry.getAlgorithm();
// because it is an AlgorithmCredential
assert matchedAlgorithm != null;
final DERDecoder decoder = new DERDecoder(encoded);
// we use algorithm-based encoding rather than a standard that encompasses all password types.
final PasswordSpec passwordSpec;
switch(matchedAlgorithm) {
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:
{
decoder.startSequence();
final byte[] hash = decoder.decodeOctetString();
final byte[] salt = decoder.decodeOctetString();
final int iterationCount = decoder.decodeInteger().intValue();
decoder.endSequence();
passwordSpec = new IteratedSaltedHashPasswordSpec(hash, salt, iterationCount);
break;
}
case ClearPassword.ALGORITHM_CLEAR:
{
passwordSpec = new ClearPasswordSpec(decoder.decodeOctetStringAsString().toCharArray());
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:
{
decoder.startSequence();
final String username = decoder.decodeOctetStringAsString();
final String realm = decoder.decodeOctetStringAsString();
final byte[] digest = decoder.decodeOctetString();
decoder.endSequence();
passwordSpec = new DigestPasswordSpec(username, realm, digest);
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:
{
decoder.startSequence();
final byte[] hash = decoder.decodeOctetString();
final String seed = decoder.decodeIA5String();
final int sequenceNumber = decoder.decodeInteger().intValue();
decoder.endSequence();
passwordSpec = new OneTimePasswordSpec(hash, seed, sequenceNumber);
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:
{
decoder.startSequence();
final byte[] hash = decoder.decodeOctetString();
final byte[] salt = decoder.decodeOctetString();
decoder.endSequence();
passwordSpec = new SaltedHashPasswordSpec(hash, salt);
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:
{
decoder.startSequence();
final byte[] hash = decoder.decodeOctetString();
decoder.endSequence();
passwordSpec = new HashPasswordSpec(hash);
break;
}
default:
{
if (MaskedPassword.isMaskedAlgorithm(matchedAlgorithm)) {
decoder.startSequence();
final char[] initialKeyMaterial = decoder.decodeOctetStringAsString().toCharArray();
final int iterationCount = decoder.decodeInteger().intValue();
final byte[] salt = decoder.decodeOctetString();
final byte[] maskedPasswordBytes = decoder.decodeOctetString();
decoder.endSequence();
passwordSpec = new MaskedPasswordSpec(initialKeyMaterial, iterationCount, salt, maskedPasswordBytes);
break;
} else {
throw log.unsupportedCredentialType(credentialType);
}
}
}
PasswordFactory passwordFactory = providers != null ? PasswordFactory.getInstance(matchedAlgorithm, () -> providers) : PasswordFactory.getInstance(matchedAlgorithm);
final Password password = passwordFactory.generatePassword(passwordSpec);
return credentialType.cast(new PasswordCredential(password));
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw log.cannotAcquireCredentialFromStore(e);
}
else {
throw log.invalidCredentialStoreEntryType(KeyStore.SecretKeyEntry.class, entry.getClass());
}
} else {
throw log.unableToReadCredentialTypeFromStore(matchedCredentialType);
}
}
Aggregations