Skip to content

Instantly share code, notes, and snippets.

@sephiroth74
Created November 22, 2014 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sephiroth74/a17ca4f3d8463ed0f16a to your computer and use it in GitHub Desktop.
Save sephiroth74/a17ca4f3d8463ed0f16a to your computer and use it in GitHub Desktop.
Decrypt open-ssl encrypted file using android
package it.sephiroth.android.library.simpleaes;
import android.support.annotation.NonNull;
import android.util.Base64;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by alessandro on 17/11/14.
*/
public final class Crypto {
private static final String TRANSFORMATION_ALGORITHM = "AES/CBC/PKCS5Padding";
private final Cipher decryptInstance;
/**
* Generate the input text file using the command:<br/>
* <pre><code>
* $ openssl enc -nosalt -aes-128-cbc -a -in input.txt -out output.txt -p
* </code></pre>
* The output string will print something like:
* <pre><code>
* key=5F4DCC3B5AA765D61D8327DEB882CF99
* iv =2B95990A9151374ABD8FF8C5A7A0FE08
* </code></pre>
* Now convert the key and iv into bytearray and add to your java code. Given the above key and iv the result bytearrays will
* be:
* <pre><code>
* byte[] SECRET = new byte[]{95, 77, -52, 59, 90, -89, 101, -42, 29, -125, 39, -34, -72, -126, -49, -103};
* byte[] IV = new byte[]{43, -107, -103, 10, -111, 81, 55, 74, -67, -113, -8, -59, -89, -96, -2, 8};
* </code></pre>
* The key can be converted into a byte[] array using this python script:
* <pre><code>
* >>> s = "5F4DCC3B5AA765D61D8327DEB882CF99"
* >>> ",".join("{:d}".format(int(s[x:x+2],16) if int(s[x:x+2],16)<128 else int(s[x:x+2],16)-256) for x in range(0,len(s),2))
* </code></pre>
*
* @throws GeneralSecurityException
*/
public Crypto(@NonNull byte[] key, @NonNull byte[] iv) throws GeneralSecurityException {
decryptInstance = Cipher.getInstance(TRANSFORMATION_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
decryptInstance.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));
}
/**
*
* @param data
* @param inputIsBase64
* @return
* @throws GeneralSecurityException
*/
public byte[] decrypt(@NonNull byte[] data, boolean inputIsBase64) throws GeneralSecurityException {
return decryptInstance.doFinal(inputIsBase64 ? Base64.decode(data, Base64.NO_WRAP) : data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment