Search in sources :

Example 41 with ASN1OctetString

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

the class OperationsFacade method search.

public SearchResult search(String dn, Filter filter, SearchScope scope, BatchOperation<?> batchOperation, int startIndex, int searchLimit, int sizeLimit, Control[] controls, String... attributes) throws LDAPSearchException {
    SearchRequest searchRequest;
    if (log.isTraceEnabled()) {
        // Find whole tree search
        if (StringHelper.equalsIgnoreCase(dn, "o=gluu")) {
            log.trace("Search in whole LDAP tree", new Exception());
        }
    }
    if (attributes == null) {
        searchRequest = new SearchRequest(dn, scope.getLdapSearchScope(), filter);
    } else {
        searchRequest = new SearchRequest(dn, scope.getLdapSearchScope(), filter, attributes);
    }
    boolean useSizeLimit = sizeLimit > 0;
    if (useSizeLimit) {
        // Use paged result to limit search
        searchLimit = sizeLimit;
    }
    SearchResult searchResult = null;
    List<SearchResult> searchResultList = new ArrayList<SearchResult>();
    List<SearchResultEntry> searchResultEntries = new ArrayList<SearchResultEntry>();
    List<SearchResultReference> searchResultReferences = new ArrayList<SearchResultReference>();
    if ((searchLimit > 0) || (startIndex > 0)) {
        if (searchLimit == 0) {
            // Default page size
            searchLimit = 100;
        }
        ASN1OctetString cookie = null;
        if (startIndex > 0) {
            try {
                cookie = scrollSimplePagedResultsControl(dn, filter, scope, controls, startIndex);
            } catch (InvalidSimplePageControlException ex) {
                throw new LDAPSearchException(ResultCode.OPERATIONS_ERROR, "Failed to scroll to specified startIndex", ex);
            }
        }
        if (batchOperation != null) {
            cookie = batchOperation.getCookie();
        }
        do {
            searchRequest.setControls(new Control[] { new SimplePagedResultsControl(searchLimit, cookie) });
            setControls(searchRequest, controls);
            if (batchOperation != null) {
                searchResult = batchOperation.getLdapConnection().search(searchRequest);
            } else {
                searchResult = getConnectionPool().search(searchRequest);
            }
            searchResultList.add(searchResult);
            searchResultEntries.addAll(searchResult.getSearchEntries());
            searchResultReferences.addAll(searchResult.getSearchReferences());
            cookie = null;
            try {
                SimplePagedResultsControl c = SimplePagedResultsControl.get(searchResult);
                if (c != null) {
                    cookie = c.getCookie();
                    if (batchOperation != null) {
                        batchOperation.setCookie(cookie);
                        batchOperation.setMoreResultsToReturn(c.moreResultsToReturn());
                    }
                }
            } catch (LDAPException ex) {
                log.error("Error while accessing cookies" + ex.getMessage());
            }
            if (useSizeLimit) {
                break;
            }
        } while ((cookie != null) && (cookie.getValueLength() > 0));
        SearchResult searchResultTemp = searchResultList.get(0);
        searchResult = new SearchResult(searchResultTemp.getMessageID(), searchResultTemp.getResultCode(), searchResultTemp.getDiagnosticMessage(), searchResultTemp.getMatchedDN(), searchResultTemp.getReferralURLs(), searchResultEntries, searchResultReferences, searchResultEntries.size(), searchResultReferences.size(), searchResultTemp.getResponseControls());
    } else {
        setControls(searchRequest, controls);
        searchResult = getConnectionPool().search(searchRequest);
    }
    return searchResult;
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) InvalidSimplePageControlException(org.gluu.site.ldap.exception.InvalidSimplePageControlException) MappingException(org.gluu.site.ldap.persistence.exception.MappingException) DuplicateEntryException(org.gluu.site.ldap.exception.DuplicateEntryException) ConnectionException(org.gluu.site.ldap.exception.ConnectionException) InvalidArgumentException(org.gluu.site.ldap.persistence.exception.InvalidArgumentException) InvalidSimplePageControlException(org.gluu.site.ldap.exception.InvalidSimplePageControlException)

