I am making an Android application and I want to encrypt String before sending it to the database, and encrytpion is correct. The problem occurs when decrypting the string, because I get a BadPaddingException, and I don't know where the problem is. Here is the code:
public final static String HEX = "36A52C8FB7DF9A3F"; public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String seed, String encrypted) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } public static String toHex(String txt) { return toHex(txt.getBytes()); } public static String fromHex(String hex) { return new String(toByte(hex)); } public static byte[] toByte(String hexString) { int len = hexString.length()/2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue(); return result; } public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2*buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); kgen.init(128, sr);
I encrypt and decrypt using this code:
String encrypted = encrypt(HEX, "some text"); String decrypted = decrypt(HEX, encrypted);
Can anybody help me?
Thank you very much!
EDIT: The problem is not resolved, but I have a bit more information. First of all, I encrypt in a Java project, and I decrypt in an Android project. I tried to decrypt in the same Java project, and there is no problem, but if I try to decrypt in Android, it will not work. The problem is the getRawKey method (see kgen.generateKey () Comment):
JAVA:
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed);
ANDROID:
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed);
I am not an expert in the crypt, but how can it be possible that with the same seed I get a different key?