Tuesday, April 16, 2013

Encryption and Decryption

public class SimpleCrypto {

        public static String encrypt(String seed, String cleartext) throws Exception {
                byte[] rawKey = getRawKey(seed.getBytes());
                byte[] result = encrypt(rawKey, cleartext.getBytes());
                return toHex(result);
        }
        
        public static String decrypt(String seed, String encrypted) throws Exception {
                byte[] rawKey = getRawKey(seed.getBytes());
                byte[] enc = toByte(encrypted);
                byte[] result = decrypt(rawKey, enc);
                return new String(result);
        }

        private static byte[] getRawKey(byte[] seed) throws Exception {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
                sr.setSeed(seed);
            kgen.init(128, sr); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey();
            byte[] raw = skey.getEncoded();
            return raw;
        }

        
        private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(clear);
                return encrypted;
        }

        private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decrypted = cipher.doFinal(encrypted);
                return decrypted;
        }

        public static String toHex(String txt) {
                return toHex(txt.getBytes());
        }
        public static String fromHex(String hex) {
                return new String(toByte(hex));
        }
        
        public static byte[] toByte(String hexString) {
                int len = hexString.length()/2;
                byte[] result = new byte[len];
                for (int i = 0; i < len; i++)
                        result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
                return result;
        }

        public static String toHex(byte[] buf) {
                if (buf == null)
                        return "";
                StringBuffer result = new StringBuffer(2*buf.length);
                for (int i = 0; i < buf.length; i++) {
                        appendHex(result, buf[i]);
                }
                return result.toString();
        }
        private final static String HEX = "0123456789ABCDEF";
        private static void appendHex(StringBuffer sb, byte b) {
                sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
        }
        }

google Authentication for Android Applications

public class GoogleAuthenticationWithLoginDetails {
    private final String googleLoginUrl = "https://www.google.com/accounts/ClientLogin";
    private final String service = "ah";
    private Cookie authCookie = null;

    //Constructor creates the cookie
    public GoogleAuthenticationWithLoginDetails(){
       
    }


    public boolean authenticate(String username,String password){
        boolean returnValue = false;
        String authToken = null;
        if (authCookie == null)
        {

            Log.d("authenticate", "NULL");

            try {
                authToken = GetToken(username,password);

                //authCookie = getAuthCookie(authToken);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("authenticate Exception", e.getMessage());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("authenticate Exception", e.getMessage());
            }


        }
       
        if(authToken.trim().length()>0){
            Log.d("authToken!=null","NOT NULL");
            Log.d("TOKEN=", authToken);
            returnValue =  true;
        }else{
            Log.d("authToken==null","NULL");
            returnValue =  false;
        }
        return returnValue;
    }


    private String GetToken(String googleAccount, String googlePassword) throws MalformedURLException, ProtocolException, UnsupportedEncodingException, IOException
    {
        Log.d("GetToken","Reached");
        String token = null;
        HttpURLConnection h = GetConnection(googleAccount,googlePassword);
        token= extractAuthTokenFromResponse(h);
        Log.d("GetToken",token);
        return token;
    }



    private HttpURLConnection GetConnection(String username, String password)
            throws MalformedURLException, IOException, ProtocolException,
            UnsupportedEncodingException {
        HttpURLConnection urlConnection;
        URL url = new URL(googleLoginUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        StringBuilder content = new StringBuilder();
        content.append("Email=").append(username);
        content.append("&Passwd=").append(password);
        content.append("&service=").append(service);

        OutputStream outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("UTF-8"));
        outputStream.close();
        return urlConnection;
    }
    private String extractAuthTokenFromResponse(HttpURLConnection urlConnection)
            throws IOException {
        int responseCode = urlConnection.getResponseCode();
        System.out.println(responseCode);
        StringBuffer resp = new StringBuffer();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = urlConnection.getInputStream();

            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
            String line;


            while ((line = rd.readLine()) != null) {

                if(line.startsWith("Auth="))
                {
                    resp.append(line.substring(5));

                }

            }

            rd.close();


        }
        return resp.toString();
    }
}