AES CB encryption in Android using key and salt

Here is a simple example of AES CB encryption in android using key and salt. I am not expert in encryption but I found how to do this pretty hard and I thought that maybe it will help somebody else if not , it will help me latter again :).

// decryption method
public static String decryptString(String cypher, String key, String textToDecrypt, String salt) {
        byte[] rawKey = new byte[32];
        java.util.Arrays.fill(rawKey, (byte) 0);
        byte[] keyOk = hmacSha1(salt, key);
        for (int i = 0; i < keyOk.length; i++) {
            rawKey[i] = keyOk[i];
        }
        SecretKeySpec skeySpec = new SecretKeySpec(hmacSha1(salt, key), "AES");
        try {
            Cipher cipher = Cipher.getInstance(cypher);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encryptedData = cipher.doFinal(Base64.decode(textToDecrypt, Base64.NO_CLOSE));
            if (encryptedData == null) return null;
            return new String(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
// encryption method
    public static String encryptString(String cypher, String key, String clearText, String salt) {
        byte[] rawKey = new byte[32];
        java.util.Arrays.fill(rawKey, (byte) 0);
        byte[] keyOk = hmacSha1(salt, key);
        for (int i = 0; i < keyOk.length; i++) {
            rawKey[i] = keyOk[i];
        }
        SecretKeySpec skeySpec = new SecretKeySpec(hmacSha1(salt, key), "AES");
        try {
            Cipher cipher = Cipher.getInstance(cypher);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encryptedData = cipher.doFinal(clearText.getBytes());
            if (encryptedData == null) return null;
            return Base64.encodeToString(encryptedData, Base64.NO_CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
// key generator method
    public static byte[] hmacSha1(String salt, String key) {
        SecretKeyFactory factory = null;
        Key keyByte = null;
        try {
            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec keyspec = new PBEKeySpec(key.toCharArray(), salt.getBytes(), 1024, 256);
            keyByte = factory.generateSecret(keyspec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return keyByte.getEncoded();
    }

How to use it:

String encryptedString = encryptString("AES/ECB/PKCS5padding", "yourkeyhere", password, "yoursalthere");
String decryptedString = decryptString("AES/ECB/PKCS5padding", "yourkeyhere", encryptedString, "yoursalthere")

You can print this out and see that it works. :)

Exit mobile version