Search in sources :

Example 21 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project oxCore by GluuFederation.

the class OperationsFacade method scrollSimplePagedResultsControl.

private ASN1OctetString scrollSimplePagedResultsControl(String dn, Filter filter, SearchScope scope, Control[] controls, int startIndex) throws LDAPSearchException, InvalidSimplePageControlException {
    SearchRequest searchRequest = new SearchRequest(dn, scope.getLdapSearchScope(), filter, "dn");
    int currentStartIndex = startIndex;
    ASN1OctetString cookie = null;
    do {
        int pageSize = Math.min(currentStartIndex, 100);
        searchRequest.setControls(new Control[] { new SimplePagedResultsControl(pageSize, cookie, true) });
        setControls(searchRequest, controls);
        SearchResult searchResult = getConnectionPool().search(searchRequest);
        currentStartIndex -= searchResult.getEntryCount();
        try {
            SimplePagedResultsControl c = SimplePagedResultsControl.get(searchResult);
            if (c != null) {
                cookie = c.getCookie();
            }
        } catch (LDAPException ex) {
            log.error("Error while accessing cookie" + ex.getMessage());
            throw new InvalidSimplePageControlException("Error while accessing cookie");
        }
    } while ((cookie != null) && (cookie.getValueLength() > 0) && (currentStartIndex > 0));
    return cookie;
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) InvalidSimplePageControlException(org.gluu.site.ldap.exception.InvalidSimplePageControlException)

Example 22 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project oxAuth by GluuFederation.

the class RSASigner method validateSignature.

