-1

I'm getting some packets from an stream that is encrypted with AES 128 bit standard:FIPS 179. They only gave me a 16 char string as password. In Android methods there is an IV parameter. I used the sample code in this SO thread. but data does not decrypts.

public class AESCrypt {

private final Cipher cipher;
private final SecretKeySpec key;
private AlgorithmParameterSpec spec;


public AESCrypt(String password) throws Exception
{
    // hash password with SHA-256 and crop the output to 128-bit for key
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(password.getBytes("UTF-8"));
    byte[] keyBytes = new byte[32];
    System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

    cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    key = new SecretKeySpec(keyBytes, "AES");
    spec = getIV();
}       

public AlgorithmParameterSpec getIV()
{
    byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
    IvParameterSpec ivParameterSpec;
    ivParameterSpec = new IvParameterSpec(iv);

    return ivParameterSpec;
}

public String encrypt(String plainText) throws Exception
{
    cipher.init(Cipher.ENCRYPT_MODE, key, spec);
    byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
    String encryptedText = new String(Base64.encode(encrypted, Base64.DEFAULT), "UTF-8");

    return encryptedText;
}

public String decrypt(String cryptedText) throws Exception
{
    cipher.init(Cipher.DECRYPT_MODE, key, spec);
    byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT);
    byte[] decrypted = cipher.doFinal(bytes);
    String decryptedText = new String(decrypted, "UTF-8");

    return decryptedText;
}

}
Community
  • 1
  • 1
Ahmad Behzadi
  • 1,006
  • 15
  • 30
  • *"but data does not decrypts."* What does that mean? Do you get an exception? Do you get some output? If you do, is the output length what you would expect and what is the difference between what you would expect and what you get (e.g. first 16 bytes are noise and the rest is ok)? Have you tried to use the 16 characters not as a password, but as a key directly? – Artjom B. Oct 26 '15 at 12:49
  • I get Exception : `javax.crypto.IllegalBlockSizeException: last block incomplete in decryption` – Ahmad Behzadi Oct 26 '15 at 12:54
  • Please provide a full and reproducible example with inputs, outputs and expected outputs. – Artjom B. Oct 26 '15 at 13:07

1 Answers1

0

To decrypt the data, you need to use the same Initialization Vector that was used to encrypt the data. If (and hopefully) the IV isn't always the same, it must be available from the stream somehow. If it's fixed, you need to put the same bytes in your code.

Zharf
  • 2,638
  • 25
  • 26