Search code examples
javaencryptiondropboxsecret-key

How to have a constant initialization vector and secret key in java?


I'm trying to decrypt an access token (it's a String), which is used to default access an Dropbox account and uploading files into it. So right now, I always need that access token to make file uploadings.

Until now, I've been generating a new initialization vector (IV) and a new secret key to encrypt and decrypt the access token. However, I want to store these two in the source code, as constant variables/attributes. The reason why I want them to remain the same ? Because I will give a crypted access token (always the same encoded one) to the users, and the app should keep the IV and the secret key inside the source code.

How can I store them in my source code ?

I tried to write the string values of the IV and of the secret key in files. I use the string from the files, and I assign the string values to string constants in my code. Then i use my constants to create byte arrays for converting into the IV and into the secret key. I'm not sure if this will work yet, it's still in development.


Solution

  • You'd better heed the advice. Storing the key is bad but can sometimes be defended if no other options are available. There is however generally no reason to use a static IV. You can just prefix the IV (which is 16 bytes for most modes of operation) to the ciphertext instead.

    Anyway, to store them as static values, just take a look at the following code; note that you should generate them as random values in advance, not the static values you're seeing here:

    private static final byte[] KEY_DATA = {
        (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
        (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
        (byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B,
        (byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F,
    };
    
    private static final byte[] IV_DATA = {
        (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
        (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
        (byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B,
        (byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F,
    };
    
    public static void main(String[] args) throws Exception {
        Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
        SecretKey key = new SecretKeySpec(KEY_DATA, "aes");
        IvParameterSpec iv = new IvParameterSpec(IV_DATA);
    
        aes.init(Cipher.ENCRYPT_MODE, key, iv);
    
        ...
    }
    

    Note that SecretKeySpec implements the interface SecretKey for easy usage.