@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }
    if (rsaPublicKey == null) {
        throw new SignatureException("The RSA public key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }
    String algorithm = null;
    switch(getSignatureAlgorithm()) {
        case RS256:
            algorithm = "SHA-256";
            break;
        case RS384:
            algorithm = "SHA-384";
            break;
        case RS512:
            algorithm = "SHA-512";
            break;
        default:
            throw new SignatureException("Unsupported signature algorithm");
    }
    ASN1InputStream aIn = null;
    try {
        byte[] sigBytes = Base64Util.base64urldecode(signature);
        byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);
        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] decSig = cipher.doFinal(sigBytes);
        aIn = new ASN1InputStream(decSig);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        MessageDigest hash = MessageDigest.getInstance(algorithm, "BC");
        hash.update(sigInBytes);
        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } catch (IOException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (NoSuchPaddingException e) {
        throw new SignatureException(e);
    } catch (BadPaddingException e) {
        throw new SignatureException(e);
    } catch (NoSuchProviderException e) {
        throw new SignatureException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SignatureException(e);
    } catch (Exception e) {
        throw new SignatureException(e);
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) RSAPublicKey(org.xdi.oxauth.model.crypto.signature.RSAPublicKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) Cipher(javax.crypto.Cipher) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 23 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project oxCore by GluuFederation.

the class LdapEntryManager method countEntries.

public <T> int countEntries(String baseDN, Class<T> entryClass, Filter filter) {
    if (StringHelper.isEmptyString(baseDN)) {
        throw new MappingException("Base DN to find entries is null");
    }
    // Check entry class
    checkEntryClass(entryClass, false);
    String[] objectClasses = getTypeObjectClasses(entryClass);
    // Don't load
    String[] ldapReturnAttributes = new String[] { "" };
    // attributes
    // Find entries
    Filter searchFilter;
    if (objectClasses.length > 0) {
        searchFilter = addObjectClassFilter(filter, objectClasses);
    } else {
        searchFilter = filter;
    }
    int countEntries = 0;
    ASN1OctetString cookie = null;
    SearchResult searchResult = null;
    do {
        Control[] controls = new Control[] { new SimplePagedResultsControl(100, cookie) };
        try {
            searchResult = this.ldapOperationService.search(baseDN, searchFilter, 0, 0, controls, ldapReturnAttributes);
            if (!ResultCode.SUCCESS.equals(searchResult.getResultCode())) {
                throw new EntryPersistenceException(String.format("Failed to calculate count entries with baseDN: %s, filter: %s", baseDN, searchFilter));
            }
        } catch (Exception ex) {
            throw new EntryPersistenceException(String.format("Failed to calculate count entries with baseDN: %s, filter: %s", baseDN, searchFilter), ex);
        }
        countEntries += searchResult.getEntryCount();
        // list
        if ((countEntries == 0) || ((countEntries % 100) != 0)) {
            break;
        }
        cookie = null;
        for (Control control : searchResult.getResponseControls()) {
            if (control instanceof SimplePagedResultsControl) {
                cookie = ((SimplePagedResultsControl) control).getCookie();
                break;
            }
        }
    } while (cookie != null);
    return countEntries;
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) EmptyEntryPersistenceException(org.gluu.site.ldap.persistence.exception.EmptyEntryPersistenceException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) EmptyEntryPersistenceException(org.gluu.site.ldap.persistence.exception.EmptyEntryPersistenceException) MappingException(org.gluu.site.ldap.persistence.exception.MappingException) AuthenticationException(org.gluu.site.ldap.persistence.exception.AuthenticationException) InvalidArgumentException(org.gluu.site.ldap.persistence.exception.InvalidArgumentException) ParseException(java.text.ParseException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) ConnectionException(org.gluu.site.ldap.exception.ConnectionException) MappingException(org.gluu.site.ldap.persistence.exception.MappingException)

Example 24 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project ddf by codice.

the class LoginFilter method validateHolderOfKeyConfirmation.

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;
        }
    }
    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject().getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();
                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with certificate.");
                        }
                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject DN.");
                        }
                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException("Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(assertionOs.getOctets());
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CertificateException(java.security.cert.CertificateException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) InvalidKeyException(java.security.InvalidKeyException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchProviderException(java.security.NoSuchProviderException)

Example 25 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project cas by apereo.

the class X509SubjectAlternativeNameUPNPrincipalResolver method getUPNStringFromSequence.

/**
     * Get UPN String.
     *
     * @param seq ASN1Sequence abstraction representing subject alternative name.
     *            First element is the object identifier, second is the object itself.
     * @return UPN string or null
     */
private static String getUPNStringFromSequence(final ASN1Sequence seq) {
    if (seq != null) {
        // First in sequence is the object identifier, that we must check
        final ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
        if (id != null && UPN_OBJECTID.equals(id.getId())) {
            final ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);
            ASN1Primitive prim = obj.getObject();
            // Due to bug in java cert.getSubjectAltName, it can be tagged an extra time
            if (prim instanceof ASN1TaggedObject) {
                prim = ASN1TaggedObject.getInstance(prim).getObject();
            }
            if (prim instanceof ASN1OctetString) {
                return new String(((ASN1OctetString) prim).getOctets(), StandardCharsets.UTF_8);
            } else if (prim instanceof ASN1String) {
                return ((ASN1String) prim).getString();
            } else {
                return null;
            }
        }
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1String(org.bouncycastle.asn1.ASN1String) ASN1String(org.bouncycastle.asn1.ASN1String) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)40 IOException (java.io.IOException)22 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)17 X509Certificate (java.security.cert.X509Certificate)11 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)11 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)11 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 DEROctetString (org.bouncycastle.asn1.DEROctetString)10 CertificateException (java.security.cert.CertificateException)9 Enumeration (java.util.Enumeration)9 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)8 ByteArrayInputStream (java.io.ByteArrayInputStream)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 CertificateEncodingException (java.security.cert.CertificateEncodingException)8 DERObject (org.bouncycastle.asn1.DERObject)8 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)8 X962Parameters (org.bouncycastle.asn1.x9.X962Parameters)8 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)8 X9ECPoint (org.bouncycastle.asn1.x9.X9ECPoint)8 DERBitString (org.bouncycastle.asn1.DERBitString)7