Example 42 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project nhin-d by DirectProject.

the class SigTest method testCreateVerifySig.

public void testCreateVerifySig() throws Exception {
    X509CertificateEx internalCert = TestUtils.getInternalCert("user1");
    X509Certificate caCert = TestUtils.getExternalCert("cacert");
    String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
    MimeMessage entity = EntitySerializer.Default.deserialize(testMessage);
    Message message = new Message(entity);
    MimeEntity entityToSig = message.extractEntityForSignature(true);
    // Serialize message out as ASCII encoded...
    byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entityToSig);
    MimeBodyPart partToSign = null;
    try {
        partToSign = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
    } catch (Exception e) {
    }
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);
    caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
    caps.addCapability(PKCSObjectIdentifiers.x509Certificate);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    List certList = new ArrayList();
    gen.addSigner(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
    //SMIMESignedGenerator.DIGEST_SHA1, null, null);
    certList.add(internalCert);
    MimeMultipart retVal = null;
    CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName());
    gen.addCertificatesAndCRLs(certsAndcrls);
    _certStores.add(certsAndcrls);
    _signers.add(new Signer(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null));
    retVal = generate(partToSign, CryptoExtensions.getJCEProviderName());
    for (int i = 0; i < 10; ++i) {
        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        retVal.writeTo(oStream);
        oStream.flush();
        byte[] serialzedBytes = oStream.toByteArray();
        //System.out.println(new String(serialzedBytes, "ASCII") + "\r\n\r\n\r\n\r\n\r\n");
        ByteArrayDataSource dataSource = new ByteArrayDataSource(serialzedBytes, retVal.getContentType());
        MimeMultipart verifyMM = new MimeMultipart(dataSource);
        CMSSignedData signed = null;
        //CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(verifyMM.getBodyPart(0)), verifyMM.getBodyPart(1).getInputStream());			
        CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(partToSign), verifyMM.getBodyPart(1).getInputStream());
        int verified = 0;
        CertStore certs = signeddata.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signeddata.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());
            Attribute dig = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
            DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
            byte[] signedHash = ((ASN1OctetString) hashObj).getOctets();
            System.out.print("value of signedHash: \r\n\tvalue: ");
            for (byte bt : signedHash) {
                System.out.print(bt + " ");
            }
            System.out.println();
            Iterator certIt = certCollection.iterator();
            try {
                assertTrue(signer.verify(internalCert, CryptoExtensions.getJCEProviderName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            byte[] bytes = signer.getContentDigest();
            /*
	    		  X509Certificate cert = (X509Certificate)certIt.next();
	    		  
    		      if (signer.verify(cert.getPublicKey()))
    		      {
    		          verified++;
    		      }
	    		  */
            verified++;
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CMSProcessableBodyPartInbound(org.bouncycastle.mail.smime.CMSProcessableBodyPartInbound) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Attribute(org.bouncycastle.asn1.cms.Attribute) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) SMIMESignedGenerator(org.bouncycastle.mail.smime.SMIMESignedGenerator) SignerInformation(org.bouncycastle.cms.SignerInformation) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) DERObject(org.bouncycastle.asn1.DERObject) MimeMessage(javax.mail.internet.MimeMessage) SMIMECapabilityVector(org.bouncycastle.asn1.smime.SMIMECapabilityVector) MimeMultipart(javax.mail.internet.MimeMultipart) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) Iterator(java.util.Iterator) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CMSException(org.bouncycastle.cms.CMSException) IOException(java.io.IOException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) NoSuchProviderException(java.security.NoSuchProviderException) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) Collection(java.util.Collection) MimeBodyPart(javax.mail.internet.MimeBodyPart) CertStore(java.security.cert.CertStore)

