MCrypt:
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MCrypt {
private String iv = "fedcba9876543210";
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "0123456789abcdef";
public MCrypt()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] data)
{
if (data==null)
{
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
private static String padString(String source)
{
char paddingChar = ' ';
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}
return source;
}
}
Main:
mcrypt = new MCrypt();
/* Encrypt */
String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );
//Returns 9975e28df055c336a9b7090b03f88689
/* Decrypt */
String decrypted = new String( mcrypt.decrypt( encrypted ) );
//Returns "Text to Encrypt "
The problem:
String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );
Encrypt returns: 9975e28df055c336a9b7090b03f88689 (which is incorrect)
String decrypted = new String( mcrypt.decrypt( encrypted ) );
Decrypt returns: "Text to Encrypt " (which properly reflects what the encryption came up with, there is a " " after Encrypt)
I've narrowed it down to this line:
encrypted = cipher.doFinal(padString(text).getBytes());
I tried changing the padString function so that char paddingChar = 0;
instead of char paddingChar = ' ';
with no luck...
When properly encrypted "Text to Encrypt" should turn into "cb4b4ca864213684070465b38783a6c8"
AES is a block cypher. It encrypts one 256 bit block (=16 bytes) into a different 256 bit block. Your plaintext, "Text to Encrypt" is 15 characters, or 248 bits. AES cannot encrypt it as-is, but must add some padding to make it up to a full block.
If you explicitly add a padding character, then you must explicitly remove it. Each different padding character will have a large impact on the decryption. On average, changing one bit in the input plaintext block will change 50% of the bits in the output cyphertext block.
Your easiest solution is to use the buit in padding facilities in Java. You specify your cipher as: "AES/CBC/NoPadding"
. Change this to "AES/CBC/PKCS5Padding"
for both encryption and decryption. Don't worry about what the cyphertext looks like, just check that the plaintext matches the decyphered cyphertext, character for character.
A common error is to convert a text string to a byte array using getBytes()
. Don't do that, because it is error-prone. You should specify precisely what mapping you are using between characters and bytes. Use something like:
byte[] plainBytes = plaintextString.getBytes("UTF-8");
and similar at the other side. Do not rely on system defaults always being the same.