0

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?

zaph
  • 111,848
  • 21
  • 189
  • 228
Mudit
  • 199
  • 2
  • 21

1 Answers1

0

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.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • Thanks for all the suggestions, I will apply them. But I also want to know that, Encryption done by above code is right or not? – Mudit Jul 13 '16 at 13:58
  • That depends on what "right or not" means? Best practice secure: No. – zaph Jul 13 '16 at 14:02
  • I wanted to encrypt XML with session key with AES and PKCS7Padding, So I want to know that encryption result from the above code can be decrypted or not ? Right now I am not concerned with security – Mudit Jul 14 '16 at 04:05