Created
November 7, 2017 10:46
-
-
Save perry-mitchell/c95c70544086f58d94ce13ed6a675bbe to your computer and use it in GitHub Desktop.
Encrypt a string in Java for Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String encryptText(String text, String keyHex, String saltHex, String hmacHexKey) { | |
String ivHex = generateIV(); | |
byte[] ivData = BCHelpers.hexStringToByteArray(ivHex); | |
byte[] keyData = BCHelpers.hexStringToByteArray(keyHex); | |
byte[] hmacKeyData = BCHelpers.hexStringToByteArray(hmacHexKey); | |
IvParameterSpec iv = new IvParameterSpec(ivData); | |
SecretKeySpec skeySpec = new SecretKeySpec(keyData, "AES"); | |
try { | |
// AES encryption | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); | |
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); | |
byte[] encrypted = cipher.doFinal(text.getBytes()); | |
byte[] encodedEncryptedText = Base64.encode(encrypted); | |
String encryptedText = new String(encodedEncryptedText); | |
// HMAC | |
Mac sha256HMAC = Mac.getInstance("HmacSHA256"); | |
SecretKeySpec hmacSecretKey = new SecretKeySpec(hmacKeyData, "HmacSHA256"); | |
sha256HMAC.init(hmacSecretKey); | |
String hmacTarget = encryptedText + ivHex + saltHex; | |
byte[] hmacData = sha256HMAC.doFinal(hmacTarget.getBytes(StandardCharsets.UTF_8)); | |
String hmacHex = BCHelpers.byteArrayToHexString(hmacData); | |
// Output | |
return encryptedText + "|" + hmacHex + "|" + ivHex + "|" + saltHex; | |
} catch (Exception ex) { | |
return "Error:" + ex.getMessage(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment