Search in sources :

Example 1 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class Filter method readFrom.

/**
 * Reads and decodes a search filter from the provided ASN.1 stream reader.
 *
 * @param  reader  The ASN.1 stream reader from which to read the filter.
 *
 * @return  The decoded search filter.
 *
 * @throws  LDAPException  If an error occurs while reading or parsing the
 *                         search filter.
 */
@NotNull()
public static Filter readFrom(@NotNull final ASN1StreamReader reader) throws LDAPException {
    try {
        final Filter[] filterComps;
        final Filter notComp;
        final String attrName;
        final ASN1OctetString assertionValue;
        final ASN1OctetString subInitial;
        final ASN1OctetString[] subAny;
        final ASN1OctetString subFinal;
        final String matchingRuleID;
        final boolean dnAttributes;
        final byte filterType = (byte) reader.peek();
        switch(filterType) {
            case FILTER_TYPE_AND:
            case FILTER_TYPE_OR:
                final ArrayList<Filter> comps = new ArrayList<>(5);
                final ASN1StreamReaderSet elementSet = reader.beginSet();
                while (elementSet.hasMoreElements()) {
                    comps.add(readFrom(reader));
                }
                filterComps = new Filter[comps.size()];
                comps.toArray(filterComps);
                notComp = null;
                attrName = null;
                assertionValue = null;
                subInitial = null;
                subAny = NO_SUB_ANY;
                subFinal = null;
                matchingRuleID = null;
                dnAttributes = false;
                break;
            case FILTER_TYPE_NOT:
                final ASN1Element notFilterElement;
                try {
                    final ASN1Element e = reader.readElement();
                    notFilterElement = ASN1Element.decode(e.getValue());
                } catch (final ASN1Exception ae) {
                    Debug.debugException(ae);
                    throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_NOT_COMP.get(StaticUtils.getExceptionMessage(ae)), ae);
                }
                notComp = decode(notFilterElement);
                filterComps = NO_FILTERS;
                attrName = null;
                assertionValue = null;
                subInitial = null;
                subAny = NO_SUB_ANY;
                subFinal = null;
                matchingRuleID = null;
                dnAttributes = false;
                break;
            case FILTER_TYPE_EQUALITY:
            case FILTER_TYPE_GREATER_OR_EQUAL:
            case FILTER_TYPE_LESS_OR_EQUAL:
            case FILTER_TYPE_APPROXIMATE_MATCH:
                reader.beginSequence();
                attrName = reader.readString();
                assertionValue = new ASN1OctetString(reader.readBytes());
                filterComps = NO_FILTERS;
                notComp = null;
                subInitial = null;
                subAny = NO_SUB_ANY;
                subFinal = null;
                matchingRuleID = null;
                dnAttributes = false;
                break;
            case FILTER_TYPE_SUBSTRING:
                reader.beginSequence();
                attrName = reader.readString();
                ASN1OctetString tempSubInitial = null;
                ASN1OctetString tempSubFinal = null;
                final ArrayList<ASN1OctetString> subAnyList = new ArrayList<>(1);
                final ASN1StreamReaderSequence subSequence = reader.beginSequence();
                while (subSequence.hasMoreElements()) {
                    final byte type = (byte) reader.peek();
                    final ASN1OctetString s = new ASN1OctetString(type, reader.readBytes());
                    switch(type) {
                        case SUBSTRING_TYPE_SUBINITIAL:
                            tempSubInitial = s;
                            break;
                        case SUBSTRING_TYPE_SUBANY:
                            subAnyList.add(s);
                            break;
                        case SUBSTRING_TYPE_SUBFINAL:
                            tempSubFinal = s;
                            break;
                        default:
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_INVALID_SUBSTR_TYPE.get(StaticUtils.toHex(type)));
                    }
                }
                subInitial = tempSubInitial;
                subFinal = tempSubFinal;
                subAny = new ASN1OctetString[subAnyList.size()];
                subAnyList.toArray(subAny);
                filterComps = NO_FILTERS;
                notComp = null;
                assertionValue = null;
                matchingRuleID = null;
                dnAttributes = false;
                break;
            case FILTER_TYPE_PRESENCE:
                attrName = reader.readString();
                filterComps = NO_FILTERS;
                notComp = null;
                assertionValue = null;
                subInitial = null;
                subAny = NO_SUB_ANY;
                subFinal = null;
                matchingRuleID = null;
                dnAttributes = false;
                break;
            case FILTER_TYPE_EXTENSIBLE_MATCH:
                String tempAttrName = null;
                ASN1OctetString tempAssertionValue = null;
                String tempMatchingRuleID = null;
                boolean tempDNAttributes = false;
                final ASN1StreamReaderSequence emSequence = reader.beginSequence();
                while (emSequence.hasMoreElements()) {
                    final byte type = (byte) reader.peek();
                    switch(type) {
                        case EXTENSIBLE_TYPE_ATTRIBUTE_NAME:
                            tempAttrName = reader.readString();
                            break;
                        case EXTENSIBLE_TYPE_MATCHING_RULE_ID:
                            tempMatchingRuleID = reader.readString();
                            break;
                        case EXTENSIBLE_TYPE_MATCH_VALUE:
                            tempAssertionValue = new ASN1OctetString(type, reader.readBytes());
                            break;
                        case EXTENSIBLE_TYPE_DN_ATTRIBUTES:
                            tempDNAttributes = reader.readBoolean();
                            break;
                        default:
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_INVALID_TYPE.get(StaticUtils.toHex(type)));
                    }
                }
                if ((tempAttrName == null) && (tempMatchingRuleID == null)) {
                    throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_NO_ATTR_OR_MRID.get());
                }
                if (tempAssertionValue == null) {
                    throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_NO_VALUE.get());
                }
                attrName = tempAttrName;
                assertionValue = tempAssertionValue;
                matchingRuleID = tempMatchingRuleID;
                dnAttributes = tempDNAttributes;
                filterComps = NO_FILTERS;
                notComp = null;
                subInitial = null;
                subAny = NO_SUB_ANY;
                subFinal = null;
                break;
            default:
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_ELEMENT_INVALID_TYPE.get(StaticUtils.toHex(filterType)));
        }
        return new Filter(null, filterType, filterComps, notComp, attrName, assertionValue, subInitial, subAny, subFinal, matchingRuleID, dnAttributes);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) ASN1Exception(com.unboundid.asn1.ASN1Exception) ArrayList(java.util.ArrayList) ASN1StreamReaderSet(com.unboundid.asn1.ASN1StreamReaderSet) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Exception(com.unboundid.asn1.ASN1Exception) JSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.JSONObjectFilter) ASN1Element(com.unboundid.asn1.ASN1Element) NotNull(com.unboundid.util.NotNull)

