Wednesday, March 4, 2015

Password Encrypt in JavaScript and Decrypt in Java

 
here is the steps,

1. create two jsps. [ login.jsp, validate.jsp ]
2. create one java.
3. Add cryptojs lib [ aes.js ] in your javascript path and mentioned in login.jsp.

here is the sample code.


1. login.jsp

<%@page import="java.util.Arrays"%>
<%@page import="com.gnax.sdex.soa.distributable.common.SdexSecurity"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
  
<%
    session.setAttribute ( "RANDKEY", SdexSecurity.generateSecret (  ) );
%>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="/./js/rollups/aes.js"></script>
<script src="/./js/rollups/pbkdf2.js"></script>
<script type="text/javascript">
    function convertAndSubmit()
    {
         var salt = CryptoJS.lib.WordArray.random(128/8);
        var iv = CryptoJS.lib.WordArray.random(128/8);          
        //console.log('salt  '+ salt );
        //console.log('iv  '+ iv );
        var key128Bits100Iterations = CryptoJS.PBKDF2( '<%=session.getAttribute ( "RANDKEY" ) %>', salt, { keySize: 128/32, iterations: 100 });
        //console.log( 'key128Bits100Iterations '+ key128Bits100Iterations);
        var encrypted = CryptoJS.AES.encrypt(document.login.password.value, key128Bits100Iterations, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7  });
        document.login.salt.value = salt;
        document.login.iv.value = iv;
        document.login.password.value = encrypted;
        document.login.submit();
    }
</script>
</head>
<body>
    <form action="validate.jsp" method="post" name="login" autocomplete="off">
        <p>User Name : <input type="text" name="userName"/></p>
        <p>
                       <input type="text" style="display:none;">
            Password : <input type="password" name="password"/>
        </p>
        <p>
            <input type="hidden" name="salt"/>
            <input type="hidden" name="iv"/>
            <input type="button" value="Login" onclick="javascript:convertAndSubmit()"/>
        </p>
    </form>
</body>
</html>










   

        User Name :

       
                      
            Password :
       

       
           
           
           
       

   


2. validate.jsp


<%@page import="java.util.Arrays"%>
<%@page import="com.gnax.sdex.soa.distributable.common.SdexSecurity"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
    <%
        out.println ("<br/>Encrypted Password     :    " + request.getParameter("password"));
        out.println ("<br/>Salt                 :    " + request.getParameter("salt"));
        out.println ("<br/>IV                     :    " + request.getParameter("iv"));
        out.println ("<br/>Key                 :    " + session.getAttribute ( "RANDKEY" ) );
        out.println ("<br/>Original Password     :    " + SdexSecurity.decryptAESEncryptWithSaltAndIV(request.getParameter("password"), session.getAttribute ( "RANDKEY" ).toString (  ), request.getParameter("salt"), request.getParameter("iv") ) );   
    %>
</body>
</html>






    <%
        out.println ("
Encrypted Password     :    " + request.getParameter("password"));
        out.println ("
Salt                 :    " + request.getParameter("salt"));
        out.println ("
IV                     :    " + request.getParameter("iv"));
        out.println ("
Key                 :    " + session.getAttribute ( "RANDKEY" ) );
        out.println ("
Original Password     :    " + YourJava.decryptAESEncryptWithSaltAndIV(request.getParameter("password"), session.getAttribute ( "RANDKEY" ).toString (  ), request.getParameter("salt"), request.getParameter("iv") ) );   
    %>

3. yourjava.java [add the below methods ]

/**
     * Hex string to byte array.
     *
     * @param s the s
     * @return the byte[]
     */
    public static byte [] hexStringToByteArray ( String s )
    {
        int len = s.length ();
        byte [] data = new byte[len / 2];
        for ( int i = 0; i < len; i += 2 )
        {
            data[i / 2] = (byte) ( ( Character.digit ( s.charAt ( i ), 16 ) << 4 ) + Character.digit ( s.charAt ( i + 1 ), 16 ) );
        }
        return data;
    }

   
    /**
     * Generate key from password with salt.
     *
     * @param password the password
     * @param saltBytes the salt bytes
     * @return the secret key
     * @throws GeneralSecurityException the general security exception
     */
    public static SecretKey generateKeyFromPasswordWithSalt ( String password, byte [] saltBytes ) throws GeneralSecurityException
    {
        KeySpec keySpec = new PBEKeySpec ( password.toCharArray (), saltBytes, 100, 128 );
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ( PBKDF2_WITH_HMAC_SHA1 );
        SecretKey secretKey = keyFactory.generateSecret ( keySpec );

        return new SecretKeySpec ( secretKey.getEncoded (), AES );
    }

    /**
     * Decrypt aes encrypt with salt and iv.
     *
     * @param encryptedData the encrypted data
     * @param key the key
     * @param salt the salt
     * @param iv the iv
     * @return the string
     * @throws Exception the exception
     */
    public static String decryptAESEncryptWithSaltAndIV ( String encryptedData, String key, String salt, String iv ) throws Exception
    {

        byte [] saltBytes = hexStringToByteArray ( salt );
        byte [] ivBytes = hexStringToByteArray ( iv );
        IvParameterSpec ivParameterSpec = new IvParameterSpec ( ivBytes );
        SecretKeySpec sKey = (SecretKeySpec) generateKeyFromPasswordWithSalt ( key, saltBytes );

        Cipher c = Cipher.getInstance ( AES_CBC_PKCS5_PADDING );
        c.init ( Cipher.DECRYPT_MODE, sKey, ivParameterSpec );
        byte [] decordedValue = new BASE64Decoder ().decodeBuffer ( encryptedData );
        byte [] decValue = c.doFinal ( decordedValue );
        String decryptedValue = new String ( decValue );

        return decryptedValue;
    }

public String generateSecret (  )
{
    return "1234455553dsfdfdsfdsf";   //generate always random number and send for each request
}

 // enjoy madi.


Licenced :-

    IBM appscan,  (Secureyes are using this)

Open Source:-

Netsparker Community Edition (Windows)

Websecurify (Windows, Linux, Mac OS X)

Wapiti (Windows, Linux, Mac OS X)

N-Stalker Free Version (Windows)

skipfish (Windows, Linux, Mac OS X)

Scrawlr (Windows)

Watcher (Windows)

 

Why to go for OWASP ? 
Pasted from www.owasp.org

A1-Injection

 

Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.


A2-Broken Authentication and Session Management

 

Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities.


A3-Cross-Site Scripting (XSS)

 

XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.


A4-Insecure Direct Object References

 

A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.


A5-Security Misconfiguration

 

Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date.


A6-Sensitive Data Exposure

 

Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.


A7-Missing Function Level Access Control

 

Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization.


A8-Cross-Site Request Forgery (CSRF)

 

A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.


A9-Using Components with Known Vulnerabilities

 

Components, such as libraries, frameworks, and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts.


A10-Unvalidated Redirects and Forwards

 

Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

 

Fraud Detection

Data preprocessing techniques for detection, validation, error correction, and filling up of missing or incorrect data.
    • Calculation of various statistical parameters such as averages, quantiles, performance metrics, probability distributions, and so on. For example, the averages may include average length of call, average number of calls per month and average delays in bill payment.
    • Models and probability distributions of various business activities either in terms of various parameters or probability distributions.
    • Computing user profiles.
    • Time-series analysis of time-dependent data.
    • Clustering and classification to find patterns and associations among groups of data.
    • Matching algorithms to detect anomalies in the behavior of transactions or users as compared to previously known models and profiles. Techniques are also needed to eliminate false alarms, estimate risks, and predict future of current transactions or users.

 

Let you get more details from :

http://en.wikipedia.org/wiki/Data_Analysis_Techniques_for_Fraud_Detection

http://horicky.blogspot.in/2011/07/fraud-detection-methods.html

 

For banking

http://www.sqnbankingsystems.com/

 

For insurance

http://www.capterra.com/insurance-fraud-detection-software

SimpleCaptcha


Installing SimpleCaptcha is no different than installing most other libraries for a J2EE container: a jar is deployed to WEB-INF/lib and web.xml is updated. These steps are described in detail below.

1. Download SimpleCaptcha
2. Copy the jar file to your WEB-INF/lib directory
3. Add a mapping to web.xml. There are three servlets provided out of the box: StickyCaptchaServlet, SimpleCaptchaServlet, and ChineseCaptchaServlet. All generate CAPTCHA image/answer pairs, but StickyCaptchaServlet and ChineseCaptchaServlet are “sticky” to the user’s session: page reloads will render the same CAPTCHA instead of generating a new one. An example mapping for StickyCaptchaServlet:

<servlet>
<servlet-name>StickyCaptcha</servlet-name>
<servlet-class>nl.captcha.servlet.StickyCaptchaServlet</servlet-class>
<init-param>
<param-name>width</param-name>
<param-value>250</param-value>
</init-param>
<init-param>
<param-name>height</param-name>
<param-value>75</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>StickyCaptcha</servlet-name>
<url-pattern>/stickyImg</url-pattern>
</servlet-mapping>


The width and height parameters are optional; if unprovided the image will default to 200×50.

4. Restart your webserver.
5. Browse to the location given by the url-pattern defined in web.xml, e.g., http://localhost:8080/stickyImg. If everything has been set up correctly you should see a CAPTCHA image.
6. Now create a JSP called captcha.jsp. Add the following code inside the <body> element:

<img src="/stickyImg" />
<form action="/captchaSubmit.jsp" method="post">
<input name="answer" />
</form>

7. Create another JSP called captchaSubmit.jsp. Add the following:

<%@ page import="nl.captcha.Captcha" %>
...
<% // We're doing this in a JSP here, but in your own app you'll want to put
// this logic in your MVC framework of choice.
Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
request.setCharacterEncoding("UTF-8"); // Do this so we can capture non-Latin chars
String answer = request.getParameter("answer");
if (captcha.isCorrect(answer)) { %>
<b>Correct!</b>
<% } %>


8. Browse to /captcha.jsp. You should get your CAPTCHA image, as well as a form for entering your answer. Submit the form and see what happens.

Secure Issues Handling