Gradle script for AES encryption

For an Android app, I want to obfuscate / encrypt the server public key when building with gradle.

I am now confusing the use of Base64, but I need AES as an optional

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 during the execution of 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 using AES in a gradle script? Google couldn't help me. Is this anything at all possible or do I need to find another solution?

+3


source to share


1 answer


There is a similar SO question here for encrypting a string with AES in java.

I have adopted this in the gradle script below.

It will encrypt the string SERVERKEY

(in your version, load this from an external source) with a key KEY

. I don't have BouncyCastle, so I used SunJCE, but I left it as a parameter so you can easily change it.



The output in this simple case is the obf.enc file. The task is decIt

also decoded and printed to show that it is working symmetrically.

Your hardest part is obviously the fact that yours KEY

for encryption is built into your application (hence my question in the comments), so it's 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")
}

      

+4


source







All Articles