-2

I have a requirement to encrypt a string in java using AES algorithm and to decrypt the data in PHP. I have searched SO but I dint get any exact answer.

In some posts, they used Padding. And also they spoke about the key size.

But, I don't have any idea about the key size and what padding I should use.

So please help me by posting some sample code and explanations to understand better.

Thanks in advance!!

Mohammad Dayyan
  • 21,578
  • 41
  • 164
  • 232
vinoth
  • 23
  • 3
  • Welcome to SO. Please add some code that you have tried so far. – Abhi Jan 23 '16 at 14:35
  • You should post some example code ([Minimal, Complete, Verifiable Example](https://stackoverflow.com/help/mcve) or a [Short, Self-Contained, Correct Example](http://sscce.org/)). Include what you've already tried and where exactly you're stuck. See more info at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) Thanks! – Will Jan 24 '16 at 03:37

1 Answers1

2

The key size is not important, any of the available sizes are secure.

AES is a block cipher, that means that input must be a multiple of the block size: 16-bytes. Unless the input is always a multiple of the block size padding will be required.

The standard padding for AES is PKCS#7 (sometimes stated PKCS#5). The problem is PHP and the usual mcrypt library used, it does not support PKCS#7 padding, only null padding and can not be used with binary data. The bozo maintainers refuse to add PKCS#7 padding. You will have to add your own PKCS#7 padding support if you use mcrypt, it is not hard, generally three lines of code.

But there are more issues. The encryption mode and CBC mode requires an iv which should be random data. Authentication to determine if the decrypted data is correct. The key should not be a string, if it is it should be used to derive a key with a function such as PBKDF2.

I suggest using RNCryptor which is available for Java, php and many other languages. It provided all the necessary elements to create secure encryption including: AES-256 encryption,CBC mode, password stretching with PBKDF2, password salting, random IV, encrypt-then-hash HMAC authentication, and versioning.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
zaph
  • 111,848
  • 21
  • 189
  • 228