Example 2 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class Control method decode.

/**
 * Decodes the provided ASN.1 sequence as an LDAP control.
 *
 * @param  controlSequence  The ASN.1 sequence to be decoded.
 *
 * @return  The decoded control.
 *
 * @throws  LDAPException  If a problem occurs while attempting to decode the
 *                         provided ASN.1 sequence as an LDAP control.
 */
@NotNull()
public static Control decode(@NotNull final ASN1Sequence controlSequence) throws LDAPException {
    final ASN1Element[] elements = controlSequence.elements();
    if ((elements.length < 1) || (elements.length > 3)) {
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_CONTROL_DECODE_INVALID_ELEMENT_COUNT.get(elements.length));
    }
    final String oid = ASN1OctetString.decodeAsOctetString(elements[0]).stringValue();
    boolean isCritical = false;
    ASN1OctetString value = null;
    if (elements.length == 2) {
        switch(elements[1].getType()) {
            case ASN1Constants.UNIVERSAL_BOOLEAN_TYPE:
                try {
                    isCritical = ASN1Boolean.decodeAsBoolean(elements[1]).booleanValue();
                } catch (final ASN1Exception ae) {
                    Debug.debugException(ae);
                    throw new LDAPException(ResultCode.DECODING_ERROR, ERR_CONTROL_DECODE_CRITICALITY.get(StaticUtils.getExceptionMessage(ae)), ae);
                }
                break;
            case ASN1Constants.UNIVERSAL_OCTET_STRING_TYPE:
                value = ASN1OctetString.decodeAsOctetString(elements[1]);
                break;
            default:
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_CONTROL_INVALID_TYPE.get(StaticUtils.toHex(elements[1].getType())));
        }
    } else if (elements.length == 3) {
        try {
            isCritical = ASN1Boolean.decodeAsBoolean(elements[1]).booleanValue();
        } catch (final ASN1Exception ae) {
            Debug.debugException(ae);
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_CONTROL_DECODE_CRITICALITY.get(StaticUtils.getExceptionMessage(ae)), ae);
        }
        value = ASN1OctetString.decodeAsOctetString(elements[2]);
    }
    return decode(oid, isCritical, value);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Exception(com.unboundid.asn1.ASN1Exception) ASN1Element(com.unboundid.asn1.ASN1Element) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) NotNull(com.unboundid.util.NotNull)

