So I have a problem that I cant't seem to solve. I need to decode some Base64 text using a generated hash md5 as key. I have written this code. The output does not come out readable. The key's "freeforall"
and "validate"
are the actual ones.
Can anyone give me some light to what is wrong with this code? Or possibly with my interpretation of the problem.
private String decrypt(String data, byte[] key) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(Base64.decode(data));
return new String(original, "UTF-8").trim();
}
private byte[] getMD5(String value) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(value.getBytes("utf-8"), 0, value.length());
return md.digest();
}
public static void main(String[] args) {
String grupo0 = "r8Z48nEsKskL+9mOb9EQ519MLNjeFkcTQe3M4+XMdmkWZ+7F3o027zOwuMpyr1XQKFDSILDSUxUhAIoDW4QcnoA0um0BKs4sA/ZczucCAEjCpQmy4xR3o+xR1Ve3bNV6/X3hq98hrlCdycgEwprn8qvQRAHwpA1FqseBl2NCuo+vn5VZA0GHKnuNPiApjCMDo6qpTIELy9FB+2vWZwYprA==";
String grupoMenos1 = "fGpu3YkXGxTdVTeHhC2FZT9utUOGJgvvmPlzlEq39oSTc419ashyqmBvYGSC7BqRvXQ3Wx+i8C7jIiaBo9fXAd/JLed+T6XvlSkJfH+PGX8xi8tuD+OoLhaA102mscVSatsKtGTzOWAt17DzWeLe2QKXbClN+ElGSQaPBRD/aHpNQJNAMrUOUEgPDNjbb7HmlmOfFsCpQZOEFq+n2SOMpA==";
System.out.println(decrypt(grupo0, getMD5("freeforall")));
System.out.println(decrypt(grupoMenos1, getMD5("validate")));
}
Without being able to see the code used to do the encryption, it is not possible to determine if you are doing the right thing. I have very similar code in an Android app and it works fine. One difference is that I pass a
javax.crypto.spec.IvParameterSpec
toCipher.init()
. Also, the Android Base64 class takes a flags argument fordecode()
but I don't think that is your problem here.You also have a minor bug in your
getMD5()
function but it should not be the issue here since your keys are plain ASCII. You should use the length of the UTF-8 byte array not the length of the original string when calculating the digest.Should be:
EDIT: As James K Polk suggested, you could just do: