For an Android app I want to obfuscate/encrypt the server public key when building with gradle.
Right now I'm obfuscating using Base64 but I need AES as an extra
task encryptKeys {
doFirst {
//Encrypt the server key
// Load key
byte[] key = new File('project/keys/server.crt.der').bytes
// Encode key twice
String encoded = key.encodeBase64().toString();
encoded = encoded.bytes.encodeBase64().toString();
//TODO AES ENCRYPTION HERE
// Save key
new File('project/src/main/assets/server.crt.der').bytes = encoded.getBytes()
Later at runtime when using this key i would decrypt it like this
public static String decrypt(byte[] cipherText) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(cipher.doFinal(cipherText),"UTF-8");
}
What would be the correct way to encrypt my key with AES in gradle script? Google couldn't help me out. Is this something that's possible at all or would I need to find another solution?
There's a similar SO question here for encrypting a string with AES in java.
I've adopted this into a gradle script below.
It will encrypt the SERVERKEY string (in your version load this from external source) with the key KEY. I don't have BouncyCastle installed, so I used SunJCE, but I left it as a parameter so you can change it easily.
The output in this simple case is the file "obf.enc". The decIt task will also decrypt and print out to show it's worked symmetrically.
Your hardest part is obviously the fact your KEY for encrypting is embedded in your application (hence my question in the comments), so this is just security through obscurity, but if that's good enough for the application, so be it.
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import javax.crypto.Cipher
ext {
KEY = "mysecretkey".padRight(16).getBytes("UTF-8")
SERVERKEY = "serverkey"
IV = "1234".padRight(16).getBytes("UTF-8")
PROVIDER = "SunJCE"
}
task encIt << {
SecretKeySpec key = new SecretKeySpec(KEY, "AES")
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", PROVIDER)
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV))
def encBytes = cipher.doFinal(SERVERKEY.bytes)
def out = file('obf.enc')
out.delete()
out << encBytes
}
task decIt << {
def cipherText = file('obf.enc').bytes
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", PROVIDER)
SecretKeySpec key = new SecretKeySpec(KEY, "AES")
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV))
println new String(cipher.doFinal(cipherText), "UTF-8")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With