Example 3 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class LDAPResult method readLDAPResultFrom.

/**
 * Creates a new LDAP result object with the provided message ID and with the
 * protocol op and controls read from the given ASN.1 stream reader.
 *
 * @param  messageID        The LDAP message ID for the LDAP message that is
 *                          associated with this LDAP result.
 * @param  messageSequence  The ASN.1 stream reader sequence used in the
 *                          course of reading the LDAP message elements.
 * @param  reader           The ASN.1 stream reader from which to read the
 *                          protocol op and controls.
 *
 * @return  The decoded LDAP result.
 *
 * @throws  LDAPException  If a problem occurs while reading or decoding data
 *                         from the ASN.1 stream reader.
 */
@NotNull()
static LDAPResult readLDAPResultFrom(final int messageID, @NotNull final ASN1StreamReaderSequence messageSequence, @NotNull final ASN1StreamReader reader) throws LDAPException {
    try {
        final ASN1StreamReaderSequence protocolOpSequence = reader.beginSequence();
        final byte protocolOpType = protocolOpSequence.getType();
        final ResultCode resultCode = ResultCode.valueOf(reader.readEnumerated());
        String matchedDN = reader.readString();
        if (matchedDN.isEmpty()) {
            matchedDN = null;
        }
        String diagnosticMessage = reader.readString();
        if (diagnosticMessage.isEmpty()) {
            diagnosticMessage = null;
        }
        String[] referralURLs = StaticUtils.NO_STRINGS;
        if (protocolOpSequence.hasMoreElements()) {
            final ArrayList<String> refList = new ArrayList<>(1);
            final ASN1StreamReaderSequence refSequence = reader.beginSequence();
            while (refSequence.hasMoreElements()) {
                refList.add(reader.readString());
            }
            referralURLs = new String[refList.size()];
            refList.toArray(referralURLs);
        }
        Control[] responseControls = NO_CONTROLS;
        if (messageSequence.hasMoreElements()) {
            final ArrayList<Control> controlList = new ArrayList<>(1);
            final ASN1StreamReaderSequence controlSequence = reader.beginSequence();
            while (controlSequence.hasMoreElements()) {
                controlList.add(Control.readFrom(reader));
            }
            responseControls = new Control[controlList.size()];
            controlList.toArray(responseControls);
        }
        return new LDAPResult(protocolOpType, messageID, resultCode, diagnosticMessage, matchedDN, referralURLs, responseControls);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final ASN1Exception ae) {
        Debug.debugException(ae);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_RESULT_CANNOT_DECODE.get(ae.getMessage()), ae);
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_RESULT_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) ASN1Exception(com.unboundid.asn1.ASN1Exception) ArrayList(java.util.ArrayList) ASN1Exception(com.unboundid.asn1.ASN1Exception) NotNull(com.unboundid.util.NotNull)

Example 4 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class Attribute method decode.

/**
 * Decodes the provided ASN.1 sequence as an LDAP attribute.
 *
 * @param  encodedAttribute  The ASN.1 sequence to be decoded as an LDAP
 *                           attribute.  It must not be {@code null}.
 *
 * @return  The decoded LDAP attribute.
 *
 * @throws  LDAPException  If a problem occurs while attempting to decode the
 *                         provided ASN.1 sequence as an LDAP attribute.
 */
@NotNull()
public static Attribute decode(@NotNull final ASN1Sequence encodedAttribute) throws LDAPException {
    Validator.ensureNotNull(encodedAttribute);
    final ASN1Element[] elements = encodedAttribute.elements();
    if (elements.length != 2) {
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_ATTR_DECODE_INVALID_COUNT.get(elements.length));
    }
    final String name = ASN1OctetString.decodeAsOctetString(elements[0]).stringValue();
    final ASN1Set valueSet;
    try {
        valueSet = ASN1Set.decodeAsSet(elements[1]);
    } catch (final ASN1Exception ae) {
        Debug.debugException(ae);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_ATTR_DECODE_VALUE_SET.get(StaticUtils.getExceptionMessage(ae)), ae);
    }
    final ASN1OctetString[] values = new ASN1OctetString[valueSet.elements().length];
    for (int i = 0; i < values.length; i++) {
        values[i] = ASN1OctetString.decodeAsOctetString(valueSet.elements()[i]);
    }
    return new Attribute(name, CaseIgnoreStringMatchingRule.getInstance(), values);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Set(com.unboundid.asn1.ASN1Set) ASN1Exception(com.unboundid.asn1.ASN1Exception) ASN1Element(com.unboundid.asn1.ASN1Element) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) NotNull(com.unboundid.util.NotNull)

Example 5 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception 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);
    }
}
Also used : MaskedPasswordSpec(org.wildfly.security.password.spec.MaskedPasswordSpec) MaskedPasswordSpec(org.wildfly.security.password.spec.MaskedPasswordSpec) PasswordSpec(org.wildfly.security.password.spec.PasswordSpec) HashPasswordSpec(org.wildfly.security.password.spec.HashPasswordSpec) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec) OneTimePasswordSpec(org.wildfly.security.password.spec.OneTimePasswordSpec) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) PrivateKey(java.security.PrivateKey) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) PasswordCredential(org.wildfly.security.credential.PasswordCredential) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeyCredential(org.wildfly.security.credential.SecretKeyCredential) OneTimePasswordSpec(org.wildfly.security.password.spec.OneTimePasswordSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) X509CertificateChainPublicCredential(org.wildfly.security.credential.X509CertificateChainPublicCredential) KeyPair(java.security.KeyPair) PublicKey(java.security.PublicKey) ASN1Exception(org.wildfly.security.asn1.ASN1Exception) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) X509Certificate(java.security.cert.X509Certificate) DERDecoder(org.wildfly.security.asn1.DERDecoder) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) SecretKey(javax.crypto.SecretKey) PasswordFactory(org.wildfly.security.password.PasswordFactory) KeyPairCredential(org.wildfly.security.credential.KeyPairCredential) ByteArrayInputStream(java.io.ByteArrayInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) DigestPasswordSpec(org.wildfly.security.password.spec.DigestPasswordSpec) BearerTokenCredential(org.wildfly.security.credential.BearerTokenCredential) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) CertificateFactory(java.security.cert.CertificateFactory) UnrecoverableEntryException(java.security.UnrecoverableEntryException) HashPasswordSpec(org.wildfly.security.password.spec.HashPasswordSpec) SaltedHashPasswordSpec(org.wildfly.security.password.spec.SaltedHashPasswordSpec) IteratedSaltedHashPasswordSpec(org.wildfly.security.password.spec.IteratedSaltedHashPasswordSpec) 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) X509CertificateChainPrivateCredential(org.wildfly.security.credential.X509CertificateChainPrivateCredential) KeyStoreException(java.security.KeyStoreException) PublicKeyCredential(org.wildfly.security.credential.PublicKeyCredential) KeyStore(java.security.KeyStore) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec)

Aggregations

IOException (java.io.IOException)18 Asn1Exception (es.gob.jmulticard.asn1.Asn1Exception)16 ASN1Exception (com.unboundid.asn1.ASN1Exception)12 TlvException (es.gob.jmulticard.asn1.TlvException)12 Asn1Exception (sun.security.krb5.Asn1Exception)11 ASN1Element (com.unboundid.asn1.ASN1Element)7 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)7 NotNull (com.unboundid.util.NotNull)7 Iso7816FourCardException (es.gob.jmulticard.card.iso7816four.Iso7816FourCardException)7 CertificateException (java.security.cert.CertificateException)7 X509Certificate (java.security.cert.X509Certificate)7 Asn1Exception (org.kse.utilities.asn1.Asn1Exception)7 ASN1Exception (org.wildfly.security.asn1.ASN1Exception)6 ApduConnectionException (es.gob.jmulticard.apdu.connection.ApduConnectionException)5 Cdf (es.gob.jmulticard.asn1.der.pkcs15.Cdf)5 CryptoCardException (es.gob.jmulticard.card.CryptoCardException)5 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)4 DecoderObject (es.gob.jmulticard.asn1.DecoderObject)4 InvalidCardException (es.gob.jmulticard.card.InvalidCardException)4 DerValue (sun.security.util.DerValue)4