Here is a simple class for encrypting strings. As we should all know, encryption is important, especially for things like login forms, personal user data etc. Therefore it is important that if you are storing such information either locally on the device or sending it to a remote server, you encrypt such details.
This class uses the SHA-512 hashing algorithm to convert a string into its raw bit format. This is then converted into a hex string and returned.
There are ways of making this even more secure (by adding salts etc) but this is just meant to be for a starting point
Usage:
This class uses the SHA-512 hashing algorithm to convert a string into its raw bit format. This is then converted into a hex string and returned.
There are ways of making this even more secure (by adding salts etc) but this is just meant to be for a starting point
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
private static String convertToHex(byte[] bytes) {
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);
}
public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(text.getBytes("iso-8859-1"), 0, text.length());
byte[] sha512hash = md.digest();
return convertToHex(sha512hash);
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Last edited: