Attend XDA's Second Annual Developer Conference, XDA:DevCon 2014!
5,731,757 Members 48,833 Now Online
XDA Developers Android and Mobile Development Forum

More secure encryption class using salt

Tip us?
(Last edited by Jonny; 10th June 2014 at 10:43 AM.)
Jonny's Avatar
Forum Moderator - OP
Thanks Meter 7817
Posts: 7,826
Join Date: Jul 2011
Location: Cheshire

Phone More secure encryption class using salt

Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.

Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc

Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.

public class Crypto {
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        String salt = getSalt(context);
        byte[] bytes = md.digest(string.getBytes());
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        return new String(hexChars);

    private static String getSalt(Context context) throws NoSuchAlgorithmException {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String salt = preferences.getString("salt", null);
        if (salt == null) {
            byte[] saltBytes = new byte[20];
            salt = new String(saltBytes);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("salt", salt).commit();
        return salt;

String example = "example";
try {
    example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
The Following 20 Users Say Thank You to Jonny For This Useful Post: [ Click to Expand ]
sybiload's Avatar
Recognized Developer
Thanks Meter 930
Posts: 477
Join Date: Apr 2012
Location: /dev/null

Thanks for sharing, it's quite usefull ! I will include it to my project
encryption, hashing, salt, security, sha512
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes