Encrypting Xml using session key

613 Views Asked by At

I have a Xml which is stored in the String. I need to encrypt it using a session key (AES and 256bit).

I am using following code to generate the key:

public byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException
{
    KeyGenerator kgen = KeyGenerator.getInstance("AES","BC");
    kgen.init(SYMMETRIC_KEY_SIZE);
    SecretKey key = kgen.generateKey();
    byte[] symmKey = key.getEncoded();
    return symmKey;
}

Using following code to encrypt data with session key:

public byte[] encryptUsingSessionKey(byte[] skey, byte[] data) throws InvalidCipherTextException
{
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESEngine(), new PKCS7Padding());

     cipher.init(true, new KeyParameter(skey));

     int outputSize = cipher.getOutputSize(data.length);

     byte[] tempOP = new byte[outputSize];
     int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
     int outputLen = cipher.doFinal(tempOP, processLen);

     byte[] result = new byte[processLen + outputLen];
     System.arraycopy(tempOP, 0, result, 0, result.length);
     return result;
}

So, I want to know, am I doing it right or wrong?

1

There are 1 best solutions below

3
On

Is the session key private, if not there is a security issue.

You are not specifying an encryption mode, it is best to be explicit.

Since there does not seem to be an iv and no mode is specified the assumption is the mode is ECB which is insecure, it is better to the CBC mode with a random iv that is prepended to the encrypted data for use during decryption.

Also missing is encryption authentication and the key generation is weak, it would be better to use a derivation function such as PBKDF2.

Do not use ECB mode, it is insecure, see ECB mode, scroll down to the Penguin.

Consider using a more complete library such as RNCryptor's JMCryptor that includes PBKDF2 key derivation, encryption authentication, random iv and versioning. Also see Specification for RNCryptor for more information.