I have a reference of PHP code that does Rijndael encryption. I want convert it to java code, I tried few examples but none of them worked for me. Here is the php code:
$initialisationVector = hash("sha256", utf8_encode($myiv), TRUE);
$key = hash("sha256", utf8_encode($mykey), TRUE);
$encryptedValue = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$encryptKey, utf8_encode($mydata), MCRYPT_MODE_CBC, $initialisationVector));
Here is my java code that throws: Key length not 128/160/192/224/256 bits
public static String encrypt() throws Exception{
String myiv = "somevalue";
String mykey = "somevalue";
String mydata = "somevalue";
String new_text = "";
RijndaelEngine rijndael = new RijndaelEngine(256);
CBCBlockCipher cbc_rijndael = new CBCBlockCipher(rijndael);
ZeroBytePadding c = new ZeroBytePadding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbc_rijndael, c);
byte[] iv_byte = sha256(myiv);
byte[] givenKey = sha256(mykey);
CipherParameters keyWithIV = new ParametersWithIV(new KeyParameter(givenKey), iv_byte);
pbbc.init(true, keyWithIV);
byte[] plaintext = mydata.getBytes(Charset.forName("UTF-8"));
byte[] ciphertext = new byte[pbbc.getOutputSize(plaintext.length)];
int offset = 0;
offset += pbbc.processBytes(plaintext, 0, plaintext.length, ciphertext, offset);
offset += pbbc.doFinal(ciphertext, offset);
new_text = new String(new Base64().encode(ciphertext), Charset.forName("UTF-8"));
System.out.println(new_text);
return new_text;
}
public static byte[] sha256(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] messageDigest = md.digest(input.getBytes(Charset.forName("UTF-8")));
return messageDigest;
}
I am not really good with cryptography. Thanks in advance!
input.getBytes()
should beinput.getBytes(Charset.forName("UTF-8"))
– President James K. Polksha256(appId)
provides a 256-bit key, just use it.final int keysize = 256;
byte[] keyData = new byte[keysize];
System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
are not needed. – zaph