Monday, 29 July 2013

Reading Cookies & Encrypting data

Below is a little bit of code to loop through cookie data.
It also adds a cookie whose data has been encrypted by CQ.  And, decrypts it too.


<%@ include file="/libs/foundation/global.jsp" %><%
%><%@ page contentType="text/html; charset=utf-8"%><%
%><%@ page import="org.apache.commons.lang.StringUtils"%><%
%><%@ page import="javax.servlet.http.Cookie"%><%
%><%@ page import="com.adobe.granite.crypto.CryptoSupport"%><%
%>
<h1>Cookie example</h1>
<%
    CryptoSupport cryptoSupport = sling.getService(com.adobe.granite.crypto.CryptoSupport.class);

    // Create an encrypted string of the data.
    String str1 = cryptoSupport.protect("Helloooo");
    // Base 64 encode the encrypted string so that only permitted Cookie data is stored.
    Cookie ck1 = new Cookie ("testCookie", java.net.URLEncoder.encode(str1));

// Additional protection - only send the cookie over HTTPS
//ck1.setSecure(true);
// Additional protection - do not let JavaScript access this Cookie
//ck1.setHttpOnly(true);

    slingResponse.addCookie(ck1);


// List out all of the Cookies, including decrypting our special Cookie.
    Cookie[] cookies = slingRequest.getCookies();
    if (cookies != null)
    {
        for (Cookie ck : cookies)
        {
            if ("testCookie".equals(ck.getName()))
                {
                %><p> <strong><%= ck.getName() %></strong> == <%= cryptoSupport.unprotect(java.net.URLDecoder.decode(ck.getValue())) %></p><%
                }
                else
                {
    %><p> <%= ck.getName() %> == <%= ck.getValue() %></p><%
                }
        }
    }

%>
<hr/>


1 comment:

  1. One of the biggest challenges that organizations face today is having inaccurate data and being unresponsive to the needs of the Adobe CQ5 CMS Email List organization.

    ReplyDelete