Example 43 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project nhin-d by DirectProject.

the class DefaultMessageSignatureImpl method logDigests.

private void logDigests(SignerInformation sigInfo) {
    // will fail
    if (this.m_logDigest && sigInfo != null) {
        try {
            //get the digests
            final Attribute digAttr = sigInfo.getSignedAttributes().get(CMSAttributes.messageDigest);
            final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
            final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
            final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
            LOGGER.info("Signed Message Digest: " + signedDigestHex);
            // should have the computed digest now
            final byte[] digest = sigInfo.getContentDigest();
            final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
            LOGGER.info("Computed Message Digest: " + digestHex);
        } catch (Throwable t) {
        /* no-op.... logging digests is a quiet operation */
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERObject(org.bouncycastle.asn1.DERObject) Attribute(org.bouncycastle.asn1.cms.Attribute) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString)

Example 44 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project nhin-d by DirectProject.

the class CRLRevocationManager method getObject.

private static DERObject getObject(String oid, byte[] ext) throws AnnotatedException {
    ASN1InputStream aIn = null;
    try {
        aIn = new ASN1InputStream(ext);
        ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
        IOUtils.closeQuietly(aIn);
        aIn = new ASN1InputStream(octs.getOctets());
        return aIn.readObject();
    } catch (Exception e) {
        throw new NHINDException("exception processing extension " + oid, e);
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) NHINDException(org.nhindirect.stagent.NHINDException) AnnotatedException(org.bouncycastle.jce.provider.AnnotatedException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NHINDException(org.nhindirect.stagent.NHINDException) CRLException(java.security.cert.CRLException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 45 with ASN1OctetString

use of org.apache.harmony.security.asn1.ASN1OctetString in project zm-mailbox by Zimbra.

the class UBIDLdapContext method searchPaged.

@Override
public void searchPaged(SearchLdapOptions searchOptions) throws ServiceException {
    int maxResults = searchOptions.getMaxResults();
    String base = searchOptions.getSearchBase();
    ZLdapFilter filter = searchOptions.getFilter();
    Set<String> binaryAttrs = searchOptions.getBinaryAttrs();
    SearchScope searchScope = ((UBIDSearchScope) searchOptions.getSearchScope()).getNative();
    SearchLdapOptions.SearchLdapVisitor visitor = searchOptions.getVisitor();
    SearchGalResult searchGalResult = searchOptions.getSearchGalResult();
    int pageSize = searchOptions.getResultPageSize();
    int offset = 0;
    boolean pagination = false;
    int limit = 0;
    String prevLastReturnedItemCreateDate = null;
    if (searchGalResult != null) {
        offset = searchGalResult.getLdapMatchCount();
        prevLastReturnedItemCreateDate = searchGalResult.getLdapTimeStamp();
        pagination = searchGalResult.getHadMore();
        limit = searchGalResult.getLimit();
    }
    if (GalOp.sync == searchOptions.getGalOp() && !pagination) {
        limit = 0;
    }
    if (limit == 0) {
        limit = Integer.MAX_VALUE;
    }
    int pageCount = 0;
    int pageOffset = 0;
    int currentPage = 0;
    int index = 0;
    if (offset > 0) {
        pageCount = offset / pageSize;
        pageOffset = offset % pageSize;
    }
    String newToken = "";
    // TODO: this is the legacy behavior, we can make it a param
    boolean wantPartialResult = true;
    try {
        SearchRequest searchRequest = new SearchRequest(base, searchScope, derefAliasPolicy, maxResults, 0, false, ((UBIDLdapFilter) filter).getNative());
        searchRequest.setAttributes(searchOptions.getReturnAttrs());
        //Set the page size and initialize the cookie that we pass back in subsequent pages
        ASN1OctetString cookie = null;
        int count = offset;
        do {
            List<Control> controls = Lists.newArrayListWithCapacity(2);
            if (searchOptions.isUseControl()) {
                controls.add(new SimplePagedResultsControl(pageSize, cookie));
            }
            if (searchOptions.isManageDSAit()) {
                controls.add(new ManageDsaITRequestControl(false));
            }
            searchRequest.setControls(controls.toArray(new Control[0]));
            SearchResult result = null;
            try {
                result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
            } catch (LDAPException e) {
                if (ResultCode.SIZE_LIMIT_EXCEEDED == e.getResultCode() && wantPartialResult) {
                    // if callsite wants partial result, return them
                    LDAPResult ldapResult = e.toLDAPResult();
                    if (ldapResult instanceof SearchResult) {
                        SearchResult searchResult = (SearchResult) ldapResult;
                        for (SearchResultEntry entry : searchResult.getSearchEntries()) {
                            String dn = entry.getDN();
                            UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
                            if (visitor.wantAttrMapOnVisit()) {
                                visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
                            } else {
                                visitor.visit(dn, ubidAttrs);
                            }
                            newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
                        }
                        if (searchGalResult != null) {
                            searchGalResult.setLdapTimeStamp(newToken);
                            searchGalResult.setLdapMatchCount(1);
                            searchGalResult.setHadMore(true);
                        }
                    }
                }
                // always re-throw
                throw e;
            }
            List<SearchResultEntry> entries = result.getSearchEntries();
            boolean hasMore = false;
            int resultSize = entries.size();
            if (resultSize > (limit + pageOffset)) {
                hasMore = true;
            }
            String leCreateDate = null;
            if (currentPage >= pageCount) {
                leCreateDate = getLastEntryCreationDate(limit + pageOffset, entries);
                if (prevLastReturnedItemCreateDate != null && !prevLastReturnedItemCreateDate.equals(leCreateDate)) {
                    count = 0;
                }
                for (index = pageOffset; index < entries.size() && limit > 0; index++) {
                    SearchResultEntry entry = entries.get(index);
                    String dn = entry.getDN();
                    UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
                    if (visitor.wantAttrMapOnVisit()) {
                        visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
                    } else {
                        visitor.visit(dn, ubidAttrs);
                    }
                    limit--;
                    newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
                    if (newToken != null && newToken.equals(leCreateDate)) {
                        count++;
                    }
                }
                prevLastReturnedItemCreateDate = leCreateDate;
                pageOffset = 0;
            }
            cookie = null;
            for (Control c : result.getResponseControls()) {
                if (c instanceof SimplePagedResultsControl) {
                    cookie = ((SimplePagedResultsControl) c).getCookie();
                }
            }
            if (searchGalResult != null && (GalOp.sync == searchOptions.getGalOp())) {
                if (limit == 0 && (((cookie != null) && (cookie.getValueLength() > 0)) || hasMore)) {
                    searchGalResult.setHadMore(true);
                    searchGalResult.setLdapTimeStamp(newToken);
                    searchGalResult.setLdapMatchCount(count);
                } else if (((cookie != null) && (cookie.getValueLength() == 0))) {
                    searchGalResult.setHadMore(false);
                    searchGalResult.setLdapMatchCount(0);
                }
            }
            currentPage++;
        } while ((cookie != null) && (cookie.getValueLength() > 0) && limit > 0);
    } catch (SearchLdapOptions.StopIteratingException e) {
    // break out of the loop and close the ne
    } catch (LDAPException e) {
        throw mapToLdapException("unable to search ldap", e);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPResult(com.unboundid.ldap.sdk.LDAPResult) SearchResult(com.unboundid.ldap.sdk.SearchResult) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SearchGalResult(com.zimbra.cs.account.Provisioning.SearchGalResult) SearchLdapOptions(com.zimbra.cs.ldap.SearchLdapOptions) ZLdapFilter(com.zimbra.cs.ldap.ZLdapFilter) Control(com.unboundid.ldap.sdk.Control) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchScope(com.unboundid.ldap.sdk.SearchScope) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

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